index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
52,104 |
pebble.pool.base_pool
|
MapFuture
| null |
class MapFuture(PebbleFuture):
def __init__(self, futures: list):
super().__init__()
self._futures = futures
@property
def futures(self) -> list:
return self._futures
def cancel(self) -> bool:
"""Cancel the future.
Returns True if any of the elements of the iterables is cancelled.
False otherwise.
"""
super().cancel()
return any(tuple(f.cancel() for f in self._futures))
|
(futures: list)
|
52,105 |
concurrent.futures._base
|
__get_result
| null |
def __get_result(self):
if self._exception:
try:
raise self._exception
finally:
# Break a reference cycle with the exception in self._exception
self = None
else:
return self._result
|
(self)
|
52,106 |
pebble.pool.base_pool
|
__init__
| null |
def __init__(self, futures: list):
super().__init__()
self._futures = futures
|
(self, futures: list)
|
52,107 |
concurrent.futures._base
|
__repr__
| null |
def __repr__(self):
with self._condition:
if self._state == FINISHED:
if self._exception:
return '<%s at %#x state=%s raised %s>' % (
self.__class__.__name__,
id(self),
_STATE_TO_DESCRIPTION_MAP[self._state],
self._exception.__class__.__name__)
else:
return '<%s at %#x state=%s returned %s>' % (
self.__class__.__name__,
id(self),
_STATE_TO_DESCRIPTION_MAP[self._state],
self._result.__class__.__name__)
return '<%s at %#x state=%s>' % (
self.__class__.__name__,
id(self),
_STATE_TO_DESCRIPTION_MAP[self._state])
|
(self)
|
52,108 |
concurrent.futures._base
|
_invoke_callbacks
| null |
def _invoke_callbacks(self):
for callback in self._done_callbacks:
try:
callback(self)
except Exception:
LOGGER.exception('exception calling callback for %r', self)
|
(self)
|
52,109 |
concurrent.futures._base
|
add_done_callback
|
Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called by a thread in the same process in which
it was added. If the future has already completed or been
cancelled then the callable will be called immediately. These
callables are called in the order that they were added.
|
def add_done_callback(self, fn):
"""Attaches a callable that will be called when the future finishes.
Args:
fn: A callable that will be called with this future as its only
argument when the future completes or is cancelled. The callable
will always be called by a thread in the same process in which
it was added. If the future has already completed or been
cancelled then the callable will be called immediately. These
callables are called in the order that they were added.
"""
with self._condition:
if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
self._done_callbacks.append(fn)
return
try:
fn(self)
except Exception:
LOGGER.exception('exception calling callback for %r', self)
|
(self, fn)
|
52,110 |
pebble.pool.base_pool
|
cancel
|
Cancel the future.
Returns True if any of the elements of the iterables is cancelled.
False otherwise.
|
def cancel(self) -> bool:
"""Cancel the future.
Returns True if any of the elements of the iterables is cancelled.
False otherwise.
"""
super().cancel()
return any(tuple(f.cancel() for f in self._futures))
|
(self) -> bool
|
52,111 |
concurrent.futures._base
|
cancelled
|
Return True if the future was cancelled.
|
def cancelled(self):
"""Return True if the future was cancelled."""
with self._condition:
return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]
|
(self)
|
52,112 |
concurrent.futures._base
|
done
|
Return True if the future was cancelled or finished executing.
|
def done(self):
"""Return True if the future was cancelled or finished executing."""
with self._condition:
return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]
|
(self)
|
52,113 |
concurrent.futures._base
|
exception
|
Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout.
|
def exception(self, timeout=None):
"""Return the exception raised by the call that the future represents.
Args:
timeout: The number of seconds to wait for the exception if the
future isn't done. If None, then there is no limit on the wait
time.
Returns:
The exception raised by the call that the future represents or None
if the call completed without raising.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout.
"""
with self._condition:
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self._exception
self._condition.wait(timeout)
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self._exception
else:
raise TimeoutError()
|
(self, timeout=None)
|
52,114 |
concurrent.futures._base
|
result
|
Return the result of the call that the future represents.
Args:
timeout: The number of seconds to wait for the result if the future
isn't done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout.
Exception: If the call raised then that exception will be raised.
|
def result(self, timeout=None):
"""Return the result of the call that the future represents.
Args:
timeout: The number of seconds to wait for the result if the future
isn't done. If None, then there is no limit on the wait time.
Returns:
The result of the call that the future represents.
Raises:
CancelledError: If the future was cancelled.
TimeoutError: If the future didn't finish executing before the given
timeout.
Exception: If the call raised then that exception will be raised.
"""
try:
with self._condition:
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self.__get_result()
self._condition.wait(timeout)
if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
raise CancelledError()
elif self._state == FINISHED:
return self.__get_result()
else:
raise TimeoutError()
finally:
# Break a reference cycle with the exception in self._exception
self = None
|
(self, timeout=None)
|
52,115 |
concurrent.futures._base
|
running
|
Return True if the future is currently executing.
|
def running(self):
"""Return True if the future is currently executing."""
with self._condition:
return self._state == RUNNING
|
(self)
|
52,116 |
concurrent.futures._base
|
set_exception
|
Sets the result of the future as being the given exception.
Should only be used by Executor implementations and unit tests.
|
def set_exception(self, exception):
"""Sets the result of the future as being the given exception.
Should only be used by Executor implementations and unit tests.
"""
with self._condition:
if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
raise InvalidStateError('{}: {!r}'.format(self._state, self))
self._exception = exception
self._state = FINISHED
for waiter in self._waiters:
waiter.add_exception(self)
self._condition.notify_all()
self._invoke_callbacks()
|
(self, exception)
|
52,117 |
concurrent.futures._base
|
set_result
|
Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.
|
def set_result(self, result):
"""Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.
"""
with self._condition:
if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
raise InvalidStateError('{}: {!r}'.format(self._state, self))
self._result = result
self._state = FINISHED
for waiter in self._waiters:
waiter.add_result(self)
self._condition.notify_all()
self._invoke_callbacks()
|
(self, result)
|
52,118 |
pebble.common
|
set_running_or_notify_cancel
|
Mark the future as running or process any cancel notifications.
Should only be used by Executor implementations and unit tests.
If the future has been cancelled (cancel() was called and returned
True) then any threads waiting on the future completing (though calls
to as_completed() or wait()) are notified and False is returned.
If the future was not cancelled then it is put in the running state
(future calls to running() will return True) and True is returned.
This method should be called by Executor implementations before
executing the work associated with this future. If this method returns
False then the work should not be executed.
Returns:
False if the Future was cancelled, True otherwise.
Raises:
RuntimeError: if set_result() or set_exception() was called.
|
def set_running_or_notify_cancel(self):
"""Mark the future as running or process any cancel notifications.
Should only be used by Executor implementations and unit tests.
If the future has been cancelled (cancel() was called and returned
True) then any threads waiting on the future completing (though calls
to as_completed() or wait()) are notified and False is returned.
If the future was not cancelled then it is put in the running state
(future calls to running() will return True) and True is returned.
This method should be called by Executor implementations before
executing the work associated with this future. If this method returns
False then the work should not be executed.
Returns:
False if the Future was cancelled, True otherwise.
Raises:
RuntimeError: if set_result() or set_exception() was called.
"""
with self._condition:
if self._state == CANCELLED:
self._state = CANCELLED_AND_NOTIFIED
for waiter in self._waiters:
waiter.add_cancelled(self)
return False
elif self._state == PENDING:
self._state = RUNNING
return True
else:
raise RuntimeError('Future in unexpected state')
|
(self)
|
52,119 |
pebble.common
|
ProcessExpired
|
Raised when process dies unexpectedly.
|
class ProcessExpired(OSError):
"""Raised when process dies unexpectedly."""
def __init__(self, msg, code=0):
super(ProcessExpired, self).__init__(msg)
self.exitcode = code
|
(msg, code=0)
|
52,120 |
pebble.common
|
__init__
| null |
def __init__(self, msg, code=0):
super(ProcessExpired, self).__init__(msg)
self.exitcode = code
|
(self, msg, code=0)
|
52,121 |
pebble.common
|
ProcessFuture
| null |
class ProcessFuture(PebbleFuture):
def cancel(self):
"""Cancel the future.
Returns True if the future was cancelled, False otherwise. A future
cannot be cancelled if it has already completed.
"""
with self._condition:
if self._state == FINISHED:
return False
if self._state in (CANCELLED, CANCELLED_AND_NOTIFIED):
return True
self._state = CANCELLED
self._condition.notify_all()
self._invoke_callbacks()
return True
|
()
|
52,123 |
concurrent.futures._base
|
__init__
|
Initializes the future. Should not be called by clients.
|
def __init__(self):
"""Initializes the future. Should not be called by clients."""
self._condition = threading.Condition()
self._state = PENDING
self._result = None
self._exception = None
self._waiters = []
self._done_callbacks = []
|
(self)
|
52,127 |
pebble.common
|
cancel
|
Cancel the future.
Returns True if the future was cancelled, False otherwise. A future
cannot be cancelled if it has already completed.
|
def cancel(self):
"""Cancel the future.
Returns True if the future was cancelled, False otherwise. A future
cannot be cancelled if it has already completed.
"""
with self._condition:
if self._state == FINISHED:
return False
if self._state in (CANCELLED, CANCELLED_AND_NOTIFIED):
return True
self._state = CANCELLED
self._condition.notify_all()
self._invoke_callbacks()
return True
|
(self)
|
52,136 |
pebble.pool.base_pool
|
ProcessMapFuture
| null |
class ProcessMapFuture(ProcessFuture):
def __init__(self, futures: list):
super().__init__()
self._futures = futures
@property
def futures(self) -> list:
return self._futures
def cancel(self) -> bool:
"""Cancel the future.
Returns True if any of the elements of the iterables is cancelled.
False otherwise.
"""
super().cancel()
return any(tuple(f.cancel() for f in self._futures))
|
(futures: list)
|
52,151 |
pebble.pool.process
|
ProcessPool
|
Allows to schedule jobs within a Pool of Processes.
max_workers is an integer representing the amount of desired process workers
managed by the pool.
If max_tasks is a number greater than zero,
each worker will be restarted after performing an equal amount of tasks.
initializer must be callable, if passed, it will be called
every time a worker is started, receiving initargs as arguments.
|
class ProcessPool(BasePool):
"""Allows to schedule jobs within a Pool of Processes.
max_workers is an integer representing the amount of desired process workers
managed by the pool.
If max_tasks is a number greater than zero,
each worker will be restarted after performing an equal amount of tasks.
initializer must be callable, if passed, it will be called
every time a worker is started, receiving initargs as arguments.
"""
def __init__(self, max_workers: int = multiprocessing.cpu_count(),
max_tasks: int = 0,
initializer: Callable = None,
initargs: list = (),
context: multiprocessing.context.BaseContext = None):
super().__init__(max_workers, max_tasks, initializer, initargs)
mp_context = multiprocessing if context is None else context
self._pool_manager = PoolManager(self._context, mp_context)
self._task_scheduler_loop = None
self._pool_manager_loop = None
self._message_manager_loop = None
def _start_pool(self):
with self._context.state_mutex:
if self._context.state == CREATED:
self._pool_manager.start()
self._task_scheduler_loop = launch_thread(
None, task_scheduler_loop, True, self._pool_manager)
self._pool_manager_loop = launch_thread(
None, pool_manager_loop, True, self._pool_manager)
self._message_manager_loop = launch_thread(
None, message_manager_loop, True, self._pool_manager)
self._context.state = RUNNING
def _stop_pool(self):
if self._pool_manager_loop is not None:
self._pool_manager_loop.join()
self._pool_manager.stop()
if self._task_scheduler_loop is not None:
self._task_scheduler_loop.join()
if self._message_manager_loop is not None:
self._message_manager_loop.join()
def schedule(self, function: Callable,
args: list = (),
kwargs: dict = {},
timeout: float = None) -> ProcessFuture:
"""Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
*timeout* is an integer, if expires the task will be terminated
and *Future.result()* will raise *TimeoutError*.
A *pebble.ProcessFuture* object is returned.
"""
self._check_pool_state()
future = ProcessFuture()
payload = TaskPayload(function, args, kwargs)
task = Task(next(self._task_counter), future, timeout, payload)
self._context.task_queue.put(task)
return future
def submit(self, function: Callable,
timeout: Optional[float],
*args, **kwargs) -> ProcessFuture:
"""This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
"""
return self.schedule(
function, args=args, kwargs=kwargs, timeout=timeout)
def map(self, function: Callable,
*iterables, **kwargs) -> ProcessMapFuture:
"""Computes the *function* using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
*timeout* is an integer, if expires the task will be terminated
and the call to next will raise *TimeoutError*.
The *timeout* is applied to each chunk of the iterable.
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function.
A *pebble.ProcessFuture* object is returned.
"""
self._check_pool_state()
timeout = kwargs.get('timeout')
chunksize = kwargs.get('chunksize', 1)
if chunksize < 1:
raise ValueError("chunksize must be >= 1")
futures = [self.schedule(
process_chunk, args=(function, chunk), timeout=timeout)
for chunk in iter_chunks(chunksize, *iterables)]
return map_results(ProcessMapFuture(futures), timeout)
|
(max_workers: int = 60, max_tasks: int = 0, initializer: Callable = None, initargs: list = (), context: multiprocessing.context.BaseContext = None)
|
52,153 |
pebble.pool.base_pool
|
__exit__
| null |
def __exit__(self, *args):
self.close()
self.join()
|
(self, *args)
|
52,154 |
pebble.pool.process
|
__init__
| null |
def __init__(self, max_workers: int = multiprocessing.cpu_count(),
max_tasks: int = 0,
initializer: Callable = None,
initargs: list = (),
context: multiprocessing.context.BaseContext = None):
super().__init__(max_workers, max_tasks, initializer, initargs)
mp_context = multiprocessing if context is None else context
self._pool_manager = PoolManager(self._context, mp_context)
self._task_scheduler_loop = None
self._pool_manager_loop = None
self._message_manager_loop = None
|
(self, max_workers: int = 60, max_tasks: int = 0, initializer: Optional[Callable] = None, initargs: list = (), context: Optional[multiprocessing.context.BaseContext] = None)
|
52,155 |
pebble.pool.base_pool
|
_check_pool_state
| null |
def _check_pool_state(self):
self._update_pool_state()
if self._context.state == ERROR:
raise RuntimeError('Unexpected error within the Pool')
elif self._context.state != RUNNING:
raise RuntimeError('The Pool is not active')
|
(self)
|
52,156 |
pebble.pool.process
|
_start_pool
| null |
def _start_pool(self):
with self._context.state_mutex:
if self._context.state == CREATED:
self._pool_manager.start()
self._task_scheduler_loop = launch_thread(
None, task_scheduler_loop, True, self._pool_manager)
self._pool_manager_loop = launch_thread(
None, pool_manager_loop, True, self._pool_manager)
self._message_manager_loop = launch_thread(
None, message_manager_loop, True, self._pool_manager)
self._context.state = RUNNING
|
(self)
|
52,157 |
pebble.pool.process
|
_stop_pool
| null |
def _stop_pool(self):
if self._pool_manager_loop is not None:
self._pool_manager_loop.join()
self._pool_manager.stop()
if self._task_scheduler_loop is not None:
self._task_scheduler_loop.join()
if self._message_manager_loop is not None:
self._message_manager_loop.join()
|
(self)
|
52,158 |
pebble.pool.base_pool
|
_update_pool_state
| null |
def _update_pool_state(self):
if self._context.state == CREATED:
self._start_pool()
for loop in self._loops:
if not loop.is_alive():
self._context.state = ERROR
|
(self)
|
52,159 |
pebble.pool.base_pool
|
_wait_queue_depletion
| null |
def _wait_queue_depletion(self, timeout: Optional[float]):
tick = time.time()
while self.active:
if timeout is not None and time.time() - tick > timeout:
raise TimeoutError("Tasks are still being executed")
elif self._context.task_queue.unfinished_tasks:
time.sleep(SLEEP_UNIT)
else:
return
|
(self, timeout: Optional[float])
|
52,160 |
pebble.pool.base_pool
|
close
|
Closes the Pool preventing new tasks from being accepted.
Pending tasks will be completed.
|
def close(self):
"""Closes the Pool preventing new tasks from being accepted.
Pending tasks will be completed.
"""
self._context.state = CLOSED
|
(self)
|
52,161 |
pebble.pool.base_pool
|
join
|
Joins the pool waiting until all workers exited.
If *timeout* is set, it block until all workers are done
or raises TimeoutError.
|
def join(self, timeout: float = None):
"""Joins the pool waiting until all workers exited.
If *timeout* is set, it block until all workers are done
or raises TimeoutError.
"""
if self._context.state == RUNNING:
raise RuntimeError('The Pool is still running')
if self._context.state == CLOSED:
self._wait_queue_depletion(timeout)
self.stop()
self.join()
else:
self._context.task_queue.put(None)
self._stop_pool()
|
(self, timeout: Optional[float] = None)
|
52,162 |
pebble.pool.process
|
map
|
Computes the *function* using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
*timeout* is an integer, if expires the task will be terminated
and the call to next will raise *TimeoutError*.
The *timeout* is applied to each chunk of the iterable.
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function.
A *pebble.ProcessFuture* object is returned.
|
def map(self, function: Callable,
*iterables, **kwargs) -> ProcessMapFuture:
"""Computes the *function* using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
*timeout* is an integer, if expires the task will be terminated
and the call to next will raise *TimeoutError*.
The *timeout* is applied to each chunk of the iterable.
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function.
A *pebble.ProcessFuture* object is returned.
"""
self._check_pool_state()
timeout = kwargs.get('timeout')
chunksize = kwargs.get('chunksize', 1)
if chunksize < 1:
raise ValueError("chunksize must be >= 1")
futures = [self.schedule(
process_chunk, args=(function, chunk), timeout=timeout)
for chunk in iter_chunks(chunksize, *iterables)]
return map_results(ProcessMapFuture(futures), timeout)
|
(self, function: Callable, *iterables, **kwargs) -> pebble.pool.base_pool.ProcessMapFuture
|
52,163 |
pebble.pool.process
|
schedule
|
Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
*timeout* is an integer, if expires the task will be terminated
and *Future.result()* will raise *TimeoutError*.
A *pebble.ProcessFuture* object is returned.
|
def schedule(self, function: Callable,
args: list = (),
kwargs: dict = {},
timeout: float = None) -> ProcessFuture:
"""Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
*timeout* is an integer, if expires the task will be terminated
and *Future.result()* will raise *TimeoutError*.
A *pebble.ProcessFuture* object is returned.
"""
self._check_pool_state()
future = ProcessFuture()
payload = TaskPayload(function, args, kwargs)
task = Task(next(self._task_counter), future, timeout, payload)
self._context.task_queue.put(task)
return future
|
(self, function: Callable, args: list = (), kwargs: dict = {}, timeout: Optional[float] = None) -> pebble.common.ProcessFuture
|
52,164 |
pebble.pool.base_pool
|
stop
|
Stops the pool without performing any pending task.
|
def stop(self):
"""Stops the pool without performing any pending task."""
self._context.state = STOPPED
|
(self)
|
52,165 |
pebble.pool.process
|
submit
|
This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
|
def submit(self, function: Callable,
timeout: Optional[float],
*args, **kwargs) -> ProcessFuture:
"""This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
"""
return self.schedule(
function, args=args, kwargs=kwargs, timeout=timeout)
|
(self, function: Callable, timeout: Optional[float], *args, **kwargs) -> pebble.common.ProcessFuture
|
52,166 |
pebble.pool.thread
|
ThreadPool
|
Allows to schedule jobs within a Pool of Threads.
max_workers is an integer representing the amount of desired process workers
managed by the pool.
If max_tasks is a number greater than zero,
each worker will be restarted after performing an equal amount of tasks.
initializer must be callable, if passed, it will be called
every time a worker is started, receiving initargs as arguments.
|
class ThreadPool(BasePool):
"""Allows to schedule jobs within a Pool of Threads.
max_workers is an integer representing the amount of desired process workers
managed by the pool.
If max_tasks is a number greater than zero,
each worker will be restarted after performing an equal amount of tasks.
initializer must be callable, if passed, it will be called
every time a worker is started, receiving initargs as arguments.
"""
def __init__(self, max_workers: int = multiprocessing.cpu_count(),
max_tasks: int = 0,
initializer: Callable = None,
initargs: list = ()):
super().__init__(max_workers, max_tasks, initializer, initargs)
self._pool_manager = PoolManager(self._context)
self._pool_manager_loop = None
def _start_pool(self):
with self._context.state_mutex:
if self._context.state == CREATED:
self._pool_manager.start()
self._pool_manager_loop = launch_thread(
None, pool_manager_loop, True, self._pool_manager)
self._context.state = RUNNING
def _stop_pool(self):
if self._pool_manager_loop is not None:
self._pool_manager_loop.join()
self._pool_manager.stop()
def schedule(self, function, args=(), kwargs={}) -> Future:
"""Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
A *concurrent.futures.Future* object is returned.
"""
self._check_pool_state()
future = Future()
payload = TaskPayload(function, args, kwargs)
task = Task(next(self._task_counter), future, None, payload)
self._context.task_queue.put(task)
return future
def submit(self, function: Callable, *args, **kwargs) -> Future:
"""This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
"""
return self.schedule(function, args=args, kwargs=kwargs)
def map(self, function: Callable, *iterables, **kwargs) -> MapFuture:
"""Returns an iterator equivalent to map(function, iterables).
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function. If None
the size will be controlled by the Pool.
"""
self._check_pool_state()
timeout = kwargs.get('timeout')
chunksize = kwargs.get('chunksize', 1)
if chunksize < 1:
raise ValueError("chunksize must be >= 1")
futures = [self.schedule(process_chunk, args=(function, chunk))
for chunk in iter_chunks(chunksize, *iterables)]
return map_results(MapFuture(futures), timeout)
|
(max_workers: int = 60, max_tasks: int = 0, initializer: Callable = None, initargs: list = ())
|
52,169 |
pebble.pool.thread
|
__init__
| null |
def __init__(self, max_workers: int = multiprocessing.cpu_count(),
max_tasks: int = 0,
initializer: Callable = None,
initargs: list = ()):
super().__init__(max_workers, max_tasks, initializer, initargs)
self._pool_manager = PoolManager(self._context)
self._pool_manager_loop = None
|
(self, max_workers: int = 60, max_tasks: int = 0, initializer: Optional[Callable] = None, initargs: list = ())
|
52,171 |
pebble.pool.thread
|
_start_pool
| null |
def _start_pool(self):
with self._context.state_mutex:
if self._context.state == CREATED:
self._pool_manager.start()
self._pool_manager_loop = launch_thread(
None, pool_manager_loop, True, self._pool_manager)
self._context.state = RUNNING
|
(self)
|
52,172 |
pebble.pool.thread
|
_stop_pool
| null |
def _stop_pool(self):
if self._pool_manager_loop is not None:
self._pool_manager_loop.join()
self._pool_manager.stop()
|
(self)
|
52,177 |
pebble.pool.thread
|
map
|
Returns an iterator equivalent to map(function, iterables).
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function. If None
the size will be controlled by the Pool.
|
def map(self, function: Callable, *iterables, **kwargs) -> MapFuture:
"""Returns an iterator equivalent to map(function, iterables).
*chunksize* controls the size of the chunks the iterable will
be broken into before being passed to the function. If None
the size will be controlled by the Pool.
"""
self._check_pool_state()
timeout = kwargs.get('timeout')
chunksize = kwargs.get('chunksize', 1)
if chunksize < 1:
raise ValueError("chunksize must be >= 1")
futures = [self.schedule(process_chunk, args=(function, chunk))
for chunk in iter_chunks(chunksize, *iterables)]
return map_results(MapFuture(futures), timeout)
|
(self, function: Callable, *iterables, **kwargs) -> pebble.pool.base_pool.MapFuture
|
52,178 |
pebble.pool.thread
|
schedule
|
Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
A *concurrent.futures.Future* object is returned.
|
def schedule(self, function, args=(), kwargs={}) -> Future:
"""Schedules *function* to be run the Pool.
*args* and *kwargs* will be forwareded to the scheduled function
respectively as arguments and keyword arguments.
A *concurrent.futures.Future* object is returned.
"""
self._check_pool_state()
future = Future()
payload = TaskPayload(function, args, kwargs)
task = Task(next(self._task_counter), future, None, payload)
self._context.task_queue.put(task)
return future
|
(self, function, args=(), kwargs={}) -> concurrent.futures._base.Future
|
52,180 |
pebble.pool.thread
|
submit
|
This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
|
def submit(self, function: Callable, *args, **kwargs) -> Future:
"""This function is provided for compatibility with
`asyncio.loop.run_in_executor`.
For scheduling jobs within the pool use `schedule` instead.
"""
return self.schedule(function, args=args, kwargs=kwargs)
|
(self, function: Callable, *args, **kwargs) -> concurrent.futures._base.Future
|
52,185 |
pebble.decorators
|
sighandler
|
Sets the decorated function as signal handler of given *signals*.
*signals* can be either a single signal or a list/tuple
of multiple ones.
|
def sighandler(signals: list) -> Callable:
"""Sets the decorated function as signal handler of given *signals*.
*signals* can be either a single signal or a list/tuple
of multiple ones.
"""
def wrap(function):
set_signal_handlers(signals, function)
@wraps(function)
def wrapper(*args, **kwargs):
return function(*args, **kwargs)
return wrapper
return wrap
|
(signals: list) -> Callable
|
52,186 |
pebble.decorators
|
synchronized
|
A synchronized function prevents two or more callers to interleave
its execution preventing race conditions.
The synchronized decorator accepts as optional parameter a Lock, RLock or
Semaphore object which will be employed to ensure the function's atomicity.
If no synchronization object is given, a single threading.Lock will be used.
This implies that between different decorated function only one at a time
will be executed.
|
def synchronized(*args) -> Callable:
"""A synchronized function prevents two or more callers to interleave
its execution preventing race conditions.
The synchronized decorator accepts as optional parameter a Lock, RLock or
Semaphore object which will be employed to ensure the function's atomicity.
If no synchronization object is given, a single threading.Lock will be used.
This implies that between different decorated function only one at a time
will be executed.
"""
if callable(args[0]):
return decorate_synchronized(args[0], _synchronized_lock)
else:
def wrap(function) -> type:
return decorate_synchronized(function, args[0])
return wrap
|
(*args) -> Callable
|
52,187 |
pebble.functions
|
waitforqueues
|
Waits for one or more *Queue* to be ready or until *timeout* expires.
*queues* is a list containing one or more *Queue.Queue* objects.
If *timeout* is not None the function will block
for the specified amount of seconds.
The function returns a list containing the ready *Queues*.
|
def waitforqueues(queues: list, timeout: float = None) -> filter:
"""Waits for one or more *Queue* to be ready or until *timeout* expires.
*queues* is a list containing one or more *Queue.Queue* objects.
If *timeout* is not None the function will block
for the specified amount of seconds.
The function returns a list containing the ready *Queues*.
"""
lock = threading.Condition(threading.Lock())
prepare_queues(queues, lock)
try:
wait_queues(queues, lock, timeout)
finally:
reset_queues(queues)
return filter(lambda q: not q.empty(), queues)
|
(queues: list, timeout: Optional[float] = None) -> filter
|
52,188 |
pebble.functions
|
waitforthreads
|
Waits for one or more *Thread* to exit or until *timeout* expires.
.. note::
Expired *Threads* are not joined by *waitforthreads*.
*threads* is a list containing one or more *threading.Thread* objects.
If *timeout* is not None the function will block
for the specified amount of seconds.
The function returns a list containing the ready *Threads*.
|
def waitforthreads(threads: list, timeout: float = None) -> filter:
"""Waits for one or more *Thread* to exit or until *timeout* expires.
.. note::
Expired *Threads* are not joined by *waitforthreads*.
*threads* is a list containing one or more *threading.Thread* objects.
If *timeout* is not None the function will block
for the specified amount of seconds.
The function returns a list containing the ready *Threads*.
"""
old_function = None
lock = threading.Condition(threading.Lock())
def new_function(*args):
old_function(*args)
with lock:
lock.notify_all()
old_function = prepare_threads(new_function)
try:
wait_threads(threads, lock, timeout)
finally:
reset_threads(old_function)
return filter(lambda t: not t.is_alive(), threads)
|
(threads: list, timeout: Optional[float] = None) -> filter
|
52,195 |
osmnx.bearing
|
add_edge_bearings
|
Add compass `bearing` attributes to all graph edges.
Vectorized function to calculate (initial) bearing from origin node to
destination node for each edge in a directed, unprojected graph then add
these bearings as new edge attributes. Bearing represents angle in degrees
(clockwise) between north and the geodesic line from the origin node to
the destination node. Ignores self-loop edges as their bearings are
undefined.
Parameters
----------
G : networkx.MultiDiGraph
unprojected graph
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with edge bearing attributes
|
def add_edge_bearings(G, precision=None):
"""
Add compass `bearing` attributes to all graph edges.
Vectorized function to calculate (initial) bearing from origin node to
destination node for each edge in a directed, unprojected graph then add
these bearings as new edge attributes. Bearing represents angle in degrees
(clockwise) between north and the geodesic line from the origin node to
the destination node. Ignores self-loop edges as their bearings are
undefined.
Parameters
----------
G : networkx.MultiDiGraph
unprojected graph
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with edge bearing attributes
"""
if precision is None:
precision = 1
else:
warn(
"The `precision` parameter is deprecated and will be removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
if projection.is_projected(G.graph["crs"]): # pragma: no cover
msg = "graph must be unprojected to add edge bearings"
raise ValueError(msg)
# extract edge IDs and corresponding coordinates from their nodes
uvk = [(u, v, k) for u, v, k in G.edges if u != v]
x = G.nodes(data="x")
y = G.nodes(data="y")
coords = np.array([(y[u], x[u], y[v], x[v]) for u, v, k in uvk])
# calculate bearings then set as edge attributes
bearings = calculate_bearing(coords[:, 0], coords[:, 1], coords[:, 2], coords[:, 3])
values = zip(uvk, bearings.round(precision))
nx.set_edge_attributes(G, dict(values), name="bearing")
return G
|
(G, precision=None)
|
52,196 |
osmnx.elevation
|
add_edge_grades
|
Add `grade` attribute to each graph edge.
Vectorized function to calculate the directed grade (ie, rise over run)
for each edge in the graph and add it to the edge as an attribute. Nodes
must already have `elevation` attributes to use this function.
See also the `add_node_elevations_raster` and `add_node_elevations_google`
functions.
Parameters
----------
G : networkx.MultiDiGraph
input graph with `elevation` node attribute
add_absolute : bool
if True, also add absolute value of grade as `grade_abs` attribute
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with edge `grade` (and optionally `grade_abs`) attributes
|
def add_edge_grades(G, add_absolute=True, precision=None):
"""
Add `grade` attribute to each graph edge.
Vectorized function to calculate the directed grade (ie, rise over run)
for each edge in the graph and add it to the edge as an attribute. Nodes
must already have `elevation` attributes to use this function.
See also the `add_node_elevations_raster` and `add_node_elevations_google`
functions.
Parameters
----------
G : networkx.MultiDiGraph
input graph with `elevation` node attribute
add_absolute : bool
if True, also add absolute value of grade as `grade_abs` attribute
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with edge `grade` (and optionally `grade_abs`) attributes
"""
if precision is None:
precision = 3
else:
warn(
"The `precision` parameter is deprecated and will be removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
elev_lookup = G.nodes(data="elevation")
u, v, k, lengths = zip(*G.edges(keys=True, data="length"))
uvk = tuple(zip(u, v, k))
# calculate edges' elevation changes from u to v then divide by lengths
elevs = np.array([(elev_lookup[u], elev_lookup[v]) for u, v, k in uvk])
grades = ((elevs[:, 1] - elevs[:, 0]) / np.array(lengths)).round(precision)
nx.set_edge_attributes(G, dict(zip(uvk, grades)), name="grade")
# optionally add grade absolute value to the edge attributes
if add_absolute:
nx.set_edge_attributes(G, dict(zip(uvk, np.abs(grades))), name="grade_abs")
utils.log("Added grade attributes to all edges.")
return G
|
(G, add_absolute=True, precision=None)
|
52,197 |
osmnx.routing
|
add_edge_speeds
|
Add edge speeds (km per hour) to graph as new `speed_kph` edge attributes.
By default, this imputes free-flow travel speeds for all edges via the
mean `maxspeed` value of the edges of each highway type. For highway types
in the graph that have no `maxspeed` value on any edge, it assigns the
mean of all `maxspeed` values in graph.
This default mean-imputation can obviously be imprecise, and the user can
override it by passing in `hwy_speeds` and/or `fallback` arguments that
correspond to local speed limit standards. The user can also specify a
different aggregation function (such as the median) to impute missing
values from the observed values.
If edge `maxspeed` attribute has "mph" in it, value will automatically be
converted from miles per hour to km per hour. Any other speed units should
be manually converted to km per hour prior to running this function,
otherwise there could be unexpected results. If "mph" does not appear in
the edge's maxspeed attribute string, then function assumes kph, per OSM
guidelines: https://wiki.openstreetmap.org/wiki/Map_Features/Units
Parameters
----------
G : networkx.MultiDiGraph
input graph
hwy_speeds : dict
dict keys = OSM highway types and values = typical speeds (km per
hour) to assign to edges of that highway type for any edges missing
speed data. Any edges with highway type not in `hwy_speeds` will be
assigned the mean preexisting speed value of all edges of that highway
type.
fallback : numeric
default speed value (km per hour) to assign to edges whose highway
type did not appear in `hwy_speeds` and had no preexisting speed
values on any edge
precision : int
deprecated, do not use
agg : function
aggregation function to impute missing values from observed values.
the default is numpy.mean, but you might also consider for example
numpy.median, numpy.nanmedian, or your own custom function
Returns
-------
G : networkx.MultiDiGraph
graph with speed_kph attributes on all edges
|
def add_edge_speeds(G, hwy_speeds=None, fallback=None, precision=None, agg=np.mean):
"""
Add edge speeds (km per hour) to graph as new `speed_kph` edge attributes.
By default, this imputes free-flow travel speeds for all edges via the
mean `maxspeed` value of the edges of each highway type. For highway types
in the graph that have no `maxspeed` value on any edge, it assigns the
mean of all `maxspeed` values in graph.
This default mean-imputation can obviously be imprecise, and the user can
override it by passing in `hwy_speeds` and/or `fallback` arguments that
correspond to local speed limit standards. The user can also specify a
different aggregation function (such as the median) to impute missing
values from the observed values.
If edge `maxspeed` attribute has "mph" in it, value will automatically be
converted from miles per hour to km per hour. Any other speed units should
be manually converted to km per hour prior to running this function,
otherwise there could be unexpected results. If "mph" does not appear in
the edge's maxspeed attribute string, then function assumes kph, per OSM
guidelines: https://wiki.openstreetmap.org/wiki/Map_Features/Units
Parameters
----------
G : networkx.MultiDiGraph
input graph
hwy_speeds : dict
dict keys = OSM highway types and values = typical speeds (km per
hour) to assign to edges of that highway type for any edges missing
speed data. Any edges with highway type not in `hwy_speeds` will be
assigned the mean preexisting speed value of all edges of that highway
type.
fallback : numeric
default speed value (km per hour) to assign to edges whose highway
type did not appear in `hwy_speeds` and had no preexisting speed
values on any edge
precision : int
deprecated, do not use
agg : function
aggregation function to impute missing values from observed values.
the default is numpy.mean, but you might also consider for example
numpy.median, numpy.nanmedian, or your own custom function
Returns
-------
G : networkx.MultiDiGraph
graph with speed_kph attributes on all edges
"""
if precision is None:
precision = 1
else:
warn(
"The `precision` parameter is deprecated and will be removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
if fallback is None:
fallback = np.nan
edges = convert.graph_to_gdfs(G, nodes=False, fill_edge_geometry=False)
# collapse any highway lists (can happen during graph simplification)
# into string values simply by keeping just the first element of the list
edges["highway"] = edges["highway"].map(lambda x: x[0] if isinstance(x, list) else x)
if "maxspeed" in edges.columns:
# collapse any maxspeed lists (can happen during graph simplification)
# into a single value
edges["maxspeed"] = edges["maxspeed"].apply(_collapse_multiple_maxspeed_values, agg=agg)
# create speed_kph by cleaning maxspeed strings and converting mph to
# kph if necessary
edges["speed_kph"] = edges["maxspeed"].astype(str).map(_clean_maxspeed).astype(float)
else:
# if no edges in graph had a maxspeed attribute
edges["speed_kph"] = None
# if user provided hwy_speeds, use them as default values, otherwise
# initialize an empty series to populate with values
hwy_speed_avg = pd.Series(dtype=float) if hwy_speeds is None else pd.Series(hwy_speeds).dropna()
# for each highway type that caller did not provide in hwy_speeds, impute
# speed of type by taking the mean of the preexisting speed values of that
# highway type
for hwy, group in edges.groupby("highway"):
if hwy not in hwy_speed_avg:
hwy_speed_avg.loc[hwy] = agg(group["speed_kph"])
# if any highway types had no preexisting speed values, impute their speed
# with fallback value provided by caller. if fallback=np.nan, impute speed
# as the mean speed of all highway types that did have preexisting values
hwy_speed_avg = hwy_speed_avg.fillna(fallback).fillna(agg(hwy_speed_avg))
# for each edge missing speed data, assign it the imputed value for its
# highway type
speed_kph = (
edges[["highway", "speed_kph"]].set_index("highway").iloc[:, 0].fillna(hwy_speed_avg)
)
# all speeds will be null if edges had no preexisting maxspeed data and
# caller did not pass in hwy_speeds or fallback arguments
if pd.isna(speed_kph).all():
msg = (
"this graph's edges have no preexisting `maxspeed` attribute "
"values so you must pass `hwy_speeds` or `fallback` arguments."
)
raise ValueError(msg)
# add speed kph attribute to graph edges
edges["speed_kph"] = speed_kph.round(precision).to_numpy()
nx.set_edge_attributes(G, values=edges["speed_kph"], name="speed_kph")
return G
|
(G, hwy_speeds=None, fallback=None, precision=None, agg=<function mean at 0x7efd24b4dd30>)
|
52,198 |
osmnx.routing
|
add_edge_travel_times
|
Add edge travel time (seconds) to graph as new `travel_time` edge attributes.
Calculates free-flow travel time along each edge, based on `length` and
`speed_kph` attributes. Note: run `add_edge_speeds` first to generate the
`speed_kph` attribute. All edges must have `length` and `speed_kph`
attributes and all their values must be non-null.
Parameters
----------
G : networkx.MultiDiGraph
input graph
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with travel_time attributes on all edges
|
def add_edge_travel_times(G, precision=None):
"""
Add edge travel time (seconds) to graph as new `travel_time` edge attributes.
Calculates free-flow travel time along each edge, based on `length` and
`speed_kph` attributes. Note: run `add_edge_speeds` first to generate the
`speed_kph` attribute. All edges must have `length` and `speed_kph`
attributes and all their values must be non-null.
Parameters
----------
G : networkx.MultiDiGraph
input graph
precision : int
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with travel_time attributes on all edges
"""
if precision is None:
precision = 1
else:
warn(
"The `precision` parameter is deprecated and will be removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
edges = convert.graph_to_gdfs(G, nodes=False)
# verify edge length and speed_kph attributes exist
if not ("length" in edges.columns and "speed_kph" in edges.columns): # pragma: no cover
msg = "all edges must have `length` and `speed_kph` attributes."
raise KeyError(msg)
# verify edge length and speed_kph attributes contain no nulls
if pd.isna(edges["length"]).any() or pd.isna(edges["speed_kph"]).any(): # pragma: no cover
msg = "edge `length` and `speed_kph` values must be non-null."
raise ValueError(msg)
# convert distance meters to km, and speed km per hour to km per second
distance_km = edges["length"] / 1000
speed_km_sec = edges["speed_kph"] / (60 * 60)
# calculate edge travel time in seconds
travel_time = distance_km / speed_km_sec
# add travel time attribute to graph edges
edges["travel_time"] = travel_time.round(precision).to_numpy()
nx.set_edge_attributes(G, values=edges["travel_time"], name="travel_time")
return G
|
(G, precision=None)
|
52,199 |
osmnx.elevation
|
add_node_elevations_google
|
Add an `elevation` (meters) attribute to each node using a web service.
By default, this uses the Google Maps Elevation API but you can optionally
use an equivalent API with the same interface and response format, such as
Open Topo Data, via the `settings` module's `elevation_url_template`. The
Google Maps Elevation API requires an API key but other providers may not.
For a free local alternative see the `add_node_elevations_raster`
function. See also the `add_edge_grades` function.
Parameters
----------
G : networkx.MultiDiGraph
input graph
api_key : string
a valid API key, can be None if the API does not require a key
batch_size : int
max number of coordinate pairs to submit in each API call (if this is
too high, the server will reject the request because its character
limit exceeds the max allowed)
pause : float
time to pause between API calls, which can be increased if you get
rate limited
max_locations_per_batch : int
deprecated, do not use
precision : int
deprecated, do not use
url_template : string
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with node elevation attributes
|
def add_node_elevations_google(
G,
api_key=None,
batch_size=350,
pause=0,
max_locations_per_batch=None,
precision=None,
url_template=None,
):
"""
Add an `elevation` (meters) attribute to each node using a web service.
By default, this uses the Google Maps Elevation API but you can optionally
use an equivalent API with the same interface and response format, such as
Open Topo Data, via the `settings` module's `elevation_url_template`. The
Google Maps Elevation API requires an API key but other providers may not.
For a free local alternative see the `add_node_elevations_raster`
function. See also the `add_edge_grades` function.
Parameters
----------
G : networkx.MultiDiGraph
input graph
api_key : string
a valid API key, can be None if the API does not require a key
batch_size : int
max number of coordinate pairs to submit in each API call (if this is
too high, the server will reject the request because its character
limit exceeds the max allowed)
pause : float
time to pause between API calls, which can be increased if you get
rate limited
max_locations_per_batch : int
deprecated, do not use
precision : int
deprecated, do not use
url_template : string
deprecated, do not use
Returns
-------
G : networkx.MultiDiGraph
graph with node elevation attributes
"""
if max_locations_per_batch is None:
max_locations_per_batch = batch_size
else:
warn(
"The `max_locations_per_batch` parameter is deprecated and will be "
"removed the v2.0.0 release, use the `batch_size` parameter instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
if precision is None:
precision = 3
else:
warn(
"The `precision` parameter is deprecated and will be removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
if url_template is None:
url_template = settings.elevation_url_template
else:
warn(
"The `url_template` parameter is deprecated and will be removed "
"in the v2.0.0 release. Configure the `settings` module's "
"`elevation_url_template` instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# make a pandas series of all the nodes' coordinates as 'lat,lon'
# round coordinates to 5 decimal places (approx 1 meter) to be able to fit
# in more locations per API call
node_points = pd.Series(
{node: f'{data["y"]:.5f},{data["x"]:.5f}' for node, data in G.nodes(data=True)}
)
n_calls = int(np.ceil(len(node_points) / max_locations_per_batch))
domain = _downloader._hostname_from_url(url_template)
utils.log(f"Requesting node elevations from {domain!r} in {n_calls} request(s)")
# break the series of coordinates into chunks of max_locations_per_batch
# API format is locations=lat,lon|lat,lon|lat,lon|lat,lon...
results = []
for i in range(0, len(node_points), max_locations_per_batch):
chunk = node_points.iloc[i : i + max_locations_per_batch]
locations = "|".join(chunk)
url = url_template.format(locations=locations, key=api_key)
# download and append these elevation results to list of all results
response_json = _elevation_request(url, pause)
if "results" in response_json and len(response_json["results"]) > 0:
results.extend(response_json["results"])
else:
raise InsufficientResponseError(str(response_json))
# sanity check that all our vectors have the same number of elements
msg = f"Graph has {len(G):,} nodes and we received {len(results):,} results from {domain!r}"
utils.log(msg)
if not (len(results) == len(G) == len(node_points)): # pragma: no cover
err_msg = f"{msg}\n{response_json}"
raise InsufficientResponseError(err_msg)
# add elevation as an attribute to the nodes
df_elev = pd.DataFrame(node_points, columns=["node_points"])
df_elev["elevation"] = [result["elevation"] for result in results]
df_elev["elevation"] = df_elev["elevation"].round(precision)
nx.set_node_attributes(G, name="elevation", values=df_elev["elevation"].to_dict())
utils.log(f"Added elevation data from {domain!r} to all nodes.")
return G
|
(G, api_key=None, batch_size=350, pause=0, max_locations_per_batch=None, precision=None, url_template=None)
|
52,200 |
osmnx.elevation
|
add_node_elevations_raster
|
Add `elevation` attribute to each node from local raster file(s).
If `filepath` is a list of paths, this will generate a virtual raster
composed of the files at those paths as an intermediate step.
See also the `add_edge_grades` function.
Parameters
----------
G : networkx.MultiDiGraph
input graph, in same CRS as raster
filepath : string or pathlib.Path or list of strings/Paths
path (or list of paths) to the raster file(s) to query
band : int
which raster band to query
cpus : int
how many CPU cores to use; if None, use all available
Returns
-------
G : networkx.MultiDiGraph
graph with node elevation attributes
|
def add_node_elevations_raster(G, filepath, band=1, cpus=None):
"""
Add `elevation` attribute to each node from local raster file(s).
If `filepath` is a list of paths, this will generate a virtual raster
composed of the files at those paths as an intermediate step.
See also the `add_edge_grades` function.
Parameters
----------
G : networkx.MultiDiGraph
input graph, in same CRS as raster
filepath : string or pathlib.Path or list of strings/Paths
path (or list of paths) to the raster file(s) to query
band : int
which raster band to query
cpus : int
how many CPU cores to use; if None, use all available
Returns
-------
G : networkx.MultiDiGraph
graph with node elevation attributes
"""
if rasterio is None or gdal is None: # pragma: no cover
msg = "gdal and rasterio must be installed to query raster files"
raise ImportError(msg)
if cpus is None:
cpus = mp.cpu_count()
cpus = min(cpus, mp.cpu_count())
utils.log(f"Attaching elevations with {cpus} CPUs...")
# if a list of filepaths is passed, compose them all as a virtual raster
# use the sha1 hash of the filepaths list as the vrt filename
if not isinstance(filepath, (str, Path)):
filepaths = [str(p) for p in filepath]
sha = sha1(str(filepaths).encode("utf-8")).hexdigest()
filepath = f"./.osmnx_{sha}.vrt"
gdal.UseExceptions()
gdal.BuildVRT(filepath, filepaths).FlushCache()
nodes = convert.graph_to_gdfs(G, edges=False, node_geometry=False)[["x", "y"]]
if cpus == 1:
elevs = dict(_query_raster(nodes, filepath, band))
else:
# divide nodes into equal-sized chunks for multiprocessing
size = int(np.ceil(len(nodes) / cpus))
args = ((nodes.iloc[i : i + size], filepath, band) for i in range(0, len(nodes), size))
with mp.get_context("spawn").Pool(cpus) as pool:
results = pool.starmap_async(_query_raster, args).get()
elevs = {k: v for kv in results for k, v in kv}
assert len(G) == len(elevs)
nx.set_node_attributes(G, elevs, name="elevation")
utils.log("Added elevation data from raster to all nodes.")
return G
|
(G, filepath, band=1, cpus=None)
|
52,201 |
osmnx.stats
|
basic_stats
|
Calculate basic descriptive geometric and topological measures of a graph.
Density measures are only calculated if `area` is provided and clean
intersection measures are only calculated if `clean_int_tol` is provided.
Parameters
----------
G : networkx.MultiDiGraph
input graph
area : float
if not None, calculate density measures and use this value (in square
meters) as the denominator
clean_int_tol : float
if not None, calculate consolidated intersections count (and density,
if `area` is also provided) and use this tolerance value; refer to the
`simplification.consolidate_intersections` function documentation for
details
Returns
-------
stats : dict
dictionary containing the following keys
- `circuity_avg` - see `circuity_avg` function documentation
- `clean_intersection_count` - see `clean_intersection_count` function documentation
- `clean_intersection_density_km` - `clean_intersection_count` per sq km
- `edge_density_km` - `edge_length_total` per sq km
- `edge_length_avg` - `edge_length_total / m`
- `edge_length_total` - see `edge_length_total` function documentation
- `intersection_count` - see `intersection_count` function documentation
- `intersection_density_km` - `intersection_count` per sq km
- `k_avg` - graph's average node degree (in-degree and out-degree)
- `m` - count of edges in graph
- `n` - count of nodes in graph
- `node_density_km` - `n` per sq km
- `self_loop_proportion` - see `self_loop_proportion` function documentation
- `street_density_km` - `street_length_total` per sq km
- `street_length_avg` - `street_length_total / street_segment_count`
- `street_length_total` - see `street_length_total` function documentation
- `street_segment_count` - see `street_segment_count` function documentation
- `streets_per_node_avg` - see `streets_per_node_avg` function documentation
- `streets_per_node_counts` - see `streets_per_node_counts` function documentation
- `streets_per_node_proportions` - see `streets_per_node_proportions` function documentation
|
def basic_stats(G, area=None, clean_int_tol=None):
"""
Calculate basic descriptive geometric and topological measures of a graph.
Density measures are only calculated if `area` is provided and clean
intersection measures are only calculated if `clean_int_tol` is provided.
Parameters
----------
G : networkx.MultiDiGraph
input graph
area : float
if not None, calculate density measures and use this value (in square
meters) as the denominator
clean_int_tol : float
if not None, calculate consolidated intersections count (and density,
if `area` is also provided) and use this tolerance value; refer to the
`simplification.consolidate_intersections` function documentation for
details
Returns
-------
stats : dict
dictionary containing the following keys
- `circuity_avg` - see `circuity_avg` function documentation
- `clean_intersection_count` - see `clean_intersection_count` function documentation
- `clean_intersection_density_km` - `clean_intersection_count` per sq km
- `edge_density_km` - `edge_length_total` per sq km
- `edge_length_avg` - `edge_length_total / m`
- `edge_length_total` - see `edge_length_total` function documentation
- `intersection_count` - see `intersection_count` function documentation
- `intersection_density_km` - `intersection_count` per sq km
- `k_avg` - graph's average node degree (in-degree and out-degree)
- `m` - count of edges in graph
- `n` - count of nodes in graph
- `node_density_km` - `n` per sq km
- `self_loop_proportion` - see `self_loop_proportion` function documentation
- `street_density_km` - `street_length_total` per sq km
- `street_length_avg` - `street_length_total / street_segment_count`
- `street_length_total` - see `street_length_total` function documentation
- `street_segment_count` - see `street_segment_count` function documentation
- `streets_per_node_avg` - see `streets_per_node_avg` function documentation
- `streets_per_node_counts` - see `streets_per_node_counts` function documentation
- `streets_per_node_proportions` - see `streets_per_node_proportions` function documentation
"""
Gu = convert.to_undirected(G)
stats = {}
stats["n"] = len(G.nodes)
stats["m"] = len(G.edges)
stats["k_avg"] = 2 * stats["m"] / stats["n"]
stats["edge_length_total"] = edge_length_total(G)
stats["edge_length_avg"] = stats["edge_length_total"] / stats["m"]
stats["streets_per_node_avg"] = streets_per_node_avg(G)
stats["streets_per_node_counts"] = streets_per_node_counts(G)
stats["streets_per_node_proportions"] = streets_per_node_proportions(G)
stats["intersection_count"] = intersection_count(G)
stats["street_length_total"] = street_length_total(Gu)
stats["street_segment_count"] = street_segment_count(Gu)
stats["street_length_avg"] = stats["street_length_total"] / stats["street_segment_count"]
stats["circuity_avg"] = circuity_avg(Gu)
stats["self_loop_proportion"] = self_loop_proportion(Gu)
# calculate clean intersection counts if requested
if clean_int_tol:
stats["clean_intersection_count"] = len(
simplification.consolidate_intersections(
G, tolerance=clean_int_tol, rebuild_graph=False, dead_ends=False
)
)
# can only calculate density measures if area was provided
if area is not None:
area_km = area / 1_000_000 # convert m^2 to km^2
stats["node_density_km"] = stats["n"] / area_km
stats["intersection_density_km"] = stats["intersection_count"] / area_km
stats["edge_density_km"] = stats["edge_length_total"] / area_km
stats["street_density_km"] = stats["street_length_total"] / area_km
if clean_int_tol:
stats["clean_intersection_density_km"] = stats["clean_intersection_count"] / area_km
return stats
|
(G, area=None, clean_int_tol=None)
|
52,203 |
osmnx.utils
|
citation
|
Print the OSMnx package's citation information.
Boeing, G. (2024). Modeling and Analyzing Urban Networks and Amenities with
OSMnx. Working paper. https://geoffboeing.com/publications/osmnx-paper/
Parameters
----------
style : string {"apa", "bibtex", "ieee"}
citation format, either APA or BibTeX or IEEE
Returns
-------
None
|
def citation(style="bibtex"):
"""
Print the OSMnx package's citation information.
Boeing, G. (2024). Modeling and Analyzing Urban Networks and Amenities with
OSMnx. Working paper. https://geoffboeing.com/publications/osmnx-paper/
Parameters
----------
style : string {"apa", "bibtex", "ieee"}
citation format, either APA or BibTeX or IEEE
Returns
-------
None
"""
if style == "apa":
msg = (
"Boeing, G. (2024). Modeling and Analyzing Urban Networks and Amenities "
"with OSMnx. Working paper. https://geoffboeing.com/publications/osmnx-paper/"
)
elif style == "bibtex":
msg = (
"@techreport{boeing_osmnx_2024,\n"
" author = {Boeing, Geoff},\n"
" title = {{Modeling and Analyzing Urban Networks and Amenities with OSMnx}},\n"
" type = {Working paper},\n"
" url = {https://geoffboeing.com/publications/osmnx-paper/},\n"
" year = {2024}\n"
"}"
)
elif style == "ieee":
msg = (
'G. Boeing, "Modeling and Analyzing Urban Networks and Amenities with OSMnx," '
"Working paper, https://geoffboeing.com/publications/osmnx-paper/"
)
else: # pragma: no cover
err_msg = f"unrecognized citation style {style!r}"
raise ValueError(err_msg)
print(msg) # noqa: T201
|
(style='bibtex')
|
52,204 |
osmnx.utils
|
config
|
Do not use: deprecated. Use the settings module directly.
Parameters
----------
all_oneway : bool
deprecated
bidirectional_network_types : list
deprecated
cache_folder : string or pathlib.Path
deprecated
data_folder : string or pathlib.Path
deprecated
cache_only_mode : bool
deprecated
default_accept_language : string
deprecated
default_access : string
deprecated
default_crs : string
deprecated
default_referer : string
deprecated
default_user_agent : string
deprecated
imgs_folder : string or pathlib.Path
deprecated
log_file : bool
deprecated
log_filename : string
deprecated
log_console : bool
deprecated
log_level : int
deprecated
log_name : string
deprecated
logs_folder : string or pathlib.Path
deprecated
max_query_area_size : int
deprecated
memory : int
deprecated
nominatim_endpoint : string
deprecated
nominatim_key : string
deprecated
osm_xml_node_attrs : list
deprecated
osm_xml_node_tags : list
deprecated
osm_xml_way_attrs : list
deprecated
osm_xml_way_tags : list
deprecated
overpass_endpoint : string
deprecated
overpass_rate_limit : bool
deprecated
overpass_settings : string
deprecated
requests_kwargs : dict
deprecated
timeout : int
deprecated
use_cache : bool
deprecated
useful_tags_node : list
deprecated
useful_tags_way : list
deprecated
Returns
-------
None
|
def config(
all_oneway=settings.all_oneway,
bidirectional_network_types=settings.bidirectional_network_types,
cache_folder=settings.cache_folder,
cache_only_mode=settings.cache_only_mode,
data_folder=settings.data_folder,
default_accept_language=settings.default_accept_language,
default_access=settings.default_access,
default_crs=settings.default_crs,
default_referer=settings.default_referer,
default_user_agent=settings.default_user_agent,
imgs_folder=settings.imgs_folder,
log_console=settings.log_console,
log_file=settings.log_file,
log_filename=settings.log_filename,
log_level=settings.log_level,
log_name=settings.log_name,
logs_folder=settings.logs_folder,
max_query_area_size=settings.max_query_area_size,
memory=settings.memory,
nominatim_endpoint=settings.nominatim_endpoint,
nominatim_key=settings.nominatim_key,
osm_xml_node_attrs=settings.osm_xml_node_attrs,
osm_xml_node_tags=settings.osm_xml_node_tags,
osm_xml_way_attrs=settings.osm_xml_way_attrs,
osm_xml_way_tags=settings.osm_xml_way_tags,
overpass_endpoint=settings.overpass_endpoint,
overpass_rate_limit=settings.overpass_rate_limit,
overpass_settings=settings.overpass_settings,
requests_kwargs=settings.requests_kwargs,
timeout=settings.timeout,
use_cache=settings.use_cache,
useful_tags_node=settings.useful_tags_node,
useful_tags_way=settings.useful_tags_way,
):
"""
Do not use: deprecated. Use the settings module directly.
Parameters
----------
all_oneway : bool
deprecated
bidirectional_network_types : list
deprecated
cache_folder : string or pathlib.Path
deprecated
data_folder : string or pathlib.Path
deprecated
cache_only_mode : bool
deprecated
default_accept_language : string
deprecated
default_access : string
deprecated
default_crs : string
deprecated
default_referer : string
deprecated
default_user_agent : string
deprecated
imgs_folder : string or pathlib.Path
deprecated
log_file : bool
deprecated
log_filename : string
deprecated
log_console : bool
deprecated
log_level : int
deprecated
log_name : string
deprecated
logs_folder : string or pathlib.Path
deprecated
max_query_area_size : int
deprecated
memory : int
deprecated
nominatim_endpoint : string
deprecated
nominatim_key : string
deprecated
osm_xml_node_attrs : list
deprecated
osm_xml_node_tags : list
deprecated
osm_xml_way_attrs : list
deprecated
osm_xml_way_tags : list
deprecated
overpass_endpoint : string
deprecated
overpass_rate_limit : bool
deprecated
overpass_settings : string
deprecated
requests_kwargs : dict
deprecated
timeout : int
deprecated
use_cache : bool
deprecated
useful_tags_node : list
deprecated
useful_tags_way : list
deprecated
Returns
-------
None
"""
warn(
"The `utils.config` function is deprecated and will be removed in "
"the v2.0.0 release. Instead, use the `settings` module directly to "
"configure a global setting's value. For example, "
"`ox.settings.log_console=True`. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# set each global setting to the argument value
settings.all_oneway = all_oneway
settings.bidirectional_network_types = bidirectional_network_types
settings.cache_folder = cache_folder
settings.cache_only_mode = cache_only_mode
settings.data_folder = data_folder
settings.default_accept_language = default_accept_language
settings.default_access = default_access
settings.default_crs = default_crs
settings.default_referer = default_referer
settings.default_user_agent = default_user_agent
settings.imgs_folder = imgs_folder
settings.log_console = log_console
settings.log_file = log_file
settings.log_filename = log_filename
settings.log_level = log_level
settings.log_name = log_name
settings.logs_folder = logs_folder
settings.max_query_area_size = max_query_area_size
settings.memory = memory
settings.nominatim_endpoint = nominatim_endpoint
settings.nominatim_key = nominatim_key
settings.osm_xml_node_attrs = osm_xml_node_attrs
settings.osm_xml_node_tags = osm_xml_node_tags
settings.osm_xml_way_attrs = osm_xml_way_attrs
settings.osm_xml_way_tags = osm_xml_way_tags
settings.overpass_endpoint = overpass_endpoint
settings.overpass_rate_limit = overpass_rate_limit
settings.overpass_settings = overpass_settings
settings.timeout = timeout
settings.use_cache = use_cache
settings.useful_tags_node = useful_tags_node
settings.useful_tags_way = useful_tags_way
settings.requests_kwargs = requests_kwargs
|
(all_oneway=False, bidirectional_network_types=['walk'], cache_folder='./cache', cache_only_mode=False, data_folder='./data', default_accept_language=None, default_access='["access"!~"private"]', default_crs='epsg:4326', default_referer=None, default_user_agent=None, imgs_folder='./images', log_console=False, log_file=False, log_filename='osmnx', log_level=20, log_name='OSMnx', logs_folder='./logs', max_query_area_size=2500000000, memory=None, nominatim_endpoint=None, nominatim_key=None, osm_xml_node_attrs=None, osm_xml_node_tags=None, osm_xml_way_attrs=None, osm_xml_way_tags=None, overpass_endpoint=None, overpass_rate_limit=True, overpass_settings='[out:json][timeout:{timeout}]{maxsize}', requests_kwargs={}, timeout=None, use_cache=True, useful_tags_node=['ref', 'highway'], useful_tags_way=['bridge', 'tunnel', 'oneway', 'lanes', 'ref', 'name', 'highway', 'maxspeed', 'service', 'access', 'area', 'landuse', 'width', 'est_width', 'junction'])
|
52,205 |
osmnx.simplification
|
consolidate_intersections
|
Consolidate intersections comprising clusters of nearby nodes.
Merges nearby nodes and returns either their centroids or a rebuilt graph
with consolidated intersections and reconnected edge geometries. The
tolerance argument should be adjusted to approximately match street design
standards in the specific street network, and you should always use a
projected graph to work in meaningful and consistent units like meters.
Note the tolerance represents a per-node buffering radius: for example, to
consolidate nodes within 10 meters of each other, use tolerance=5.
When rebuild_graph=False, it uses a purely geometrical (and relatively
fast) algorithm to identify "geometrically close" nodes, merge them, and
return just the merged intersections' centroids. When rebuild_graph=True,
it uses a topological (and slower but more accurate) algorithm to identify
"topologically close" nodes, merge them, then rebuild/return the graph.
Returned graph's node IDs represent clusters rather than osmids. Refer to
nodes' osmid_original attributes for original osmids. If multiple nodes
were merged together, the osmid_original attribute is a list of merged
nodes' osmids.
Divided roads are often represented by separate centerline edges. The
intersection of two divided roads thus creates 4 nodes, representing where
each edge intersects a perpendicular edge. These 4 nodes represent a
single intersection in the real world. A similar situation occurs with
roundabouts and traffic circles. This function consolidates nearby nodes
by buffering them to an arbitrary distance, merging overlapping buffers,
and taking their centroid.
Parameters
----------
G : networkx.MultiDiGraph
a projected graph
tolerance : float
nodes are buffered to this distance (in graph's geometry's units) and
subsequent overlaps are dissolved into a single node
rebuild_graph : bool
if True, consolidate the nodes topologically, rebuild the graph, and
return as networkx.MultiDiGraph. if False, consolidate the nodes
geometrically and return the consolidated node points as
geopandas.GeoSeries
dead_ends : bool
if False, discard dead-end nodes to return only street-intersection
points
reconnect_edges : bool
ignored if rebuild_graph is not True. if True, reconnect edges and
their geometries in rebuilt graph to the consolidated nodes and update
edge length attributes; if False, returned graph has no edges (which
is faster if you just need topologically consolidated intersection
counts).
Returns
-------
networkx.MultiDiGraph or geopandas.GeoSeries
if rebuild_graph=True, returns MultiDiGraph with consolidated
intersections and reconnected edge geometries. if rebuild_graph=False,
returns GeoSeries of shapely Points representing the centroids of
street intersections
|
def consolidate_intersections(
G, tolerance=10, rebuild_graph=True, dead_ends=False, reconnect_edges=True
):
"""
Consolidate intersections comprising clusters of nearby nodes.
Merges nearby nodes and returns either their centroids or a rebuilt graph
with consolidated intersections and reconnected edge geometries. The
tolerance argument should be adjusted to approximately match street design
standards in the specific street network, and you should always use a
projected graph to work in meaningful and consistent units like meters.
Note the tolerance represents a per-node buffering radius: for example, to
consolidate nodes within 10 meters of each other, use tolerance=5.
When rebuild_graph=False, it uses a purely geometrical (and relatively
fast) algorithm to identify "geometrically close" nodes, merge them, and
return just the merged intersections' centroids. When rebuild_graph=True,
it uses a topological (and slower but more accurate) algorithm to identify
"topologically close" nodes, merge them, then rebuild/return the graph.
Returned graph's node IDs represent clusters rather than osmids. Refer to
nodes' osmid_original attributes for original osmids. If multiple nodes
were merged together, the osmid_original attribute is a list of merged
nodes' osmids.
Divided roads are often represented by separate centerline edges. The
intersection of two divided roads thus creates 4 nodes, representing where
each edge intersects a perpendicular edge. These 4 nodes represent a
single intersection in the real world. A similar situation occurs with
roundabouts and traffic circles. This function consolidates nearby nodes
by buffering them to an arbitrary distance, merging overlapping buffers,
and taking their centroid.
Parameters
----------
G : networkx.MultiDiGraph
a projected graph
tolerance : float
nodes are buffered to this distance (in graph's geometry's units) and
subsequent overlaps are dissolved into a single node
rebuild_graph : bool
if True, consolidate the nodes topologically, rebuild the graph, and
return as networkx.MultiDiGraph. if False, consolidate the nodes
geometrically and return the consolidated node points as
geopandas.GeoSeries
dead_ends : bool
if False, discard dead-end nodes to return only street-intersection
points
reconnect_edges : bool
ignored if rebuild_graph is not True. if True, reconnect edges and
their geometries in rebuilt graph to the consolidated nodes and update
edge length attributes; if False, returned graph has no edges (which
is faster if you just need topologically consolidated intersection
counts).
Returns
-------
networkx.MultiDiGraph or geopandas.GeoSeries
if rebuild_graph=True, returns MultiDiGraph with consolidated
intersections and reconnected edge geometries. if rebuild_graph=False,
returns GeoSeries of shapely Points representing the centroids of
street intersections
"""
# if dead_ends is False, discard dead-ends to retain only intersections
if not dead_ends:
spn = stats.streets_per_node(G)
dead_end_nodes = [node for node, count in spn.items() if count <= 1]
# make a copy to not mutate original graph object caller passed in
G = G.copy()
G.remove_nodes_from(dead_end_nodes)
if rebuild_graph:
if not G or not G.edges:
# cannot rebuild a graph with no nodes or no edges, just return it
return G
# otherwise
return _consolidate_intersections_rebuild_graph(G, tolerance, reconnect_edges)
# otherwise, if we're not rebuilding the graph
if not G:
# if graph has no nodes, just return empty GeoSeries
return gpd.GeoSeries(crs=G.graph["crs"])
# otherwise, return the centroids of the merged intersection polygons
return _merge_nodes_geometric(G, tolerance).centroid
|
(G, tolerance=10, rebuild_graph=True, dead_ends=False, reconnect_edges=True)
|
52,210 |
osmnx.features
|
features_from_address
|
Create GeoDataFrame of OSM features within some distance N, S, E, W of address.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
address : string
the address to geocode and use as the central point around which to
get the features
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
dist : numeric
distance in meters
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_address(address, tags, dist=1000):
"""
Create GeoDataFrame of OSM features within some distance N, S, E, W of address.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
address : string
the address to geocode and use as the central point around which to
get the features
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
dist : numeric
distance in meters
Returns
-------
gdf : geopandas.GeoDataFrame
"""
# geocode the address string to a (lat, lon) point
center_point = geocoder.geocode(query=address)
# create GeoDataFrame of features around this point
return features_from_point(center_point, tags, dist=dist)
|
(address, tags, dist=1000)
|
52,211 |
osmnx.features
|
features_from_bbox
|
Create a GeoDataFrame of OSM features within a N, S, E, W bounding box.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
north : float
deprecated, do not use
south : float
deprecated, do not use
east : float
deprecated, do not use
west : float
deprecated, do not use
bbox : tuple of floats
bounding box as (north, south, east, west)
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_bbox(north=None, south=None, east=None, west=None, bbox=None, tags=None):
"""
Create a GeoDataFrame of OSM features within a N, S, E, W bounding box.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
north : float
deprecated, do not use
south : float
deprecated, do not use
east : float
deprecated, do not use
west : float
deprecated, do not use
bbox : tuple of floats
bounding box as (north, south, east, west)
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
if not (north is None and south is None and east is None and west is None):
msg = (
"The `north`, `south`, `east`, and `west` parameters are deprecated and "
"will be removed in the v2.0.0 release. Use the `bbox` parameter instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
bbox = (north, south, east, west)
# convert bounding box to a polygon
polygon = utils_geo.bbox_to_poly(bbox=bbox)
# create GeoDataFrame of features within this polygon
return features_from_polygon(polygon, tags)
|
(north=None, south=None, east=None, west=None, bbox=None, tags=None)
|
52,212 |
osmnx.features
|
features_from_place
|
Create GeoDataFrame of OSM features within boundaries of some place(s).
The query must be geocodable and OSM must have polygon boundaries for the
geocode result. If OSM does not have a polygon for this place, you can
instead get features within it using the `features_from_address`
function, which geocodes the place name to a point and gets the features
within some distance of that point.
If OSM does have polygon boundaries for this place but you're not finding
it, try to vary the query string, pass in a structured query dict, or vary
the `which_result` argument to use a different geocode result. If you know
the OSM ID of the place, you can retrieve its boundary polygon using the
`geocode_to_gdf` function, then pass it to the `features_from_polygon`
function.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
query : string or dict or list
the query or queries to geocode to get place boundary polygon(s)
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
which_result : int
which geocoding result to use. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one.
buffer_dist : float
deprecated, do not use
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_place(query, tags, which_result=None, buffer_dist=None):
"""
Create GeoDataFrame of OSM features within boundaries of some place(s).
The query must be geocodable and OSM must have polygon boundaries for the
geocode result. If OSM does not have a polygon for this place, you can
instead get features within it using the `features_from_address`
function, which geocodes the place name to a point and gets the features
within some distance of that point.
If OSM does have polygon boundaries for this place but you're not finding
it, try to vary the query string, pass in a structured query dict, or vary
the `which_result` argument to use a different geocode result. If you know
the OSM ID of the place, you can retrieve its boundary polygon using the
`geocode_to_gdf` function, then pass it to the `features_from_polygon`
function.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
query : string or dict or list
the query or queries to geocode to get place boundary polygon(s)
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
which_result : int
which geocoding result to use. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one.
buffer_dist : float
deprecated, do not use
Returns
-------
gdf : geopandas.GeoDataFrame
"""
if buffer_dist is not None:
warn(
"The buffer_dist argument has been deprecated and will be removed "
"in the v2.0.0 release. Buffer your query area directly, if desired. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# create a GeoDataFrame with the spatial boundaries of the place(s)
if isinstance(query, (str, dict)):
# if it is a string (place name) or dict (structured place query),
# then it is a single place
gdf_place = geocoder.geocode_to_gdf(
query, which_result=which_result, buffer_dist=buffer_dist
)
elif isinstance(query, list):
# if it is a list, it contains multiple places to get
gdf_place = geocoder.geocode_to_gdf(query, buffer_dist=buffer_dist)
else: # pragma: no cover
msg = "query must be dict, string, or list of strings"
raise TypeError(msg)
# extract the geometry from the GeoDataFrame to use in API query
polygon = gdf_place["geometry"].unary_union
utils.log("Constructed place geometry polygon(s) to query API")
# create GeoDataFrame using this polygon(s) geometry
return features_from_polygon(polygon, tags)
|
(query, tags, which_result=None, buffer_dist=None)
|
52,213 |
osmnx.features
|
features_from_point
|
Create GeoDataFrame of OSM features within some distance N, S, E, W of a point.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
center_point : tuple
the (lat, lon) center point around which to get the features
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
dist : numeric
distance in meters
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_point(center_point, tags, dist=1000):
"""
Create GeoDataFrame of OSM features within some distance N, S, E, W of a point.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
center_point : tuple
the (lat, lon) center point around which to get the features
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
dist : numeric
distance in meters
Returns
-------
gdf : geopandas.GeoDataFrame
"""
# create bounding box from center point and distance in each direction
bbox = utils_geo.bbox_from_point(center_point, dist)
# convert the bounding box to a polygon
polygon = utils_geo.bbox_to_poly(bbox=bbox)
# create GeoDataFrame of features within this polygon
return features_from_polygon(polygon, tags)
|
(center_point, tags, dist=1000)
|
52,214 |
osmnx.features
|
features_from_polygon
|
Create GeoDataFrame of OSM features within boundaries of a (multi)polygon.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
geographic boundaries to fetch features within
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_polygon(polygon, tags):
"""
Create GeoDataFrame of OSM features within boundaries of a (multi)polygon.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
geographic boundaries to fetch features within
tags : dict
Dict of tags used for finding elements in the selected area. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
# verify that the geometry is valid and a Polygon/MultiPolygon
if not polygon.is_valid:
msg = "The geometry of `polygon` is invalid"
raise ValueError(msg)
if not isinstance(polygon, (Polygon, MultiPolygon)):
msg = (
"Boundaries must be a shapely Polygon or MultiPolygon. If you "
"requested features from place name, make sure your query resolves "
"to a Polygon or MultiPolygon, and not some other geometry, like a "
"Point. See OSMnx documentation for details."
)
raise TypeError(msg)
# download the data from OSM
response_jsons = _overpass._download_overpass_features(polygon, tags)
# create GeoDataFrame from the downloaded data
return _create_gdf(response_jsons, polygon, tags)
|
(polygon, tags)
|
52,215 |
osmnx.features
|
features_from_xml
|
Create a GeoDataFrame of OSM features in an OSM-formatted XML file.
Because this function creates a GeoDataFrame of features from an
OSM-formatted XML file that has already been downloaded (i.e. no query is
made to the Overpass API) the polygon and tags arguments are not required.
If they are not supplied to the function, features_from_xml() will
return features for all of the tagged elements in the file. If they are
supplied they will be used to filter the final GeoDataFrame.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
filepath : string or pathlib.Path
path to file containing OSM XML data
polygon : shapely.geometry.Polygon
optional geographic boundary to filter elements
tags : dict
optional dict of tags for filtering elements from the XML. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
encoding : string
the XML file's character encoding
Returns
-------
gdf : geopandas.GeoDataFrame
|
def features_from_xml(filepath, polygon=None, tags=None, encoding="utf-8"):
"""
Create a GeoDataFrame of OSM features in an OSM-formatted XML file.
Because this function creates a GeoDataFrame of features from an
OSM-formatted XML file that has already been downloaded (i.e. no query is
made to the Overpass API) the polygon and tags arguments are not required.
If they are not supplied to the function, features_from_xml() will
return features for all of the tagged elements in the file. If they are
supplied they will be used to filter the final GeoDataFrame.
For more details, see: https://wiki.openstreetmap.org/wiki/Map_features
Parameters
----------
filepath : string or pathlib.Path
path to file containing OSM XML data
polygon : shapely.geometry.Polygon
optional geographic boundary to filter elements
tags : dict
optional dict of tags for filtering elements from the XML. Results
returned are the union, not intersection of each individual tag.
Each result matches at least one given tag. The dict keys should be
OSM tags, (e.g., `building`, `landuse`, `highway`, etc) and the dict
values should be either `True` to retrieve all items with the given
tag, or a string to get a single tag-value combination, or a list of
strings to get multiple values for the given tag. For example,
`tags = {'building': True}` would return all building footprints in
the area. `tags = {'amenity':True, 'landuse':['retail','commercial'],
'highway':'bus_stop'}` would return all amenities, landuse=retail,
landuse=commercial, and highway=bus_stop.
encoding : string
the XML file's character encoding
Returns
-------
gdf : geopandas.GeoDataFrame
"""
# transmogrify file of OSM XML data into JSON
response_jsons = [osm_xml._overpass_json_from_file(filepath, encoding)]
# create GeoDataFrame using this response JSON
return _create_gdf(response_jsons, polygon=polygon, tags=tags)
|
(filepath, polygon=None, tags=None, encoding='utf-8')
|
52,217 |
osmnx.geocoder
|
geocode
|
Geocode place names or addresses to (lat, lon) with the Nominatim API.
This geocodes the query via the Nominatim "search" endpoint.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder
|
def geocode(query):
"""
Geocode place names or addresses to (lat, lon) with the Nominatim API.
This geocodes the query via the Nominatim "search" endpoint.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder
"""
# define the parameters
params = OrderedDict()
params["format"] = "json"
params["limit"] = 1
params["dedupe"] = 0 # prevent deduping to get precise number of results
params["q"] = query
response_json = _nominatim._nominatim_request(params=params)
# if results were returned, parse lat and lon out of the result
if response_json and "lat" in response_json[0] and "lon" in response_json[0]:
lat = float(response_json[0]["lat"])
lon = float(response_json[0]["lon"])
point = (lat, lon)
utils.log(f"Geocoded {query!r} to {point}")
return point
# otherwise we got no results back
msg = f"Nominatim could not geocode query {query!r}"
raise InsufficientResponseError(msg)
|
(query)
|
52,218 |
osmnx.geocoder
|
geocode_to_gdf
|
Retrieve OSM elements by place name or OSM ID with the Nominatim API.
If searching by place name, the `query` argument can be a string or
structured dict, or a list of such strings/dicts to send to the geocoder.
This uses the Nominatim "search" endpoint to geocode the place name to the
best-matching OSM element, then returns that element and its attribute
data.
You can instead query by OSM ID by passing `by_osmid=True`. This uses the
Nominatim "lookup" endpoint to retrieve the OSM element with that ID. In
this case, the function treats the `query` argument as an OSM ID (or list
of OSM IDs), which must be prepended with their types: node (N), way (W),
or relation (R) in accordance with the Nominatim API format. For example,
`query=["R2192363", "N240109189", "W427818536"]`.
If `query` is a list, then `which_result` must be either a single value or
a list with the same length as `query`. The queries you provide must be
resolvable to elements in the Nominatim database. The resulting
GeoDataFrame's geometry column contains place boundaries if they exist.
Parameters
----------
query : string or dict or list of strings/dicts
query string(s) or structured dict(s) to geocode
which_result : int
which search result to return. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one. to get
the top match regardless of geometry type, set which_result=1.
ignored if by_osmid=True.
by_osmid : bool
if True, treat query as an OSM ID lookup rather than text search
buffer_dist : float
deprecated, do not use
Returns
-------
gdf : geopandas.GeoDataFrame
a GeoDataFrame with one row for each query
|
def geocode_to_gdf(query, which_result=None, by_osmid=False, buffer_dist=None):
"""
Retrieve OSM elements by place name or OSM ID with the Nominatim API.
If searching by place name, the `query` argument can be a string or
structured dict, or a list of such strings/dicts to send to the geocoder.
This uses the Nominatim "search" endpoint to geocode the place name to the
best-matching OSM element, then returns that element and its attribute
data.
You can instead query by OSM ID by passing `by_osmid=True`. This uses the
Nominatim "lookup" endpoint to retrieve the OSM element with that ID. In
this case, the function treats the `query` argument as an OSM ID (or list
of OSM IDs), which must be prepended with their types: node (N), way (W),
or relation (R) in accordance with the Nominatim API format. For example,
`query=["R2192363", "N240109189", "W427818536"]`.
If `query` is a list, then `which_result` must be either a single value or
a list with the same length as `query`. The queries you provide must be
resolvable to elements in the Nominatim database. The resulting
GeoDataFrame's geometry column contains place boundaries if they exist.
Parameters
----------
query : string or dict or list of strings/dicts
query string(s) or structured dict(s) to geocode
which_result : int
which search result to return. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one. to get
the top match regardless of geometry type, set which_result=1.
ignored if by_osmid=True.
by_osmid : bool
if True, treat query as an OSM ID lookup rather than text search
buffer_dist : float
deprecated, do not use
Returns
-------
gdf : geopandas.GeoDataFrame
a GeoDataFrame with one row for each query
"""
if buffer_dist is not None:
warn(
"The buffer_dist argument has been deprecated and will be removed "
"in the v2.0.0 release. Buffer your results directly, if desired. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
if not isinstance(query, (str, dict, list)): # pragma: no cover
msg = "query must be a string or dict or list"
raise TypeError(msg)
# if caller passed a list of queries but a scalar which_result value, then
# turn which_result into a list with same length as query list
if isinstance(query, list) and (isinstance(which_result, int) or which_result is None):
which_result = [which_result] * len(query)
# turn query and which_result into lists if they're not already
if not isinstance(query, list):
query = [query]
if not isinstance(which_result, list):
which_result = [which_result]
# ensure same length
if len(query) != len(which_result): # pragma: no cover
msg = "which_result length must equal query length"
raise ValueError(msg)
# ensure query type of each item
for q in query:
if not isinstance(q, (str, dict)): # pragma: no cover
msg = "each query must be a dict or a string"
raise TypeError(msg)
# geocode each query and add to GeoDataFrame as a new row
gdf = gpd.GeoDataFrame()
for q, wr in zip(query, which_result):
gdf = pd.concat([gdf, _geocode_query_to_gdf(q, wr, by_osmid)])
# reset GeoDataFrame index and set its CRS
gdf = gdf.reset_index(drop=True)
gdf = gdf.set_crs(settings.default_crs)
# if buffer_dist was passed in, project the geometry to UTM, buffer it in
# meters, then project it back to lat-lon
if buffer_dist is not None and len(gdf) > 0:
gdf_utm = projection.project_gdf(gdf)
gdf_utm["geometry"] = gdf_utm["geometry"].buffer(buffer_dist)
gdf = projection.project_gdf(gdf_utm, to_latlong=True)
utils.log(f"Buffered GeoDataFrame to {buffer_dist} meters")
utils.log(f"Created GeoDataFrame with {len(gdf)} rows from {len(query)} queries")
return gdf
|
(query, which_result=None, by_osmid=False, buffer_dist=None)
|
52,221 |
osmnx.geometries
|
geometries_from_address
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
address : string
Do not use: deprecated.
tags : dict
Do not use: deprecated.
dist : numeric
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_address(address, tags, dist=1000):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
address : string
Do not use: deprecated.
tags : dict
Do not use: deprecated.
dist : numeric
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_address(address, tags, dist)
|
(address, tags, dist=1000)
|
52,222 |
osmnx.geometries
|
geometries_from_bbox
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
north : float
Do not use: deprecated.
south : float
Do not use: deprecated.
east : float
Do not use: deprecated.
west : float
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_bbox(north, south, east, west, tags):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
north : float
Do not use: deprecated.
south : float
Do not use: deprecated.
east : float
Do not use: deprecated.
west : float
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_bbox(north, south, east, west, tags=tags)
|
(north, south, east, west, tags)
|
52,223 |
osmnx.geometries
|
geometries_from_place
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
query : string or dict or list
Do not use: deprecated.
tags : dict
Do not use: deprecated.
which_result : int
Do not use: deprecated.
buffer_dist : float
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_place(query, tags, which_result=None, buffer_dist=None):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
query : string or dict or list
Do not use: deprecated.
tags : dict
Do not use: deprecated.
which_result : int
Do not use: deprecated.
buffer_dist : float
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_place(query, tags, which_result, buffer_dist)
|
(query, tags, which_result=None, buffer_dist=None)
|
52,224 |
osmnx.geometries
|
geometries_from_point
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
center_point : tuple
Do not use: deprecated.
tags : dict
Do not use: deprecated.
dist : numeric
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_point(center_point, tags, dist=1000):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
center_point : tuple
Do not use: deprecated.
tags : dict
Do not use: deprecated.
dist : numeric
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_point(center_point, tags, dist)
|
(center_point, tags, dist=1000)
|
52,225 |
osmnx.geometries
|
geometries_from_polygon
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_polygon(polygon, tags):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_polygon(polygon, tags)
|
(polygon, tags)
|
52,226 |
osmnx.geometries
|
geometries_from_xml
|
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
filepath : string or pathlib.Path
Do not use: deprecated.
polygon : shapely.geometry.Polygon
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
|
def geometries_from_xml(filepath, polygon=None, tags=None):
"""
Do not use: deprecated.
The `geometries` module and `geometries_from_X` functions have been
renamed the `features` module and `features_from_X` functions. Use these
instead. The `geometries` module and functions are deprecated and will be
removed in the v2.0.0 release.
Parameters
----------
filepath : string or pathlib.Path
Do not use: deprecated.
polygon : shapely.geometry.Polygon
Do not use: deprecated.
tags : dict
Do not use: deprecated.
Returns
-------
gdf : geopandas.GeoDataFrame
"""
warn(DEP_MSG, FutureWarning, stacklevel=2)
return features.features_from_xml(filepath, polygon, tags)
|
(filepath, polygon=None, tags=None)
|
52,227 |
osmnx.utils_graph
|
get_digraph
|
Do not use: deprecated.
Use the `convert.to_digraph` function instead.
Parameters
----------
G : networkx.MultiDiGraph
deprecated, do not use
weight : string
deprecated, do not use
Returns
-------
networkx.DiGraph
|
def get_digraph(G, weight="length"):
"""
Do not use: deprecated.
Use the `convert.to_digraph` function instead.
Parameters
----------
G : networkx.MultiDiGraph
deprecated, do not use
weight : string
deprecated, do not use
Returns
-------
networkx.DiGraph
"""
msg = (
"The `get_digraph` function is deprecated and will be removed in the "
"v2.0.0 release. Replace it with `convert.to_digraph` instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
return convert.to_digraph(G, weight)
|
(G, weight='length')
|
52,228 |
osmnx.utils_graph
|
get_undirected
|
Do not use: deprecated.
Use the `convert.to_undirected` function instead.
Parameters
----------
G : networkx.MultiDiGraph
deprecated, do not use
Returns
-------
networkx.MultiGraph
|
def get_undirected(G):
"""
Do not use: deprecated.
Use the `convert.to_undirected` function instead.
Parameters
----------
G : networkx.MultiDiGraph
deprecated, do not use
Returns
-------
networkx.MultiGraph
"""
msg = (
"The `get_undirected` function is deprecated and will be removed in the "
"v2.0.0 release. Replace it with `convert.to_undirected` instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
return convert.to_undirected(G)
|
(G)
|
52,230 |
osmnx.graph
|
graph_from_address
|
Download and create a graph within some distance of an address.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
address : string
the address to geocode and use as the central point around which to
construct the graph
dist : int
retain only those nodes within this many meters of the center of the
graph
dist_type : string {"network", "bbox"}
if "bbox", retain only those nodes within a bounding box of the
distance parameter. if "network", retain only those nodes within some
network distance from the center-most node.
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
return_coords : bool
deprecated, do not use
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
networkx.MultiDiGraph or optionally (networkx.MultiDiGraph, (lat, lon))
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
|
def graph_from_address(
address,
dist=1000,
dist_type="bbox",
network_type="all",
simplify=True,
retain_all=False,
truncate_by_edge=False,
return_coords=None,
clean_periphery=None,
custom_filter=None,
):
"""
Download and create a graph within some distance of an address.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
address : string
the address to geocode and use as the central point around which to
construct the graph
dist : int
retain only those nodes within this many meters of the center of the
graph
dist_type : string {"network", "bbox"}
if "bbox", retain only those nodes within a bounding box of the
distance parameter. if "network", retain only those nodes within some
network distance from the center-most node.
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
return_coords : bool
deprecated, do not use
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
networkx.MultiDiGraph or optionally (networkx.MultiDiGraph, (lat, lon))
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
"""
if return_coords is None:
return_coords = False
else:
warn(
"The `return_coords` argument has been deprecated and will be removed in "
"the v2.0.0 release. Future behavior will be as though `return_coords=False`. "
"If you want the address's geocoded coordinates, use the `geocode` function. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# geocode the address string to a (lat, lon) point
point = geocoder.geocode(query=address)
# then create a graph from this point
G = graph_from_point(
point,
dist,
dist_type,
network_type=network_type,
simplify=simplify,
retain_all=retain_all,
truncate_by_edge=truncate_by_edge,
clean_periphery=clean_periphery,
custom_filter=custom_filter,
)
utils.log(f"graph_from_address returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
if return_coords:
return G, point
# otherwise
return G
|
(address, dist=1000, dist_type='bbox', network_type='all', simplify=True, retain_all=False, truncate_by_edge=False, return_coords=None, clean_periphery=None, custom_filter=None)
|
52,231 |
osmnx.graph
|
graph_from_bbox
|
Download and create a graph within some bounding box.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
north : float
deprecated, do not use
south : float
deprecated, do not use
east : float
deprecated, do not use
west : float
deprecated, do not use
bbox : tuple of floats
bounding box as (north, south, east, west)
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
|
def graph_from_bbox(
north=None,
south=None,
east=None,
west=None,
bbox=None,
network_type="all",
simplify=True,
retain_all=False,
truncate_by_edge=False,
clean_periphery=None,
custom_filter=None,
):
"""
Download and create a graph within some bounding box.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
north : float
deprecated, do not use
south : float
deprecated, do not use
east : float
deprecated, do not use
west : float
deprecated, do not use
bbox : tuple of floats
bounding box as (north, south, east, west)
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
"""
if not (north is None and south is None and east is None and west is None):
msg = (
"The `north`, `south`, `east`, and `west` parameters are deprecated and "
"will be removed in the v2.0.0 release. Use the `bbox` parameter instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
bbox = (north, south, east, west)
# convert bounding box to a polygon
polygon = utils_geo.bbox_to_poly(bbox=bbox)
# create graph using this polygon geometry
G = graph_from_polygon(
polygon,
network_type=network_type,
simplify=simplify,
retain_all=retain_all,
truncate_by_edge=truncate_by_edge,
clean_periphery=clean_periphery,
custom_filter=custom_filter,
)
utils.log(f"graph_from_bbox returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
return G
|
(north=None, south=None, east=None, west=None, bbox=None, network_type='all', simplify=True, retain_all=False, truncate_by_edge=False, clean_periphery=None, custom_filter=None)
|
52,232 |
osmnx.convert
|
graph_from_gdfs
|
Convert node and edge GeoDataFrames to a MultiDiGraph.
This function is the inverse of `graph_to_gdfs` and is designed to work in
conjunction with it.
However, you can convert arbitrary node and edge GeoDataFrames as long as
1) `gdf_nodes` is uniquely indexed by `osmid`, 2) `gdf_nodes` contains `x`
and `y` coordinate columns representing node geometries, 3) `gdf_edges` is
uniquely multi-indexed by `u`, `v`, `key` (following normal MultiDiGraph
structure). This allows you to load any node/edge shapefiles or GeoPackage
layers as GeoDataFrames then convert them to a MultiDiGraph for graph
analysis. Note that any `geometry` attribute on `gdf_nodes` is discarded
since `x` and `y` provide the necessary node geometry information instead.
Parameters
----------
gdf_nodes : geopandas.GeoDataFrame
GeoDataFrame of graph nodes uniquely indexed by osmid
gdf_edges : geopandas.GeoDataFrame
GeoDataFrame of graph edges uniquely multi-indexed by u, v, key
graph_attrs : dict
the new G.graph attribute dict. if None, use crs from gdf_edges as the
only graph-level attribute (gdf_edges must have crs attribute set)
Returns
-------
G : networkx.MultiDiGraph
|
def graph_from_gdfs(gdf_nodes, gdf_edges, graph_attrs=None):
"""
Convert node and edge GeoDataFrames to a MultiDiGraph.
This function is the inverse of `graph_to_gdfs` and is designed to work in
conjunction with it.
However, you can convert arbitrary node and edge GeoDataFrames as long as
1) `gdf_nodes` is uniquely indexed by `osmid`, 2) `gdf_nodes` contains `x`
and `y` coordinate columns representing node geometries, 3) `gdf_edges` is
uniquely multi-indexed by `u`, `v`, `key` (following normal MultiDiGraph
structure). This allows you to load any node/edge shapefiles or GeoPackage
layers as GeoDataFrames then convert them to a MultiDiGraph for graph
analysis. Note that any `geometry` attribute on `gdf_nodes` is discarded
since `x` and `y` provide the necessary node geometry information instead.
Parameters
----------
gdf_nodes : geopandas.GeoDataFrame
GeoDataFrame of graph nodes uniquely indexed by osmid
gdf_edges : geopandas.GeoDataFrame
GeoDataFrame of graph edges uniquely multi-indexed by u, v, key
graph_attrs : dict
the new G.graph attribute dict. if None, use crs from gdf_edges as the
only graph-level attribute (gdf_edges must have crs attribute set)
Returns
-------
G : networkx.MultiDiGraph
"""
if not ("x" in gdf_nodes.columns and "y" in gdf_nodes.columns): # pragma: no cover
msg = "gdf_nodes must contain x and y columns"
raise ValueError(msg)
# if gdf_nodes has a geometry attribute set, drop that column (as we use x
# and y for geometry information) and warn the user if the geometry values
# differ from the coordinates in the x and y columns
if hasattr(gdf_nodes, "geometry"):
try:
all_x_match = (gdf_nodes.geometry.x == gdf_nodes["x"]).all()
all_y_match = (gdf_nodes.geometry.y == gdf_nodes["y"]).all()
assert all_x_match
assert all_y_match
except (AssertionError, ValueError): # pragma: no cover
# AssertionError if x/y coords don't match geometry column
# ValueError if geometry column contains non-point geometry types
warn(
"discarding the gdf_nodes geometry column, though its "
"values differ from the coordinates in the x and y columns",
stacklevel=2,
)
gdf_nodes = gdf_nodes.drop(columns=gdf_nodes.geometry.name)
# create graph and add graph-level attribute dict
if graph_attrs is None:
graph_attrs = {"crs": gdf_edges.crs}
G = nx.MultiDiGraph(**graph_attrs)
# add edges and their attributes to graph, but filter out null attribute
# values so that edges only get attributes with non-null values
attr_names = gdf_edges.columns.to_list()
for (u, v, k), attr_vals in zip(gdf_edges.index, gdf_edges.to_numpy()):
data_all = zip(attr_names, attr_vals)
data = {name: val for name, val in data_all if isinstance(val, list) or pd.notna(val)}
G.add_edge(u, v, key=k, **data)
# add any nodes with no incident edges, since they wouldn't be added above
G.add_nodes_from(set(gdf_nodes.index) - set(G.nodes))
# now all nodes are added, so set nodes' attributes
for col in gdf_nodes.columns:
nx.set_node_attributes(G, name=col, values=gdf_nodes[col].dropna())
utils.log("Created graph from node/edge GeoDataFrames")
return G
|
(gdf_nodes, gdf_edges, graph_attrs=None)
|
52,233 |
osmnx.graph
|
graph_from_place
|
Download and create a graph within the boundaries of some place(s).
The query must be geocodable and OSM must have polygon boundaries for the
geocode result. If OSM does not have a polygon for this place, you can
instead get its street network using the graph_from_address function,
which geocodes the place name to a point and gets the network within some
distance of that point.
If OSM does have polygon boundaries for this place but you're not finding
it, try to vary the query string, pass in a structured query dict, or vary
the which_result argument to use a different geocode result. If you know
the OSM ID of the place, you can retrieve its boundary polygon using the
geocode_to_gdf function, then pass it to the graph_from_polygon function.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
query : string or dict or list
the query or queries to geocode to get place boundary polygon(s)
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside boundary polygon if at least one of
node's neighbors is within the polygon
which_result : int
which geocoding result to use. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one.
buffer_dist : float
deprecated, do not use
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
|
def graph_from_place(
query,
network_type="all",
simplify=True,
retain_all=False,
truncate_by_edge=False,
which_result=None,
buffer_dist=None,
clean_periphery=None,
custom_filter=None,
):
"""
Download and create a graph within the boundaries of some place(s).
The query must be geocodable and OSM must have polygon boundaries for the
geocode result. If OSM does not have a polygon for this place, you can
instead get its street network using the graph_from_address function,
which geocodes the place name to a point and gets the network within some
distance of that point.
If OSM does have polygon boundaries for this place but you're not finding
it, try to vary the query string, pass in a structured query dict, or vary
the which_result argument to use a different geocode result. If you know
the OSM ID of the place, you can retrieve its boundary polygon using the
geocode_to_gdf function, then pass it to the graph_from_polygon function.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
query : string or dict or list
the query or queries to geocode to get place boundary polygon(s)
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside boundary polygon if at least one of
node's neighbors is within the polygon
which_result : int
which geocoding result to use. if None, auto-select the first
(Multi)Polygon or raise an error if OSM doesn't return one.
buffer_dist : float
deprecated, do not use
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
"""
if buffer_dist is not None:
warn(
"The buffer_dist argument has been deprecated and will be removed "
"in the v2.0.0 release. Buffer your query area directly, if desired. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# create a GeoDataFrame with the spatial boundaries of the place(s)
if isinstance(query, (str, dict)):
# if it is a string (place name) or dict (structured place query),
# then it is a single place
gdf_place = geocoder.geocode_to_gdf(
query, which_result=which_result, buffer_dist=buffer_dist
)
elif isinstance(query, list):
# if it is a list, it contains multiple places to get
gdf_place = geocoder.geocode_to_gdf(query, buffer_dist=buffer_dist)
else: # pragma: no cover
msg = "query must be dict, string, or list of strings"
raise TypeError(msg)
# extract the geometry from the GeoDataFrame to use in API query
polygon = gdf_place["geometry"].unary_union
utils.log("Constructed place geometry polygon(s) to query API")
# create graph using this polygon(s) geometry
G = graph_from_polygon(
polygon,
network_type=network_type,
simplify=simplify,
retain_all=retain_all,
truncate_by_edge=truncate_by_edge,
clean_periphery=clean_periphery,
custom_filter=custom_filter,
)
utils.log(f"graph_from_place returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
return G
|
(query, network_type='all', simplify=True, retain_all=False, truncate_by_edge=False, which_result=None, buffer_dist=None, clean_periphery=None, custom_filter=None)
|
52,234 |
osmnx.graph
|
graph_from_point
|
Download and create a graph within some distance of a (lat, lon) point.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
center_point : tuple
the (lat, lon) center point around which to construct the graph
dist : int
retain only those nodes within this many meters of the center of the
graph, with distance determined according to dist_type argument
dist_type : string {"network", "bbox"}
if "bbox", retain only those nodes within a bounding box of the
distance parameter. if "network", retain only those nodes within some
network distance from the center-most node.
network_type : string, {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
clean_periphery : bool,
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
|
def graph_from_point(
center_point,
dist=1000,
dist_type="bbox",
network_type="all",
simplify=True,
retain_all=False,
truncate_by_edge=False,
clean_periphery=None,
custom_filter=None,
):
"""
Download and create a graph within some distance of a (lat, lon) point.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
center_point : tuple
the (lat, lon) center point around which to construct the graph
dist : int
retain only those nodes within this many meters of the center of the
graph, with distance determined according to dist_type argument
dist_type : string {"network", "bbox"}
if "bbox", retain only those nodes within a bounding box of the
distance parameter. if "network", retain only those nodes within some
network distance from the center-most node.
network_type : string, {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside bounding box if at least one of node's
neighbors is within the bounding box
clean_periphery : bool,
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
"""
if dist_type not in {"bbox", "network"}: # pragma: no cover
msg = 'dist_type must be "bbox" or "network"'
raise ValueError(msg)
# create bounding box from center point and distance in each direction
bbox = utils_geo.bbox_from_point(center_point, dist)
# create a graph from the bounding box
G = graph_from_bbox(
bbox=bbox,
network_type=network_type,
simplify=simplify,
retain_all=retain_all,
truncate_by_edge=truncate_by_edge,
clean_periphery=clean_periphery,
custom_filter=custom_filter,
)
if dist_type == "network":
# if dist_type is network, find node in graph nearest to center point
# then truncate graph by network dist from it
node = distance.nearest_nodes(G, X=[center_point[1]], Y=[center_point[0]])[0]
G = truncate.truncate_graph_dist(G, node, max_dist=dist)
utils.log(f"graph_from_point returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
return G
|
(center_point, dist=1000, dist_type='bbox', network_type='all', simplify=True, retain_all=False, truncate_by_edge=False, clean_periphery=None, custom_filter=None)
|
52,235 |
osmnx.graph
|
graph_from_polygon
|
Download and create a graph within the boundaries of a (multi)polygon.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
the shape to get network data within. coordinates should be in
unprojected latitude-longitude degrees (EPSG:4326).
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside boundary polygon if at least one of
node's neighbors is within the polygon
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
|
def graph_from_polygon(
polygon,
network_type="all",
simplify=True,
retain_all=False,
truncate_by_edge=False,
clean_periphery=None,
custom_filter=None,
):
"""
Download and create a graph within the boundaries of a (multi)polygon.
You can use the `settings` module to retrieve a snapshot of historical OSM
data as of a certain date, or to configure the Overpass server timeout,
memory allocation, and other custom settings.
Parameters
----------
polygon : shapely.geometry.Polygon or shapely.geometry.MultiPolygon
the shape to get network data within. coordinates should be in
unprojected latitude-longitude degrees (EPSG:4326).
network_type : string {"all", "all_public", "bike", "drive", "drive_service", "walk"}
what type of street network to get if custom_filter is None
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
truncate_by_edge : bool
if True, retain nodes outside boundary polygon if at least one of
node's neighbors is within the polygon
clean_periphery : bool
deprecated, do not use
custom_filter : string
a custom ways filter to be used instead of the network_type presets
e.g., '["power"~"line"]' or '["highway"~"motorway|trunk"]'. Also pass
in a network_type that is in settings.bidirectional_network_types if
you want graph to be fully bi-directional.
Returns
-------
G : networkx.MultiDiGraph
Notes
-----
Very large query areas use the `utils_geo._consolidate_subdivide_geometry`
function to automatically make multiple requests: see that function's
documentation for caveats.
"""
if clean_periphery is None:
clean_periphery = True
else:
warn(
"The clean_periphery argument has been deprecated and will be removed in "
"the v2.0.0 release. Future behavior will be as though clean_periphery=True. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# verify that the geometry is valid and is a shapely Polygon/MultiPolygon
# before proceeding
if not polygon.is_valid: # pragma: no cover
msg = "The geometry to query within is invalid"
raise ValueError(msg)
if not isinstance(polygon, (Polygon, MultiPolygon)): # pragma: no cover
msg = (
"Geometry must be a shapely Polygon or MultiPolygon. If you "
"requested graph from place name, make sure your query resolves "
"to a Polygon or MultiPolygon, and not some other geometry, like "
"a Point. See OSMnx documentation for details."
)
raise TypeError(msg)
if clean_periphery:
# create a new buffered polygon 0.5km around the desired one
buffer_dist = 500
poly_proj, crs_utm = projection.project_geometry(polygon)
poly_proj_buff = poly_proj.buffer(buffer_dist)
poly_buff, _ = projection.project_geometry(poly_proj_buff, crs=crs_utm, to_latlong=True)
# download the network data from OSM within buffered polygon
response_jsons = _overpass._download_overpass_network(
poly_buff, network_type, custom_filter
)
# create buffered graph from the downloaded data
bidirectional = network_type in settings.bidirectional_network_types
G_buff = _create_graph(response_jsons, retain_all=True, bidirectional=bidirectional)
# truncate buffered graph to the buffered polygon and retain_all for
# now. needed because overpass returns entire ways that also include
# nodes outside the poly if the way (that is, a way with a single OSM
# ID) has a node inside the poly at some point.
G_buff = truncate.truncate_graph_polygon(G_buff, poly_buff, True, truncate_by_edge)
# simplify the graph topology
if simplify:
G_buff = simplification.simplify_graph(G_buff)
# truncate graph by original polygon to return graph within polygon
# caller wants. don't simplify again: this allows us to retain
# intersections along the street that may now only connect 2 street
# segments in the network, but in reality also connect to an
# intersection just outside the polygon
G = truncate.truncate_graph_polygon(G_buff, polygon, retain_all, truncate_by_edge)
# count how many physical streets in buffered graph connect to each
# intersection in un-buffered graph, to retain true counts for each
# intersection, even if some of its neighbors are outside the polygon
spn = stats.count_streets_per_node(G_buff, nodes=G.nodes)
nx.set_node_attributes(G, values=spn, name="street_count")
# if clean_periphery=False, just use the polygon as provided
else:
# download the network data from OSM
response_jsons = _overpass._download_overpass_network(polygon, network_type, custom_filter)
# create graph from the downloaded data
bidirectional = network_type in settings.bidirectional_network_types
G = _create_graph(response_jsons, retain_all=True, bidirectional=bidirectional)
# truncate the graph to the extent of the polygon
G = truncate.truncate_graph_polygon(G, polygon, retain_all, truncate_by_edge)
# simplify the graph topology after truncation. don't truncate after
# simplifying or you may have simplified out to an endpoint beyond the
# truncation distance, which would strip out the entire edge
if simplify:
G = simplification.simplify_graph(G)
# count how many physical streets connect to each intersection/deadend
# note this will be somewhat inaccurate due to periphery effects, so
# it's best to parameterize function with clean_periphery=True
spn = stats.count_streets_per_node(G)
nx.set_node_attributes(G, values=spn, name="street_count")
warn(
"the graph-level street_count attribute will likely be inaccurate "
"when you set clean_periphery=False",
stacklevel=2,
)
utils.log(f"graph_from_polygon returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
return G
|
(polygon, network_type='all', simplify=True, retain_all=False, truncate_by_edge=False, clean_periphery=None, custom_filter=None)
|
52,236 |
osmnx.graph
|
graph_from_xml
|
Create a graph from data in a .osm formatted XML file.
Do not load an XML file generated by OSMnx: this use case is not supported
and may not behave as expected. To save/load graphs to/from disk for later
use in OSMnx, use the `io.save_graphml` and `io.load_graphml` functions
instead.
Parameters
----------
filepath : string or pathlib.Path
path to file containing OSM XML data
bidirectional : bool
if True, create bi-directional edges for one-way streets
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
encoding : string
the XML file's character encoding
Returns
-------
G : networkx.MultiDiGraph
|
def graph_from_xml(
filepath, bidirectional=False, simplify=True, retain_all=False, encoding="utf-8"
):
"""
Create a graph from data in a .osm formatted XML file.
Do not load an XML file generated by OSMnx: this use case is not supported
and may not behave as expected. To save/load graphs to/from disk for later
use in OSMnx, use the `io.save_graphml` and `io.load_graphml` functions
instead.
Parameters
----------
filepath : string or pathlib.Path
path to file containing OSM XML data
bidirectional : bool
if True, create bi-directional edges for one-way streets
simplify : bool
if True, simplify graph topology with the `simplify_graph` function
retain_all : bool
if True, return the entire graph even if it is not connected.
otherwise, retain only the largest weakly connected component.
encoding : string
the XML file's character encoding
Returns
-------
G : networkx.MultiDiGraph
"""
# transmogrify file of OSM XML data into JSON
response_jsons = [osm_xml._overpass_json_from_file(filepath, encoding)]
# create graph using this response JSON
G = _create_graph(response_jsons, bidirectional=bidirectional, retain_all=retain_all)
# simplify the graph topology as the last step
if simplify:
G = simplification.simplify_graph(G)
utils.log(f"graph_from_xml returned graph with {len(G):,} nodes and {len(G.edges):,} edges")
return G
|
(filepath, bidirectional=False, simplify=True, retain_all=False, encoding='utf-8')
|
52,237 |
osmnx.convert
|
graph_to_gdfs
|
Convert a MultiDiGraph to node and/or edge GeoDataFrames.
This function is the inverse of `graph_from_gdfs`.
Parameters
----------
G : networkx.MultiDiGraph
input graph
nodes : bool
if True, convert graph nodes to a GeoDataFrame and return it
edges : bool
if True, convert graph edges to a GeoDataFrame and return it
node_geometry : bool
if True, create a geometry column from node x and y attributes
fill_edge_geometry : bool
if True, fill in missing edge geometry fields using nodes u and v
Returns
-------
geopandas.GeoDataFrame or tuple
gdf_nodes or gdf_edges or tuple of (gdf_nodes, gdf_edges). gdf_nodes
is indexed by osmid and gdf_edges is multi-indexed by u, v, key
following normal MultiDiGraph structure.
|
def graph_to_gdfs(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True):
"""
Convert a MultiDiGraph to node and/or edge GeoDataFrames.
This function is the inverse of `graph_from_gdfs`.
Parameters
----------
G : networkx.MultiDiGraph
input graph
nodes : bool
if True, convert graph nodes to a GeoDataFrame and return it
edges : bool
if True, convert graph edges to a GeoDataFrame and return it
node_geometry : bool
if True, create a geometry column from node x and y attributes
fill_edge_geometry : bool
if True, fill in missing edge geometry fields using nodes u and v
Returns
-------
geopandas.GeoDataFrame or tuple
gdf_nodes or gdf_edges or tuple of (gdf_nodes, gdf_edges). gdf_nodes
is indexed by osmid and gdf_edges is multi-indexed by u, v, key
following normal MultiDiGraph structure.
"""
crs = G.graph["crs"]
if nodes:
if not G.nodes: # pragma: no cover
msg = "graph contains no nodes"
raise ValueError(msg)
uvk, data = zip(*G.nodes(data=True))
if node_geometry:
# convert node x/y attributes to Points for geometry column
node_geoms = (Point(d["x"], d["y"]) for d in data)
gdf_nodes = gpd.GeoDataFrame(data, index=uvk, crs=crs, geometry=list(node_geoms))
else:
gdf_nodes = gpd.GeoDataFrame(data, index=uvk)
gdf_nodes.index = gdf_nodes.index.rename("osmid")
utils.log("Created nodes GeoDataFrame from graph")
if edges:
if not G.edges: # pragma: no cover
msg = "Graph contains no edges"
raise ValueError(msg)
u, v, k, data = zip(*G.edges(keys=True, data=True))
if fill_edge_geometry:
# subroutine to get geometry for every edge: if edge already has
# geometry return it, otherwise create it using the incident nodes
x_lookup = nx.get_node_attributes(G, "x")
y_lookup = nx.get_node_attributes(G, "y")
def _make_edge_geometry(u, v, data, x=x_lookup, y=y_lookup):
if "geometry" in data:
return data["geometry"]
# otherwise
return LineString((Point((x[u], y[u])), Point((x[v], y[v]))))
edge_geoms = map(_make_edge_geometry, u, v, data)
gdf_edges = gpd.GeoDataFrame(data, crs=crs, geometry=list(edge_geoms))
else:
gdf_edges = gpd.GeoDataFrame(data)
if "geometry" not in gdf_edges.columns:
# if no edges have a geometry attribute, create null column
gdf_edges = gdf_edges.set_geometry([None] * len(gdf_edges))
gdf_edges = gdf_edges.set_crs(crs)
# add u, v, key attributes as index
gdf_edges["u"] = u
gdf_edges["v"] = v
gdf_edges["key"] = k
gdf_edges = gdf_edges.set_index(["u", "v", "key"])
utils.log("Created edges GeoDataFrame from graph")
if nodes and edges:
return gdf_nodes, gdf_edges
if nodes:
return gdf_nodes
if edges:
return gdf_edges
# otherwise
msg = "you must request nodes or edges or both"
raise ValueError(msg)
|
(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True)
|
52,239 |
osmnx.routing
|
k_shortest_paths
|
Solve `k` shortest paths from an origin node to a destination node.
Uses Yen's algorithm. See also `shortest_path` to solve just the one
shortest path.
Parameters
----------
G : networkx.MultiDiGraph
input graph
orig : int
origin node ID
dest : int
destination node ID
k : int
number of shortest paths to solve
weight : string
edge attribute to minimize when solving shortest paths. default is
edge length in meters.
Yields
------
path : list
a generator of `k` shortest paths ordered by total weight. each path
is a list of node IDs.
|
def k_shortest_paths(G, orig, dest, k, weight="length"):
"""
Solve `k` shortest paths from an origin node to a destination node.
Uses Yen's algorithm. See also `shortest_path` to solve just the one
shortest path.
Parameters
----------
G : networkx.MultiDiGraph
input graph
orig : int
origin node ID
dest : int
destination node ID
k : int
number of shortest paths to solve
weight : string
edge attribute to minimize when solving shortest paths. default is
edge length in meters.
Yields
------
path : list
a generator of `k` shortest paths ordered by total weight. each path
is a list of node IDs.
"""
_verify_edge_attribute(G, weight)
paths_gen = nx.shortest_simple_paths(convert.to_digraph(G, weight), orig, dest, weight)
yield from itertools.islice(paths_gen, 0, k)
|
(G, orig, dest, k, weight='length')
|
52,240 |
osmnx.io
|
load_graphml
|
Load an OSMnx-saved GraphML file from disk or GraphML string.
This function converts node, edge, and graph-level attributes (serialized
as strings) to their appropriate data types. These can be customized as
needed by passing in dtypes arguments providing types or custom converter
functions. For example, if you want to convert some attribute's values to
`bool`, consider using the built-in `ox.io._convert_bool_string` function
to properly handle "True"/"False" string literals as True/False booleans:
`ox.load_graphml(fp, node_dtypes={my_attr: ox.io._convert_bool_string})`.
If you manually configured the `all_oneway=True` setting, you may need to
manually specify here that edge `oneway` attributes should be type `str`.
Note that you must pass one and only one of `filepath` or `graphml_str`.
If passing `graphml_str`, you may need to decode the bytes read from your
file before converting to string to pass to this function.
Parameters
----------
filepath : string or pathlib.Path
path to the GraphML file
graphml_str : string
a valid and decoded string representation of a GraphML file's contents
node_dtypes : dict
dict of node attribute names:types to convert values' data types. the
type can be a python type or a custom string converter function.
edge_dtypes : dict
dict of edge attribute names:types to convert values' data types. the
type can be a python type or a custom string converter function.
graph_dtypes : dict
dict of graph-level attribute names:types to convert values' data
types. the type can be a python type or a custom string converter
function.
Returns
-------
G : networkx.MultiDiGraph
|
def load_graphml(
filepath=None, graphml_str=None, node_dtypes=None, edge_dtypes=None, graph_dtypes=None
):
"""
Load an OSMnx-saved GraphML file from disk or GraphML string.
This function converts node, edge, and graph-level attributes (serialized
as strings) to their appropriate data types. These can be customized as
needed by passing in dtypes arguments providing types or custom converter
functions. For example, if you want to convert some attribute's values to
`bool`, consider using the built-in `ox.io._convert_bool_string` function
to properly handle "True"/"False" string literals as True/False booleans:
`ox.load_graphml(fp, node_dtypes={my_attr: ox.io._convert_bool_string})`.
If you manually configured the `all_oneway=True` setting, you may need to
manually specify here that edge `oneway` attributes should be type `str`.
Note that you must pass one and only one of `filepath` or `graphml_str`.
If passing `graphml_str`, you may need to decode the bytes read from your
file before converting to string to pass to this function.
Parameters
----------
filepath : string or pathlib.Path
path to the GraphML file
graphml_str : string
a valid and decoded string representation of a GraphML file's contents
node_dtypes : dict
dict of node attribute names:types to convert values' data types. the
type can be a python type or a custom string converter function.
edge_dtypes : dict
dict of edge attribute names:types to convert values' data types. the
type can be a python type or a custom string converter function.
graph_dtypes : dict
dict of graph-level attribute names:types to convert values' data
types. the type can be a python type or a custom string converter
function.
Returns
-------
G : networkx.MultiDiGraph
"""
if (filepath is None and graphml_str is None) or (
filepath is not None and graphml_str is not None
): # pragma: no cover
msg = "You must pass one and only one of `filepath` or `graphml_str`."
raise ValueError(msg)
# specify default graph/node/edge attribute values' data types
default_graph_dtypes = {"simplified": _convert_bool_string}
default_node_dtypes = {
"elevation": float,
"elevation_res": float,
"lat": float,
"lon": float,
"osmid": int,
"street_count": int,
"x": float,
"y": float,
}
default_edge_dtypes = {
"bearing": float,
"grade": float,
"grade_abs": float,
"length": float,
"oneway": _convert_bool_string,
"osmid": int,
"reversed": _convert_bool_string,
"speed_kph": float,
"travel_time": float,
}
# override default graph/node/edge attr types with user-passed types, if any
if graph_dtypes is not None:
default_graph_dtypes.update(graph_dtypes)
if node_dtypes is not None:
default_node_dtypes.update(node_dtypes)
if edge_dtypes is not None:
default_edge_dtypes.update(edge_dtypes)
if filepath is not None:
# read the graphml file from disk
source = filepath
G = nx.read_graphml(
Path(filepath), node_type=default_node_dtypes["osmid"], force_multigraph=True
)
else:
# parse the graphml string
source = "string"
G = nx.parse_graphml(
graphml_str, node_type=default_node_dtypes["osmid"], force_multigraph=True
)
# convert graph/node/edge attribute data types
utils.log("Converting node, edge, and graph-level attribute data types")
G = _convert_graph_attr_types(G, default_graph_dtypes)
G = _convert_node_attr_types(G, default_node_dtypes)
G = _convert_edge_attr_types(G, default_edge_dtypes)
utils.log(f"Loaded graph with {len(G)} nodes and {len(G.edges)} edges from {source!r}")
return G
|
(filepath=None, graphml_str=None, node_dtypes=None, edge_dtypes=None, graph_dtypes=None)
|
52,241 |
osmnx.utils
|
log
|
Write a message to the logger.
This logs to file and/or prints to the console (terminal), depending on
the current configuration of settings.log_file and settings.log_console.
Parameters
----------
message : string
the message to log
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
None
|
def log(message, level=None, name=None, filename=None):
"""
Write a message to the logger.
This logs to file and/or prints to the console (terminal), depending on
the current configuration of settings.log_file and settings.log_console.
Parameters
----------
message : string
the message to log
level : int
one of Python's logger.level constants
name : string
name of the logger
filename : string
name of the log file, without file extension
Returns
-------
None
"""
if level is None:
level = settings.log_level
if name is None:
name = settings.log_name
if filename is None:
filename = settings.log_filename
# if logging to file is turned on
if settings.log_file:
# get the current logger (or create a new one, if none), then log
# message at requested level
logger = _get_logger(level=level, name=name, filename=filename)
if level == lg.DEBUG:
logger.debug(message)
elif level == lg.INFO:
logger.info(message)
elif level == lg.WARNING:
logger.warning(message)
elif level == lg.ERROR:
logger.error(message)
# if logging to console (terminal window) is turned on
if settings.log_console:
# prepend timestamp then convert to ASCII for Windows command prompts
message = f"{ts()} {message}"
message = ud.normalize("NFKD", message).encode("ascii", errors="replace").decode()
try:
# print explicitly to terminal in case Jupyter has captured stdout
if getattr(sys.stdout, "_original_stdstream_copy", None) is not None:
# redirect the Jupyter-captured pipe back to original
os.dup2(sys.stdout._original_stdstream_copy, sys.__stdout__.fileno())
sys.stdout._original_stdstream_copy = None
with redirect_stdout(sys.__stdout__):
print(message, file=sys.__stdout__, flush=True)
except OSError:
# handle pytest on Windows raising OSError from sys.__stdout__
print(message, flush=True) # noqa: T201
|
(message, level=None, name=None, filename=None)
|
52,242 |
osmnx.distance
|
nearest_edges
|
Find the nearest edge to a point or to each of several points.
If `X` and `Y` are single coordinate values, this will return the nearest
edge to that point. If `X` and `Y` are lists of coordinate values, this
will return the nearest edge to each point. This function uses an R-tree
spatial index and minimizes the euclidean distance from each point to the
possible matches. For accurate results, use a projected graph and points.
Parameters
----------
G : networkx.MultiDiGraph
graph in which to find nearest edges
X : float or list
points' x (longitude) coordinates, in same CRS/units as graph and
containing no nulls
Y : float or list
points' y (latitude) coordinates, in same CRS/units as graph and
containing no nulls
interpolate : float
deprecated, do not use
return_dist : bool
optionally also return distance between points and nearest edges
Returns
-------
ne or (ne, dist) : tuple or list
nearest edges as (u, v, key) or optionally a tuple where `dist`
contains distances between the points and their nearest edges
|
def nearest_edges(G, X, Y, interpolate=None, return_dist=False):
"""
Find the nearest edge to a point or to each of several points.
If `X` and `Y` are single coordinate values, this will return the nearest
edge to that point. If `X` and `Y` are lists of coordinate values, this
will return the nearest edge to each point. This function uses an R-tree
spatial index and minimizes the euclidean distance from each point to the
possible matches. For accurate results, use a projected graph and points.
Parameters
----------
G : networkx.MultiDiGraph
graph in which to find nearest edges
X : float or list
points' x (longitude) coordinates, in same CRS/units as graph and
containing no nulls
Y : float or list
points' y (latitude) coordinates, in same CRS/units as graph and
containing no nulls
interpolate : float
deprecated, do not use
return_dist : bool
optionally also return distance between points and nearest edges
Returns
-------
ne or (ne, dist) : tuple or list
nearest edges as (u, v, key) or optionally a tuple where `dist`
contains distances between the points and their nearest edges
"""
is_scalar = False
if not (hasattr(X, "__iter__") and hasattr(Y, "__iter__")):
# make coordinates arrays if user passed non-iterable values
is_scalar = True
X = np.array([X])
Y = np.array([Y])
if np.isnan(X).any() or np.isnan(Y).any(): # pragma: no cover
msg = "`X` and `Y` cannot contain nulls"
raise ValueError(msg)
geoms = convert.graph_to_gdfs(G, nodes=False)["geometry"]
# if no interpolation distance was provided
if interpolate is None:
# build an r-tree spatial index by position for subsequent iloc
rtree = STRtree(geoms)
# use the r-tree to find each point's nearest neighbor and distance
points = [Point(xy) for xy in zip(X, Y)]
pos, dist = rtree.query_nearest(points, all_matches=False, return_distance=True)
# if user passed X/Y lists, the 2nd subarray contains geom indices
if len(pos.shape) > 1:
pos = pos[1]
ne = geoms.iloc[pos].index
# otherwise, if interpolation distance was provided
else:
warn(
"The `interpolate` parameter has been deprecated and will be "
"removed in the v2.0.0 release. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# interpolate points along edges to index with k-d tree or ball tree
uvk_xy = []
for uvk, geom in zip(geoms.index, geoms.to_numpy()):
uvk_xy.extend((uvk, xy) for xy in utils_geo.interpolate_points(geom, interpolate))
labels, xy = zip(*uvk_xy)
vertices = pd.DataFrame(xy, index=labels, columns=["x", "y"])
if projection.is_projected(G.graph["crs"]):
# if projected, use k-d tree for euclidean nearest-neighbor search
if cKDTree is None: # pragma: no cover
msg = "scipy must be installed to search a projected graph"
raise ImportError(msg)
dist, pos = cKDTree(vertices).query(np.array([X, Y]).T, k=1)
ne = vertices.index[pos]
else:
# if unprojected, use ball tree for haversine nearest-neighbor search
if BallTree is None: # pragma: no cover
msg = "scikit-learn must be installed to search an unprojected graph"
raise ImportError(msg)
# haversine requires lat, lon coords in radians
vertices_rad = np.deg2rad(vertices[["y", "x"]])
points_rad = np.deg2rad(np.array([Y, X]).T)
dist, pos = BallTree(vertices_rad, metric="haversine").query(points_rad, k=1)
dist = dist[:, 0] * EARTH_RADIUS_M # convert radians -> meters
ne = vertices.index[pos[:, 0]]
# convert results to correct types for return
ne = list(ne)
dist = list(dist)
if is_scalar:
ne = ne[0]
dist = dist[0]
if return_dist:
return ne, dist
# otherwise
return ne
|
(G, X, Y, interpolate=None, return_dist=False)
|
52,243 |
osmnx.distance
|
nearest_nodes
|
Find the nearest node to a point or to each of several points.
If `X` and `Y` are single coordinate values, this will return the nearest
node to that point. If `X` and `Y` are lists of coordinate values, this
will return the nearest node to each point.
If the graph is projected, this uses a k-d tree for euclidean nearest
neighbor search, which requires that scipy is installed as an optional
dependency. If it is unprojected, this uses a ball tree for haversine
nearest neighbor search, which requires that scikit-learn is installed as
an optional dependency.
Parameters
----------
G : networkx.MultiDiGraph
graph in which to find nearest nodes
X : float or list
points' x (longitude) coordinates, in same CRS/units as graph and
containing no nulls
Y : float or list
points' y (latitude) coordinates, in same CRS/units as graph and
containing no nulls
return_dist : bool
optionally also return distance between points and nearest nodes
Returns
-------
nn or (nn, dist) : int/list or tuple
nearest node IDs or optionally a tuple where `dist` contains distances
between the points and their nearest nodes
|
def nearest_nodes(G, X, Y, return_dist=False):
"""
Find the nearest node to a point or to each of several points.
If `X` and `Y` are single coordinate values, this will return the nearest
node to that point. If `X` and `Y` are lists of coordinate values, this
will return the nearest node to each point.
If the graph is projected, this uses a k-d tree for euclidean nearest
neighbor search, which requires that scipy is installed as an optional
dependency. If it is unprojected, this uses a ball tree for haversine
nearest neighbor search, which requires that scikit-learn is installed as
an optional dependency.
Parameters
----------
G : networkx.MultiDiGraph
graph in which to find nearest nodes
X : float or list
points' x (longitude) coordinates, in same CRS/units as graph and
containing no nulls
Y : float or list
points' y (latitude) coordinates, in same CRS/units as graph and
containing no nulls
return_dist : bool
optionally also return distance between points and nearest nodes
Returns
-------
nn or (nn, dist) : int/list or tuple
nearest node IDs or optionally a tuple where `dist` contains distances
between the points and their nearest nodes
"""
is_scalar = False
if not (hasattr(X, "__iter__") and hasattr(Y, "__iter__")):
# make coordinates arrays if user passed non-iterable values
is_scalar = True
X = np.array([X])
Y = np.array([Y])
if np.isnan(X).any() or np.isnan(Y).any(): # pragma: no cover
msg = "`X` and `Y` cannot contain nulls"
raise ValueError(msg)
nodes = convert.graph_to_gdfs(G, edges=False, node_geometry=False)[["x", "y"]]
if projection.is_projected(G.graph["crs"]):
# if projected, use k-d tree for euclidean nearest-neighbor search
if cKDTree is None: # pragma: no cover
msg = "scipy must be installed to search a projected graph"
raise ImportError(msg)
dist, pos = cKDTree(nodes).query(np.array([X, Y]).T, k=1)
nn = nodes.index[pos]
else:
# if unprojected, use ball tree for haversine nearest-neighbor search
if BallTree is None: # pragma: no cover
msg = "scikit-learn must be installed to search an unprojected graph"
raise ImportError(msg)
# haversine requires lat, lon coords in radians
nodes_rad = np.deg2rad(nodes[["y", "x"]])
points_rad = np.deg2rad(np.array([Y, X]).T)
dist, pos = BallTree(nodes_rad, metric="haversine").query(points_rad, k=1)
dist = dist[:, 0] * EARTH_RADIUS_M # convert radians -> meters
nn = nodes.index[pos[:, 0]]
# convert results to correct types for return
nn = nn.tolist()
dist = dist.tolist()
if is_scalar:
nn = nn[0]
dist = dist[0]
if return_dist:
return nn, dist
# otherwise
return nn
|
(G, X, Y, return_dist=False)
|
52,244 |
osmnx.bearing
|
orientation_entropy
|
Calculate undirected graph's orientation entropy.
Orientation entropy is the entropy of its edges' bidirectional bearings
across evenly spaced bins. Ignores self-loop edges as their bearings are
undefined.
For more info see: Boeing, G. 2019. "Urban Spatial Order: Street Network
Orientation, Configuration, and Entropy." Applied Network Science, 4 (1),
67. https://doi.org/10.1007/s41109-019-0189-1
Parameters
----------
Gu : networkx.MultiGraph
undirected, unprojected graph with `bearing` attributes on each edge
num_bins : int
number of bins; for example, if `num_bins=36` is provided, then each
bin will represent 10 degrees around the compass
min_length : float
ignore edges with `length` attributes less than `min_length`; useful
to ignore the noise of many very short edges
weight : string
if not None, weight edges' bearings by this (non-null) edge attribute.
for example, if "length" is provided, this will return 1 bearing
observation per meter per street, which could result in a very large
`bearings` array.
Returns
-------
entropy : float
the graph's orientation entropy
|
def orientation_entropy(Gu, num_bins=36, min_length=0, weight=None):
"""
Calculate undirected graph's orientation entropy.
Orientation entropy is the entropy of its edges' bidirectional bearings
across evenly spaced bins. Ignores self-loop edges as their bearings are
undefined.
For more info see: Boeing, G. 2019. "Urban Spatial Order: Street Network
Orientation, Configuration, and Entropy." Applied Network Science, 4 (1),
67. https://doi.org/10.1007/s41109-019-0189-1
Parameters
----------
Gu : networkx.MultiGraph
undirected, unprojected graph with `bearing` attributes on each edge
num_bins : int
number of bins; for example, if `num_bins=36` is provided, then each
bin will represent 10 degrees around the compass
min_length : float
ignore edges with `length` attributes less than `min_length`; useful
to ignore the noise of many very short edges
weight : string
if not None, weight edges' bearings by this (non-null) edge attribute.
for example, if "length" is provided, this will return 1 bearing
observation per meter per street, which could result in a very large
`bearings` array.
Returns
-------
entropy : float
the graph's orientation entropy
"""
# check if we were able to import scipy
if scipy is None: # pragma: no cover
msg = "scipy must be installed to calculate entropy"
raise ImportError(msg)
bin_counts, _ = _bearings_distribution(Gu, num_bins, min_length, weight)
return scipy.stats.entropy(bin_counts)
|
(Gu, num_bins=36, min_length=0, weight=None)
|
52,247 |
osmnx.plot
|
plot_figure_ground
|
Plot a figure-ground diagram of a street network.
Parameters
----------
G : networkx.MultiDiGraph
input graph, must be unprojected
address : string
deprecated, do not use
point : tuple
deprecated, do not use
dist : numeric
how many meters to extend north, south, east, west from center point
network_type : string
deprecated, do not use
street_widths : dict
dict keys are street types and values are widths to plot in pixels
default_width : numeric
fallback width in pixels for any street type not in street_widths
color : string
color of the streets
edge_color : string
deprecated, do not use
smooth_joints : bool
deprecated, do not use
pg_kwargs
keyword arguments to pass to plot_graph
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_figure_ground(
G=None,
address=None,
point=None,
dist=805,
network_type="drive_service",
street_widths=None,
default_width=4,
color="w",
edge_color=None,
smooth_joints=None,
**pg_kwargs,
):
"""
Plot a figure-ground diagram of a street network.
Parameters
----------
G : networkx.MultiDiGraph
input graph, must be unprojected
address : string
deprecated, do not use
point : tuple
deprecated, do not use
dist : numeric
how many meters to extend north, south, east, west from center point
network_type : string
deprecated, do not use
street_widths : dict
dict keys are street types and values are widths to plot in pixels
default_width : numeric
fallback width in pixels for any street type not in street_widths
color : string
color of the streets
edge_color : string
deprecated, do not use
smooth_joints : bool
deprecated, do not use
pg_kwargs
keyword arguments to pass to plot_graph
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
if edge_color is None:
edge_color = color
else:
msg = (
"The `edge_color` parameter is deprecated and will be removed in the "
"v2.0.0 release. Use `color` instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
if smooth_joints is None:
smooth_joints = True
else:
msg = (
"The `smooth_joints` parameter is deprecated and will be removed in the "
"v2.0.0 release. In the future this function will behave as though True. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
warn(msg, FutureWarning, stacklevel=2)
# if user did not pass in custom street widths, create a dict of defaults
if street_widths is None:
street_widths = {
"footway": 1.5,
"steps": 1.5,
"pedestrian": 1.5,
"service": 1.5,
"path": 1.5,
"track": 1.5,
"motorway": 6,
}
multiplier = 1.2
dep_msg = (
"The `address`, `point`, and `network_type` parameters are deprecated "
"and will be removed in the v2.0.0 release. Pass `G` instead. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123"
)
# if G was passed in, plot it centered on its node centroid
if G is not None:
gdf_nodes = convert.graph_to_gdfs(G, edges=False, node_geometry=True)
lonlat_point = gdf_nodes.unary_union.centroid.coords[0]
point = tuple(reversed(lonlat_point))
# otherwise get network by address or point (whichever was passed) using a
# dist multiplier to ensure we get more than enough network. simplify in
# non-strict mode to not combine multiple street types into single edge
elif address is not None:
warn(dep_msg, FutureWarning, stacklevel=2)
G, point = graph.graph_from_address(
address,
dist=dist * multiplier,
dist_type="bbox",
network_type=network_type,
simplify=False,
truncate_by_edge=True,
return_coords=True,
)
G = simplification.simplify_graph(G, edge_attrs_differ=["osmid"])
elif point is not None:
warn(dep_msg, FutureWarning, stacklevel=2)
G = graph.graph_from_point(
point,
dist=dist * multiplier,
dist_type="bbox",
network_type=network_type,
simplify=False,
truncate_by_edge=True,
)
G = simplification.simplify_graph(G, edge_attrs_differ=["osmid"])
else: # pragma: no cover
msg = "You must pass an address or lat-lon point or graph."
raise ValueError(msg)
# we need an undirected graph to find every edge incident on a node
Gu = convert.to_undirected(G)
# for each edge, get a linewidth according to street type
edge_linewidths = []
for _, _, d in Gu.edges(keys=False, data=True):
street_type = d["highway"][0] if isinstance(d["highway"], list) else d["highway"]
if street_type in street_widths:
edge_linewidths.append(street_widths[street_type])
else:
edge_linewidths.append(default_width)
if smooth_joints:
# for each node, get a nodesize according to the narrowest incident edge
node_widths = {}
for node in Gu.nodes:
# first, identify all the highway types of this node's incident edges
ie_data = [Gu.get_edge_data(node, nbr) for nbr in Gu.neighbors(node)]
edge_types = [d[min(d)]["highway"] for d in ie_data]
if not edge_types:
# if node has no incident edges, make size zero
node_widths[node] = 0
else:
# flatten the list of edge types
et_flat = []
for et in edge_types:
if isinstance(et, list):
et_flat.extend(et)
else:
et_flat.append(et)
# lookup corresponding width for each edge type in flat list
edge_widths = [street_widths.get(et, default_width) for et in et_flat]
# node diameter should equal largest edge width to make joints
# perfectly smooth. alternatively use min(?) to prevent
# anything larger from extending past smallest street's line.
# circle marker sizes are in area, so use diameter squared.
circle_diameter = max(edge_widths)
circle_area = circle_diameter**2
node_widths[node] = circle_area
# assign the node size to each node in the graph
node_sizes = [node_widths[node] for node in Gu.nodes]
else:
node_sizes = 0
# define the view extents of the plotting figure
bbox = utils_geo.bbox_from_point(point, dist, project_utm=False)
# plot the figure
overrides = {"bbox", "node_size", "node_color", "edge_linewidth"}
kwargs = {k: v for k, v in pg_kwargs.items() if k not in overrides}
fig, ax = plot_graph(
G=Gu,
bbox=bbox,
node_size=node_sizes,
node_color=edge_color,
edge_color=edge_color,
edge_linewidth=edge_linewidths,
**kwargs,
)
return fig, ax
|
(G=None, address=None, point=None, dist=805, network_type='drive_service', street_widths=None, default_width=4, color='w', edge_color=None, smooth_joints=None, **pg_kwargs)
|
52,248 |
osmnx.plot
|
plot_footprints
|
Visualize a GeoDataFrame of geospatial features' footprints.
Parameters
----------
gdf : geopandas.GeoDataFrame
GeoDataFrame of footprints (shapely Polygons and MultiPolygons)
ax : axis
if not None, plot on this preexisting axis
figsize : tuple
if ax is None, create new figure with size (width, height)
color : string
color of the footprints
edge_color : string
color of the edge of the footprints
edge_linewidth : float
width of the edge of the footprints
alpha : float
opacity of the footprints
bgcolor : string
background color of the plot
bbox : tuple
bounding box as (north, south, east, west). if None, will calculate
from the spatial extents of the geometries in gdf
save : bool
if True, save the figure to disk at filepath
show : bool
if True, call pyplot.show() to show the figure
close : bool
if True, call pyplot.close() to close the figure
filepath : string
if save is True, the path to the file. file format determined from
extension. if None, use settings.imgs_folder/image.png
dpi : int
if save is True, the resolution of saved file
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_footprints(
gdf,
ax=None,
figsize=(8, 8),
color="orange",
edge_color="none",
edge_linewidth=0,
alpha=None,
bgcolor="#111111",
bbox=None,
save=False,
show=True,
close=False,
filepath=None,
dpi=600,
):
"""
Visualize a GeoDataFrame of geospatial features' footprints.
Parameters
----------
gdf : geopandas.GeoDataFrame
GeoDataFrame of footprints (shapely Polygons and MultiPolygons)
ax : axis
if not None, plot on this preexisting axis
figsize : tuple
if ax is None, create new figure with size (width, height)
color : string
color of the footprints
edge_color : string
color of the edge of the footprints
edge_linewidth : float
width of the edge of the footprints
alpha : float
opacity of the footprints
bgcolor : string
background color of the plot
bbox : tuple
bounding box as (north, south, east, west). if None, will calculate
from the spatial extents of the geometries in gdf
save : bool
if True, save the figure to disk at filepath
show : bool
if True, call pyplot.show() to show the figure
close : bool
if True, call pyplot.close() to close the figure
filepath : string
if save is True, the path to the file. file format determined from
extension. if None, use settings.imgs_folder/image.png
dpi : int
if save is True, the resolution of saved file
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
if ax is None:
fig, ax = plt.subplots(figsize=figsize, facecolor=bgcolor, frameon=False)
ax.set_facecolor(bgcolor)
else:
fig = ax.figure
# retain only Polygons and MultiPolygons, then plot
gdf = gdf[gdf["geometry"].type.isin({"Polygon", "MultiPolygon"})]
ax = gdf.plot(
ax=ax, facecolor=color, edgecolor=edge_color, linewidth=edge_linewidth, alpha=alpha
)
# determine figure extents
if bbox is None:
west, south, east, north = gdf.total_bounds
else:
north, south, east, west = bbox
# configure axis appearance, save/show figure as specified, and return
ax = _config_ax(ax, gdf.crs, (north, south, east, west), 0)
fig, ax = _save_and_show(fig, ax, save, show, close, filepath, dpi)
return fig, ax
|
(gdf, ax=None, figsize=(8, 8), color='orange', edge_color='none', edge_linewidth=0, alpha=None, bgcolor='#111111', bbox=None, save=False, show=True, close=False, filepath=None, dpi=600)
|
52,249 |
osmnx.plot
|
plot_graph
|
Visualize a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
ax : matplotlib axis
if not None, plot on this preexisting axis
figsize : tuple
if ax is None, create new figure with size (width, height)
bgcolor : string
background color of plot
node_color : string or list
color(s) of the nodes
node_size : int
size of the nodes: if 0, then skip plotting the nodes
node_alpha : float
opacity of the nodes, note: if you passed RGBA values to node_color,
set node_alpha=None to use the alpha channel in node_color
node_edgecolor : string
color of the nodes' markers' borders
node_zorder : int
zorder to plot nodes: edges are always 1, so set node_zorder=0 to plot
nodes below edges
edge_color : string or list
color(s) of the edges' lines
edge_linewidth : float
width of the edges' lines: if 0, then skip plotting the edges
edge_alpha : float
opacity of the edges, note: if you passed RGBA values to edge_color,
set edge_alpha=None to use the alpha channel in edge_color
show : bool
if True, call pyplot.show() to show the figure
close : bool
if True, call pyplot.close() to close the figure
save : bool
if True, save the figure to disk at filepath
filepath : string
if save is True, the path to the file. file format determined from
extension. if None, use settings.imgs_folder/image.png
dpi : int
if save is True, the resolution of saved file
bbox : tuple
bounding box as (north, south, east, west). if None, will calculate
from spatial extents of plotted geometries.
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_graph(
G,
ax=None,
figsize=(8, 8),
bgcolor="#111111",
node_color="w",
node_size=15,
node_alpha=None,
node_edgecolor="none",
node_zorder=1,
edge_color="#999999",
edge_linewidth=1,
edge_alpha=None,
show=True,
close=False,
save=False,
filepath=None,
dpi=300,
bbox=None,
):
"""
Visualize a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
ax : matplotlib axis
if not None, plot on this preexisting axis
figsize : tuple
if ax is None, create new figure with size (width, height)
bgcolor : string
background color of plot
node_color : string or list
color(s) of the nodes
node_size : int
size of the nodes: if 0, then skip plotting the nodes
node_alpha : float
opacity of the nodes, note: if you passed RGBA values to node_color,
set node_alpha=None to use the alpha channel in node_color
node_edgecolor : string
color of the nodes' markers' borders
node_zorder : int
zorder to plot nodes: edges are always 1, so set node_zorder=0 to plot
nodes below edges
edge_color : string or list
color(s) of the edges' lines
edge_linewidth : float
width of the edges' lines: if 0, then skip plotting the edges
edge_alpha : float
opacity of the edges, note: if you passed RGBA values to edge_color,
set edge_alpha=None to use the alpha channel in edge_color
show : bool
if True, call pyplot.show() to show the figure
close : bool
if True, call pyplot.close() to close the figure
save : bool
if True, save the figure to disk at filepath
filepath : string
if save is True, the path to the file. file format determined from
extension. if None, use settings.imgs_folder/image.png
dpi : int
if save is True, the resolution of saved file
bbox : tuple
bounding box as (north, south, east, west). if None, will calculate
from spatial extents of plotted geometries.
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
max_node_size = max(node_size) if hasattr(node_size, "__iter__") else node_size
max_edge_lw = max(edge_linewidth) if hasattr(edge_linewidth, "__iter__") else edge_linewidth
if max_node_size <= 0 and max_edge_lw <= 0: # pragma: no cover
msg = "Either node_size or edge_linewidth must be > 0 to plot something."
raise ValueError(msg)
# create fig, ax as needed
utils.log("Begin plotting the graph...")
if ax is None:
fig, ax = plt.subplots(figsize=figsize, facecolor=bgcolor, frameon=False)
ax.set_facecolor(bgcolor)
else:
fig = ax.figure
if max_edge_lw > 0:
# plot the edges' geometries
gdf_edges = convert.graph_to_gdfs(G, nodes=False)["geometry"]
ax = gdf_edges.plot(ax=ax, color=edge_color, lw=edge_linewidth, alpha=edge_alpha, zorder=1)
if max_node_size > 0:
# scatter plot the nodes' x/y coordinates
gdf_nodes = convert.graph_to_gdfs(G, edges=False, node_geometry=False)[["x", "y"]]
ax.scatter(
x=gdf_nodes["x"],
y=gdf_nodes["y"],
s=node_size,
c=node_color,
alpha=node_alpha,
edgecolor=node_edgecolor,
zorder=node_zorder,
)
# get spatial extents from bbox parameter or the edges' geometries
padding = 0
if bbox is None:
try:
west, south, east, north = gdf_edges.total_bounds
except NameError:
west, south = gdf_nodes.min()
east, north = gdf_nodes.max()
bbox = north, south, east, west
padding = 0.02 # pad 2% to not cut off peripheral nodes' circles
# configure axis appearance, save/show figure as specified, and return
ax = _config_ax(ax, G.graph["crs"], bbox, padding)
fig, ax = _save_and_show(fig, ax, save, show, close, filepath, dpi)
utils.log("Finished plotting the graph")
return fig, ax
|
(G, ax=None, figsize=(8, 8), bgcolor='#111111', node_color='w', node_size=15, node_alpha=None, node_edgecolor='none', node_zorder=1, edge_color='#999999', edge_linewidth=1, edge_alpha=None, show=True, close=False, save=False, filepath=None, dpi=300, bbox=None)
|
52,250 |
osmnx.folium
|
plot_graph_folium
|
Do not use: deprecated.
You can generate and explore interactive web maps of graph nodes, edges,
and/or routes automatically using GeoPandas.GeoDataFrame.explore instead,
for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the
OSMnx examples gallery for complete details and demonstrations.
Parameters
----------
G : networkx.MultiDiGraph
deprecated
graph_map : folium.folium.Map
deprecated
popup_attribute : string
deprecated
tiles : string
deprecated
zoom : int
deprecated
fit_bounds : bool
deprecated
kwargs
deprecated
Returns
-------
folium.folium.Map
|
def plot_graph_folium(
G,
graph_map=None,
popup_attribute=None,
tiles="cartodbpositron",
zoom=1,
fit_bounds=True,
**kwargs,
):
"""
Do not use: deprecated.
You can generate and explore interactive web maps of graph nodes, edges,
and/or routes automatically using GeoPandas.GeoDataFrame.explore instead,
for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the
OSMnx examples gallery for complete details and demonstrations.
Parameters
----------
G : networkx.MultiDiGraph
deprecated
graph_map : folium.folium.Map
deprecated
popup_attribute : string
deprecated
tiles : string
deprecated
zoom : int
deprecated
fit_bounds : bool
deprecated
kwargs
deprecated
Returns
-------
folium.folium.Map
"""
warn(
"The `folium` module has been deprecated and will be removed in the v2.0.0 release. "
"You can generate and explore interactive web maps of graph nodes, edges, "
"and/or routes automatically using GeoPandas.GeoDataFrame.explore instead, "
"for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the "
"OSMnx examples gallery for complete details and demonstrations.",
FutureWarning,
stacklevel=2,
)
# create gdf of all graph edges
gdf_edges = convert.graph_to_gdfs(G, nodes=False)
return _plot_folium(gdf_edges, graph_map, popup_attribute, tiles, zoom, fit_bounds, **kwargs)
|
(G, graph_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, **kwargs)
|
52,251 |
osmnx.plot
|
plot_graph_route
|
Visualize a route along a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
route : list
route as a list of node IDs
route_color : string
color of the route
route_linewidth : int
width of the route line
route_alpha : float
opacity of the route line
orig_dest_size : int
size of the origin and destination nodes
ax : matplotlib axis
if not None, plot route on this preexisting axis instead of creating a
new fig, ax and drawing the underlying graph
pg_kwargs
keyword arguments to pass to plot_graph
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_graph_route(
G,
route,
route_color="r",
route_linewidth=4,
route_alpha=0.5,
orig_dest_size=100,
ax=None,
**pg_kwargs,
):
"""
Visualize a route along a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
route : list
route as a list of node IDs
route_color : string
color of the route
route_linewidth : int
width of the route line
route_alpha : float
opacity of the route line
orig_dest_size : int
size of the origin and destination nodes
ax : matplotlib axis
if not None, plot route on this preexisting axis instead of creating a
new fig, ax and drawing the underlying graph
pg_kwargs
keyword arguments to pass to plot_graph
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
if ax is None:
# plot the graph but not the route, and override any user show/close
# args for now: we'll do that later
overrides = {"show", "save", "close"}
kwargs = {k: v for k, v in pg_kwargs.items() if k not in overrides}
fig, ax = plot_graph(G, show=False, save=False, close=False, **kwargs)
else:
fig = ax.figure
# scatterplot origin and destination points (first/last nodes in route)
x = (G.nodes[route[0]]["x"], G.nodes[route[-1]]["x"])
y = (G.nodes[route[0]]["y"], G.nodes[route[-1]]["y"])
ax.scatter(x, y, s=orig_dest_size, c=route_color, alpha=route_alpha, edgecolor="none")
# assemble the route edge geometries' x and y coords then plot the line
x = []
y = []
for u, v in zip(route[:-1], route[1:]):
# if there are parallel edges, select the shortest in length
data = min(G.get_edge_data(u, v).values(), key=lambda d: d["length"])
if "geometry" in data:
# if geometry attribute exists, add all its coords to list
xs, ys = data["geometry"].xy
x.extend(xs)
y.extend(ys)
else:
# otherwise, the edge is a straight line from node to node
x.extend((G.nodes[u]["x"], G.nodes[v]["x"]))
y.extend((G.nodes[u]["y"], G.nodes[v]["y"]))
ax.plot(x, y, c=route_color, lw=route_linewidth, alpha=route_alpha)
# save and show the figure as specified, passing relevant kwargs
sas_kwargs = {"save", "show", "close", "filepath", "file_format", "dpi"}
kwargs = {k: v for k, v in pg_kwargs.items() if k in sas_kwargs}
fig, ax = _save_and_show(fig, ax, **kwargs)
return fig, ax
|
(G, route, route_color='r', route_linewidth=4, route_alpha=0.5, orig_dest_size=100, ax=None, **pg_kwargs)
|
52,252 |
osmnx.plot
|
plot_graph_routes
|
Visualize several routes along a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
routes : list
routes as a list of lists of node IDs
route_colors : string or list
if string, 1 color for all routes. if list, the colors for each route.
route_linewidths : int or list
if int, 1 linewidth for all routes. if list, the linewidth for each route.
pgr_kwargs
keyword arguments to pass to plot_graph_route
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_graph_routes(G, routes, route_colors="r", route_linewidths=4, **pgr_kwargs):
"""
Visualize several routes along a graph.
Parameters
----------
G : networkx.MultiDiGraph
input graph
routes : list
routes as a list of lists of node IDs
route_colors : string or list
if string, 1 color for all routes. if list, the colors for each route.
route_linewidths : int or list
if int, 1 linewidth for all routes. if list, the linewidth for each route.
pgr_kwargs
keyword arguments to pass to plot_graph_route
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
# check for valid arguments
if not all(isinstance(r, list) for r in routes): # pragma: no cover
msg = "routes must be a list of route lists"
raise ValueError(msg)
if len(routes) <= 1: # pragma: no cover
msg = "You must pass more than 1 route"
raise ValueError(msg)
if isinstance(route_colors, str):
route_colors = [route_colors] * len(routes)
if len(routes) != len(route_colors): # pragma: no cover
msg = "route_colors list must have same length as routes"
raise ValueError(msg)
if isinstance(route_linewidths, int):
route_linewidths = [route_linewidths] * len(routes)
if len(routes) != len(route_linewidths): # pragma: no cover
msg = "route_linewidths list must have same length as routes"
raise ValueError(msg)
# plot the graph and the first route
overrides = {"route", "route_color", "route_linewidth", "show", "save", "close"}
kwargs = {k: v for k, v in pgr_kwargs.items() if k not in overrides}
fig, ax = plot_graph_route(
G,
route=routes[0],
route_color=route_colors[0],
route_linewidth=route_linewidths[0],
show=False,
save=False,
close=False,
**kwargs,
)
# plot the subsequent routes on top of existing ax
overrides.update({"ax"})
kwargs = {k: v for k, v in pgr_kwargs.items() if k not in overrides}
r_rc_rlw = zip(routes[1:], route_colors[1:], route_linewidths[1:])
for route, route_color, route_linewidth in r_rc_rlw:
fig, ax = plot_graph_route(
G,
route=route,
route_color=route_color,
route_linewidth=route_linewidth,
show=False,
save=False,
close=False,
ax=ax,
**kwargs,
)
# save and show the figure as specified, passing relevant kwargs
sas_kwargs = {"save", "show", "close", "filepath", "file_format", "dpi"}
kwargs = {k: v for k, v in pgr_kwargs.items() if k in sas_kwargs}
fig, ax = _save_and_show(fig, ax, **kwargs)
return fig, ax
|
(G, routes, route_colors='r', route_linewidths=4, **pgr_kwargs)
|
52,253 |
osmnx.plot
|
plot_orientation
|
Plot a polar histogram of a spatial network's bidirectional edge bearings.
Ignores self-loop edges as their bearings are undefined.
For more info see: Boeing, G. 2019. "Urban Spatial Order: Street Network
Orientation, Configuration, and Entropy." Applied Network Science, 4 (1),
67. https://doi.org/10.1007/s41109-019-0189-1
Parameters
----------
Gu : networkx.MultiGraph
undirected, unprojected graph with `bearing` attributes on each edge
num_bins : int
number of bins; for example, if `num_bins=36` is provided, then each
bin will represent 10 degrees around the compass
min_length : float
ignore edges with `length` attributes less than `min_length`
weight : string
if not None, weight edges' bearings by this (non-null) edge attribute
ax : matplotlib.axes.PolarAxesSubplot
if not None, plot on this preexisting axis; must have projection=polar
figsize : tuple
if ax is None, create new figure with size (width, height)
area : bool
if True, set bar length so area is proportional to frequency,
otherwise set bar length so height is proportional to frequency
color : string
color of histogram bars
edgecolor : string
color of histogram bar edges
linewidth : float
width of histogram bar edges
alpha : float
opacity of histogram bars
title : string
title for plot
title_y : float
y position to place title
title_font : dict
the title's fontdict to pass to matplotlib
xtick_font : dict
the xtick labels' fontdict to pass to matplotlib
Returns
-------
fig, ax : tuple
matplotlib figure, axis
|
def plot_orientation(
Gu,
num_bins=36,
min_length=0,
weight=None,
ax=None,
figsize=(5, 5),
area=True,
color="#003366",
edgecolor="k",
linewidth=0.5,
alpha=0.7,
title=None,
title_y=1.05,
title_font=None,
xtick_font=None,
):
"""
Plot a polar histogram of a spatial network's bidirectional edge bearings.
Ignores self-loop edges as their bearings are undefined.
For more info see: Boeing, G. 2019. "Urban Spatial Order: Street Network
Orientation, Configuration, and Entropy." Applied Network Science, 4 (1),
67. https://doi.org/10.1007/s41109-019-0189-1
Parameters
----------
Gu : networkx.MultiGraph
undirected, unprojected graph with `bearing` attributes on each edge
num_bins : int
number of bins; for example, if `num_bins=36` is provided, then each
bin will represent 10 degrees around the compass
min_length : float
ignore edges with `length` attributes less than `min_length`
weight : string
if not None, weight edges' bearings by this (non-null) edge attribute
ax : matplotlib.axes.PolarAxesSubplot
if not None, plot on this preexisting axis; must have projection=polar
figsize : tuple
if ax is None, create new figure with size (width, height)
area : bool
if True, set bar length so area is proportional to frequency,
otherwise set bar length so height is proportional to frequency
color : string
color of histogram bars
edgecolor : string
color of histogram bar edges
linewidth : float
width of histogram bar edges
alpha : float
opacity of histogram bars
title : string
title for plot
title_y : float
y position to place title
title_font : dict
the title's fontdict to pass to matplotlib
xtick_font : dict
the xtick labels' fontdict to pass to matplotlib
Returns
-------
fig, ax : tuple
matplotlib figure, axis
"""
_verify_mpl()
if title_font is None:
title_font = {"family": "DejaVu Sans", "size": 24, "weight": "bold"}
if xtick_font is None:
xtick_font = {
"family": "DejaVu Sans",
"size": 10,
"weight": "bold",
"alpha": 1.0,
"zorder": 3,
}
# get the bearings' distribution's bin counts and edges
bin_counts, bin_edges = bearing._bearings_distribution(Gu, num_bins, min_length, weight)
# positions: where to center each bar. ignore the last bin edge, because
# it's the same as the first (i.e., 0 degrees = 360 degrees)
positions = np.radians(bin_edges[:-1])
# width: make bars fill the circumference without gaps or overlaps
width = 2 * np.pi / num_bins
# radius: how long to make each bar. set bar length so either the bar area
# (ie, via sqrt) or the bar height is proportional to the bin's frequency
bin_frequency = bin_counts / bin_counts.sum()
radius = np.sqrt(bin_frequency) if area else bin_frequency
# create ax (if necessary) then set N at top and go clockwise
if ax is None:
fig, ax = plt.subplots(figsize=figsize, subplot_kw={"projection": "polar"})
else:
fig = ax.figure
ax.set_theta_zero_location("N")
ax.set_theta_direction("clockwise")
ax.set_ylim(top=radius.max())
# configure the y-ticks and remove their labels
ax.set_yticks(np.linspace(0, radius.max(), 5))
ax.set_yticklabels(labels="")
# configure the x-ticks and their labels
xticklabels = ["N", "", "E", "", "S", "", "W", ""]
ax.set_xticks(ax.get_xticks())
ax.set_xticklabels(labels=xticklabels, fontdict=xtick_font)
ax.tick_params(axis="x", which="major", pad=-2)
# draw the bars
ax.bar(
positions,
height=radius,
width=width,
align="center",
bottom=0,
zorder=2,
color=color,
edgecolor=edgecolor,
linewidth=linewidth,
alpha=alpha,
)
if title:
ax.set_title(title, y=title_y, fontdict=title_font)
fig.tight_layout()
return fig, ax
|
(Gu, num_bins=36, min_length=0, weight=None, ax=None, figsize=(5, 5), area=True, color='#003366', edgecolor='k', linewidth=0.5, alpha=0.7, title=None, title_y=1.05, title_font=None, xtick_font=None)
|
52,254 |
osmnx.folium
|
plot_route_folium
|
Do not use: deprecated.
You can generate and explore interactive web maps of graph nodes, edges,
and/or routes automatically using GeoPandas.GeoDataFrame.explore instead,
for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the
OSMnx examples gallery for complete details and demonstrations.
Parameters
----------
G : networkx.MultiDiGraph
deprecated
route : list
deprecated
route_map : folium.folium.Map
deprecated
popup_attribute : string
deprecated
tiles : string
deprecated
zoom : int
deprecated
fit_bounds : bool
deprecated
kwargs
deprecated
Returns
-------
folium.folium.Map
|
def plot_route_folium(
G,
route,
route_map=None,
popup_attribute=None,
tiles="cartodbpositron",
zoom=1,
fit_bounds=True,
**kwargs,
):
"""
Do not use: deprecated.
You can generate and explore interactive web maps of graph nodes, edges,
and/or routes automatically using GeoPandas.GeoDataFrame.explore instead,
for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the
OSMnx examples gallery for complete details and demonstrations.
Parameters
----------
G : networkx.MultiDiGraph
deprecated
route : list
deprecated
route_map : folium.folium.Map
deprecated
popup_attribute : string
deprecated
tiles : string
deprecated
zoom : int
deprecated
fit_bounds : bool
deprecated
kwargs
deprecated
Returns
-------
folium.folium.Map
"""
warn(
"The `folium` module has been deprecated and will be removed in the v2.0.0 release. "
"You can generate and explore interactive web maps of graph nodes, edges, "
"and/or routes automatically using GeoPandas.GeoDataFrame.explore instead, "
"for example like: `ox.graph_to_gdfs(G, nodes=False).explore()`. See the "
"OSMnx examples gallery for complete details and demonstrations.",
FutureWarning,
stacklevel=2,
)
# create gdf of the route edges in order
node_pairs = zip(route[:-1], route[1:])
uvk = ((u, v, min(G[u][v].items(), key=lambda k: k[1]["length"])[0]) for u, v in node_pairs)
gdf_edges = convert.graph_to_gdfs(G.subgraph(route), nodes=False).loc[uvk]
return _plot_folium(gdf_edges, route_map, popup_attribute, tiles, zoom, fit_bounds, **kwargs)
|
(G, route, route_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, **kwargs)
|
52,255 |
osmnx.projection
|
project_gdf
|
Project a GeoDataFrame from its current CRS to another.
If `to_latlong` is `True`, this projects the GeoDataFrame to the CRS
defined by `settings.default_crs`, otherwise it projects it to the CRS
defined by `to_crs`. If `to_crs` is `None`, it projects it to the CRS of
an appropriate UTM zone given `gdf`'s bounds.
Parameters
----------
gdf : geopandas.GeoDataFrame
the GeoDataFrame to be projected
to_crs : string or pyproj.CRS
if None, project to an appropriate UTM zone, otherwise project to
this CRS
to_latlong : bool
if True, project to `settings.default_crs` and ignore `to_crs`
Returns
-------
gdf_proj : geopandas.GeoDataFrame
the projected GeoDataFrame
|
def project_gdf(gdf, to_crs=None, to_latlong=False):
"""
Project a GeoDataFrame from its current CRS to another.
If `to_latlong` is `True`, this projects the GeoDataFrame to the CRS
defined by `settings.default_crs`, otherwise it projects it to the CRS
defined by `to_crs`. If `to_crs` is `None`, it projects it to the CRS of
an appropriate UTM zone given `gdf`'s bounds.
Parameters
----------
gdf : geopandas.GeoDataFrame
the GeoDataFrame to be projected
to_crs : string or pyproj.CRS
if None, project to an appropriate UTM zone, otherwise project to
this CRS
to_latlong : bool
if True, project to `settings.default_crs` and ignore `to_crs`
Returns
-------
gdf_proj : geopandas.GeoDataFrame
the projected GeoDataFrame
"""
if gdf.crs is None or len(gdf) < 1: # pragma: no cover
msg = "GeoDataFrame must have a valid CRS and cannot be empty"
raise ValueError(msg)
# if to_latlong is True, project the gdf to the default_crs
if to_latlong:
to_crs = settings.default_crs
# else if to_crs is None, project gdf to an appropriate UTM zone
elif to_crs is None:
to_crs = gdf.estimate_utm_crs()
# project the gdf
gdf_proj = gdf.to_crs(to_crs)
crs_desc = f"{gdf_proj.crs.to_string()} / {gdf_proj.crs.name}"
utils.log(f"Projected GeoDataFrame to {crs_desc!r}")
return gdf_proj
|
(gdf, to_crs=None, to_latlong=False)
|
52,256 |
osmnx.projection
|
project_graph
|
Project a graph from its current CRS to another.
If `to_latlong` is `True`, this projects the GeoDataFrame to the CRS
defined by `settings.default_crs`, otherwise it projects it to the CRS
defined by `to_crs`. If `to_crs` is `None`, it projects it to the CRS of
an appropriate UTM zone given `G`'s bounds.
Parameters
----------
G : networkx.MultiDiGraph
the graph to be projected
to_crs : string or pyproj.CRS
if None, project to an appropriate UTM zone, otherwise project to
this CRS
to_latlong : bool
if True, project to `settings.default_crs` and ignore `to_crs`
Returns
-------
G_proj : networkx.MultiDiGraph
the projected graph
|
def project_graph(G, to_crs=None, to_latlong=False):
"""
Project a graph from its current CRS to another.
If `to_latlong` is `True`, this projects the GeoDataFrame to the CRS
defined by `settings.default_crs`, otherwise it projects it to the CRS
defined by `to_crs`. If `to_crs` is `None`, it projects it to the CRS of
an appropriate UTM zone given `G`'s bounds.
Parameters
----------
G : networkx.MultiDiGraph
the graph to be projected
to_crs : string or pyproj.CRS
if None, project to an appropriate UTM zone, otherwise project to
this CRS
to_latlong : bool
if True, project to `settings.default_crs` and ignore `to_crs`
Returns
-------
G_proj : networkx.MultiDiGraph
the projected graph
"""
if to_latlong:
to_crs = settings.default_crs
# STEP 1: PROJECT THE NODES
gdf_nodes = convert.graph_to_gdfs(G, edges=False)
# create new lat/lon columns to preserve lat/lon for later reference if
# cols do not already exist (ie, don't overwrite in later re-projections)
if "lon" not in gdf_nodes.columns or "lat" not in gdf_nodes.columns:
gdf_nodes["lon"] = gdf_nodes["x"]
gdf_nodes["lat"] = gdf_nodes["y"]
# project the nodes GeoDataFrame and extract the projected x/y values
gdf_nodes_proj = project_gdf(gdf_nodes, to_crs=to_crs)
gdf_nodes_proj["x"] = gdf_nodes_proj["geometry"].x
gdf_nodes_proj["y"] = gdf_nodes_proj["geometry"].y
to_crs = gdf_nodes_proj.crs
gdf_nodes_proj = gdf_nodes_proj.drop(columns=["geometry"])
# STEP 2: PROJECT THE EDGES
if "simplified" in G.graph and G.graph["simplified"]:
# if graph has previously been simplified, project the edge geometries
gdf_edges = convert.graph_to_gdfs(G, nodes=False, fill_edge_geometry=False)
gdf_edges_proj = project_gdf(gdf_edges, to_crs=to_crs)
else:
# if not, you don't have to project these edges because the nodes
# contain all the spatial data in the graph (unsimplified edges have
# no geometry attributes)
gdf_edges_proj = convert.graph_to_gdfs(G, nodes=False, fill_edge_geometry=False).drop(
columns=["geometry"]
)
# STEP 3: REBUILD GRAPH
# turn projected node/edge gdfs into a graph and update its CRS attribute
G_proj = convert.graph_from_gdfs(gdf_nodes_proj, gdf_edges_proj, G.graph)
G_proj.graph["crs"] = to_crs
utils.log(f"Projected graph with {len(G)} nodes and {len(G.edges)} edges")
return G_proj
|
(G, to_crs=None, to_latlong=False)
|
52,259 |
osmnx.io
|
save_graph_geopackage
|
Save graph nodes and edges to disk as layers in a GeoPackage file.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the GeoPackage file including extension. if None, use default
data folder + graph.gpkg
encoding : string
the character encoding for the saved file
directed : bool
if False, save one edge for each undirected edge in the graph but
retain original oneway and to/from information as edge attributes; if
True, save one edge for each directed edge in the graph
Returns
-------
None
|
def save_graph_geopackage(G, filepath=None, encoding="utf-8", directed=False):
"""
Save graph nodes and edges to disk as layers in a GeoPackage file.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the GeoPackage file including extension. if None, use default
data folder + graph.gpkg
encoding : string
the character encoding for the saved file
directed : bool
if False, save one edge for each undirected edge in the graph but
retain original oneway and to/from information as edge attributes; if
True, save one edge for each directed edge in the graph
Returns
-------
None
"""
# default filepath if none was provided
filepath = Path(settings.data_folder) / "graph.gpkg" if filepath is None else Path(filepath)
# if save folder does not already exist, create it
filepath.parent.mkdir(parents=True, exist_ok=True)
# convert graph to gdfs and stringify non-numeric columns
if directed:
gdf_nodes, gdf_edges = convert.graph_to_gdfs(G)
else:
gdf_nodes, gdf_edges = convert.graph_to_gdfs(convert.to_undirected(G))
gdf_nodes = _stringify_nonnumeric_cols(gdf_nodes)
gdf_edges = _stringify_nonnumeric_cols(gdf_edges)
# save the nodes and edges as GeoPackage layers
gdf_nodes.to_file(filepath, layer="nodes", driver="GPKG", index=True, encoding=encoding)
gdf_edges.to_file(filepath, layer="edges", driver="GPKG", index=True, encoding=encoding)
utils.log(f"Saved graph as GeoPackage at {filepath!r}")
|
(G, filepath=None, encoding='utf-8', directed=False)
|
52,260 |
osmnx.io
|
save_graph_shapefile
|
Do not use: deprecated. Use the save_graph_geopackage function instead.
The Shapefile format is proprietary and outdated. Instead, use the
superior GeoPackage file format via the save_graph_geopackage function.
See http://switchfromshapefile.org/ for more information.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the shapefiles folder (no file extension). if None, use
default data folder + graph_shapefile
encoding : string
the character encoding for the saved files
directed : bool
if False, save one edge for each undirected edge in the graph but
retain original oneway and to/from information as edge attributes; if
True, save one edge for each directed edge in the graph
Returns
-------
None
|
def save_graph_shapefile(G, filepath=None, encoding="utf-8", directed=False):
"""
Do not use: deprecated. Use the save_graph_geopackage function instead.
The Shapefile format is proprietary and outdated. Instead, use the
superior GeoPackage file format via the save_graph_geopackage function.
See http://switchfromshapefile.org/ for more information.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the shapefiles folder (no file extension). if None, use
default data folder + graph_shapefile
encoding : string
the character encoding for the saved files
directed : bool
if False, save one edge for each undirected edge in the graph but
retain original oneway and to/from information as edge attributes; if
True, save one edge for each directed edge in the graph
Returns
-------
None
"""
warn(
"The `save_graph_shapefile` function is deprecated and will be removed "
"in the v2.0.0 release. Instead, use the `save_graph_geopackage` function "
"to save graphs as GeoPackage files for subsequent GIS analysis. "
"See the OSMnx v2 migration guide: https://github.com/gboeing/osmnx/issues/1123",
FutureWarning,
stacklevel=2,
)
# default filepath if none was provided
filepath = (
Path(settings.data_folder) / "graph_shapefile" if filepath is None else Path(filepath)
)
# if save folder does not already exist, create it (shapefiles
# get saved as set of files)
filepath.mkdir(parents=True, exist_ok=True)
filepath_nodes = filepath / "nodes.shp"
filepath_edges = filepath / "edges.shp"
# convert graph to gdfs and stringify non-numeric columns
if directed:
gdf_nodes, gdf_edges = convert.graph_to_gdfs(G)
else:
gdf_nodes, gdf_edges = convert.graph_to_gdfs(convert.to_undirected(G))
gdf_nodes = _stringify_nonnumeric_cols(gdf_nodes)
gdf_edges = _stringify_nonnumeric_cols(gdf_edges)
# save the nodes and edges as separate ESRI shapefiles
gdf_nodes.to_file(filepath_nodes, driver="ESRI Shapefile", index=True, encoding=encoding)
gdf_edges.to_file(filepath_edges, driver="ESRI Shapefile", index=True, encoding=encoding)
utils.log(f"Saved graph as shapefiles at {filepath!r}")
|
(G, filepath=None, encoding='utf-8', directed=False)
|
52,261 |
osmnx.io
|
save_graph_xml
|
Save graph to disk as an OSM-formatted XML .osm file.
This function exists only to allow serialization to the .osm file format
for applications that require it, and has constraints to conform to that.
As such, this function has a limited use case which does not include
saving/loading graphs for subsequent OSMnx analysis. To save/load graphs
to/from disk for later use in OSMnx, use the `io.save_graphml` and
`io.load_graphml` functions instead. To load a graph from a .osm file that
you have downloaded or generated elsewhere, use the `graph.graph_from_xml`
function.
Parameters
----------
data : networkx.MultiDiGraph
the input graph
filepath : string or pathlib.Path
do not use, deprecated
node_tags : list
do not use, deprecated
node_attrs: list
do not use, deprecated
edge_tags : list
do not use, deprecated
edge_attrs : list
do not use, deprecated
oneway : bool
do not use, deprecated
merge_edges : bool
do not use, deprecated
edge_tag_aggs : tuple
do not use, deprecated
api_version : float
do not use, deprecated
precision : int
do not use, deprecated
way_tag_aggs : dict
Keys are OSM way tag keys and values are aggregation functions
(anything accepted as an argument by pandas.agg). Allows user to
aggregate graph edge attribute values into single OSM way values. If
None, or if some tag's key does not exist in the dict, the way
attribute will be assigned the value of the first edge of the way.
Returns
-------
None
|
def save_graph_xml(
data,
filepath=None,
node_tags=None,
node_attrs=None,
edge_tags=None,
edge_attrs=None,
oneway=None,
merge_edges=None,
edge_tag_aggs=None,
api_version=None,
precision=None,
way_tag_aggs=None,
):
"""
Save graph to disk as an OSM-formatted XML .osm file.
This function exists only to allow serialization to the .osm file format
for applications that require it, and has constraints to conform to that.
As such, this function has a limited use case which does not include
saving/loading graphs for subsequent OSMnx analysis. To save/load graphs
to/from disk for later use in OSMnx, use the `io.save_graphml` and
`io.load_graphml` functions instead. To load a graph from a .osm file that
you have downloaded or generated elsewhere, use the `graph.graph_from_xml`
function.
Parameters
----------
data : networkx.MultiDiGraph
the input graph
filepath : string or pathlib.Path
do not use, deprecated
node_tags : list
do not use, deprecated
node_attrs: list
do not use, deprecated
edge_tags : list
do not use, deprecated
edge_attrs : list
do not use, deprecated
oneway : bool
do not use, deprecated
merge_edges : bool
do not use, deprecated
edge_tag_aggs : tuple
do not use, deprecated
api_version : float
do not use, deprecated
precision : int
do not use, deprecated
way_tag_aggs : dict
Keys are OSM way tag keys and values are aggregation functions
(anything accepted as an argument by pandas.agg). Allows user to
aggregate graph edge attribute values into single OSM way values. If
None, or if some tag's key does not exist in the dict, the way
attribute will be assigned the value of the first edge of the way.
Returns
-------
None
"""
osm_xml._save_graph_xml(
data,
filepath,
node_tags,
node_attrs,
edge_tags,
edge_attrs,
oneway,
merge_edges,
edge_tag_aggs,
api_version,
precision,
way_tag_aggs,
)
|
(data, filepath=None, node_tags=None, node_attrs=None, edge_tags=None, edge_attrs=None, oneway=None, merge_edges=None, edge_tag_aggs=None, api_version=None, precision=None, way_tag_aggs=None)
|
52,262 |
osmnx.io
|
save_graphml
|
Save graph to disk as GraphML file.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the GraphML file including extension. if None, use default
data folder + graph.graphml
gephi : bool
if True, give each edge a unique key/id to work around Gephi's
interpretation of the GraphML specification
encoding : string
the character encoding for the saved file
Returns
-------
None
|
def save_graphml(G, filepath=None, gephi=False, encoding="utf-8"):
"""
Save graph to disk as GraphML file.
Parameters
----------
G : networkx.MultiDiGraph
input graph
filepath : string or pathlib.Path
path to the GraphML file including extension. if None, use default
data folder + graph.graphml
gephi : bool
if True, give each edge a unique key/id to work around Gephi's
interpretation of the GraphML specification
encoding : string
the character encoding for the saved file
Returns
-------
None
"""
# default filepath if none was provided
filepath = Path(settings.data_folder) / "graph.graphml" if filepath is None else Path(filepath)
# if save folder does not already exist, create it
filepath.parent.mkdir(parents=True, exist_ok=True)
if gephi:
# for gephi compatibility, each edge's key must be unique as an id
uvkd = ((u, v, k, d) for k, (u, v, d) in enumerate(G.edges(keys=False, data=True)))
G = nx.MultiDiGraph(uvkd)
else:
# make a copy to not mutate original graph object caller passed in
G = G.copy()
# stringify all the graph attribute values
for attr, value in G.graph.items():
G.graph[attr] = str(value)
# stringify all the node attribute values
for _, data in G.nodes(data=True):
for attr, value in data.items():
data[attr] = str(value)
# stringify all the edge attribute values
for _, _, data in G.edges(keys=False, data=True):
for attr, value in data.items():
data[attr] = str(value)
nx.write_graphml(G, path=filepath, encoding=encoding)
utils.log(f"Saved graph as GraphML file at {filepath!r}")
|
(G, filepath=None, gephi=False, encoding='utf-8')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.