id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
154,945 | from __future__ import annotations as _annotations
import enum
from collections import defaultdict
from datetime import date
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Request, UploadFile
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from fastui.forms import FormFile, SelectSearchResponse, Textarea, fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr, field_validator
from pydantic_core import PydanticCustomError
from .shared import demo_page
class BigModel(BaseModel):
name: str | None = Field(
None, description='This field is not required, it must start with a capital letter if provided'
)
info: Annotated[str | None, Textarea(rows=5)] = Field(None, description='Optional free text information about you.')
profile_pic: Annotated[UploadFile, FormFile(accept='image/*', max_size=16_000)] = Field(
description='Upload a profile picture, must not be more than 16kb'
)
profile_pics: Annotated[list[UploadFile], FormFile(accept='image/*')] | None = Field(
None, description='Upload multiple images'
)
dob: date = Field(title='Date of Birth', description='Your date of birth, this is required hence bold')
human: bool | None = Field(
None, title='Is human', description='Are you human?', json_schema_extra={'mode': 'switch'}
)
size: SizeModel
position: tuple[
Annotated[int, Field(description='X Coordinate')],
Annotated[int, Field(description='Y Coordinate')],
]
def name_validator(cls, v: str | None) -> str:
if v and v[0].islower():
raise PydanticCustomError('lower', 'Name must start with a capital letter')
return v
class GoToEvent(BaseModel):
# can be a path or a full URL
url: Union[str, None] = None
query: Union[Dict[str, Union[str, float, None]], None] = None
target: Union[Literal['_blank'], None] = None
type: Literal['go-to'] = 'go-to'
def fastui_form(model: _t.Type[FormModel]) -> fastapi_params.Depends:
async def run_fastui_form(request: fastapi.Request):
async with request.form() as form_data:
model_data = unflatten(form_data)
try:
return model.model_validate(model_data)
except pydantic.ValidationError as e:
raise fastapi.HTTPException(
status_code=422,
detail={'form': e.errors(include_input=False, include_url=False, include_context=False)},
)
return fastapi.Depends(run_fastui_form)
async def big_form_post(form: Annotated[BigModel, fastui_form(BigModel)]):
print(form)
return [c.FireEvent(event=GoToEvent(url='/'))] | null |
154,946 | from __future__ import annotations as _annotations
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from .shared import demo_page
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def api_index() -> list[AnyComponent]:
# language=markdown
markdown = """\
This site provides a demo of [FastUI](https://github.com/pydantic/FastUI), the code for the demo
is [here](https://github.com/pydantic/FastUI/tree/main/demo).
The following components are demonstrated:
* `Markdown` — that's me :-)
* `Text`— example [here](/components#text)
* `Paragraph` — example [here](/components#paragraph)
* `PageTitle` — you'll see the title in the browser tab change when you navigate through the site
* `Heading` — example [here](/components#heading)
* `Code` — example [here](/components#code)
* `Button` — example [here](/components#button-and-modal)
* `Link` — example [here](/components#link-list)
* `LinkList` — example [here](/components#link-list)
* `Navbar` — see the top of this page
* `Footer` — see the bottom of this page
* `Modal` — static example [here](/components#button-and-modal), dynamic content example [here](/components#dynamic-modal)
* `ServerLoad` — see [dynamic modal example](/components#dynamic-modal) and [SSE example](/components#server-load-sse)
* `Image` - example [here](/components#image)
* `Iframe` - example [here](/components#iframe)
* `Video` - example [here](/components#video)
* `Table` — See [cities table](/table/cities) and [users table](/table/users)
* `Pagination` — See the bottom of the [cities table](/table/cities)
* `ModelForm` — See [forms](/forms/login)
Authentication is supported via:
* token based authentication — see [here](/auth/login/password) for an example of password authentication
* GitHub OAuth — see [here](/auth/login/github) for an example of GitHub OAuth login
"""
return demo_page(c.Markdown(text=markdown)) | null |
154,947 | from __future__ import annotations as _annotations
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from .shared import demo_page
async def api_404():
# so we don't fall through to the index page
return {'message': 'Not Found'} | null |
154,948 | from datetime import date
from functools import cache
from pathlib import Path
import pydantic
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.components.display import DisplayLookup, DisplayMode
from fastui.events import BackEvent, GoToEvent
from pydantic import BaseModel, Field, TypeAdapter
from .shared import demo_page
class City(BaseModel):
id: int = Field(title='ID')
city: str = Field(title='Name')
city_ascii: str = Field(title='City Ascii')
lat: float = Field(title='Latitude')
lng: float = Field(title='Longitude')
country: str = Field(title='Country')
iso2: str = Field(title='ISO2')
iso3: str = Field(title='ISO3')
admin_name: str | None = Field(title='Admin Name')
capital: str | None = Field(title='Capital')
population: float = Field(title='Population')
def cities_list() -> list[City]:
cities_adapter = TypeAdapter(list[City])
cities_file = Path(__file__).parent / 'cities.json'
cities = cities_adapter.validate_json(cities_file.read_bytes())
cities.sort(key=lambda city: city.population, reverse=True)
return cities
class FilterForm(pydantic.BaseModel):
country: str = Field(json_schema_extra={'search_url': '/api/forms/search', 'placeholder': 'Filter by Country...'})
def tabs() -> list[AnyComponent]:
return [
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Cities')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table/cities',
),
c.Link(
components=[c.Text(text='Users')],
on_click=GoToEvent(url='/table/users'),
active='startswith:/table/users',
),
],
mode='tabs',
class_name='+ mb-4',
),
]
class DisplayLookup(DisplayBase, extra='forbid'):
"""
Description of how to display a value looked up from data, either in a table or detail view.
"""
field: str
# percentage width - 0 to 100, specific to tables
table_width_percent: _t.Union[_te.Annotated[int, _at.Interval(ge=0, le=100)], None] = pydantic.Field(
default=None, serialization_alias='tableWidthPercent'
)
class GoToEvent(BaseModel):
# can be a path or a full URL
url: Union[str, None] = None
query: Union[Dict[str, Union[str, float, None]], None] = None
target: Union[Literal['_blank'], None] = None
type: Literal['go-to'] = 'go-to'
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def cities_view(page: int = 1, country: str | None = None) -> list[AnyComponent]:
cities = cities_list()
page_size = 50
filter_form_initial = {}
if country:
cities = [city for city in cities if city.iso3 == country]
country_name = cities[0].country if cities else country
filter_form_initial['country'] = {'value': country, 'label': country_name}
return demo_page(
*tabs(),
c.ModelForm(
model=FilterForm,
submit_url='.',
initial=filter_form_initial,
method='GOTO',
submit_on_change=True,
display_mode='inline',
),
c.Table(
data=cities[(page - 1) * page_size : page * page_size],
data_model=City,
columns=[
DisplayLookup(field='city', on_click=GoToEvent(url='./{id}'), table_width_percent=33),
DisplayLookup(field='country', table_width_percent=33),
DisplayLookup(field='population', table_width_percent=33),
],
),
c.Pagination(page=page, page_size=page_size, total=len(cities)),
title='Cities',
) | null |
154,949 | from datetime import date
from functools import cache
from pathlib import Path
import pydantic
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.components.display import DisplayLookup, DisplayMode
from fastui.events import BackEvent, GoToEvent
from pydantic import BaseModel, Field, TypeAdapter
from .shared import demo_page
def cities_lookup() -> dict[id, City]:
return {city.id: city for city in cities_list()}
def tabs() -> list[AnyComponent]:
return [
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Cities')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table/cities',
),
c.Link(
components=[c.Text(text='Users')],
on_click=GoToEvent(url='/table/users'),
active='startswith:/table/users',
),
],
mode='tabs',
class_name='+ mb-4',
),
]
class BackEvent(BaseModel):
type: Literal['back'] = 'back'
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def city_view(city_id: int) -> list[AnyComponent]:
city = cities_lookup()[city_id]
return demo_page(
*tabs(),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(data=city),
title=city.city,
) | null |
154,950 | from datetime import date
from functools import cache
from pathlib import Path
import pydantic
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.components.display import DisplayLookup, DisplayMode
from fastui.events import BackEvent, GoToEvent
from pydantic import BaseModel, Field, TypeAdapter
from .shared import demo_page
users: list[User] = [
User(id=1, name='John', dob=date(1990, 1, 1), enabled=True),
User(id=2, name='Jane', dob=date(1991, 1, 1), enabled=False),
User(id=3, name='Jack', dob=date(1992, 1, 1)),
]
def tabs() -> list[AnyComponent]:
return [
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Cities')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table/cities',
),
c.Link(
components=[c.Text(text='Users')],
on_click=GoToEvent(url='/table/users'),
active='startswith:/table/users',
),
],
mode='tabs',
class_name='+ mb-4',
),
]
class DisplayMode(str, enum.Enum):
auto = 'auto' # default, same as None below
plain = 'plain'
datetime = 'datetime'
date = 'date'
duration = 'duration'
as_title = 'as_title'
markdown = 'markdown'
json = 'json'
inline_code = 'inline_code'
class DisplayLookup(DisplayBase, extra='forbid'):
"""
Description of how to display a value looked up from data, either in a table or detail view.
"""
field: str
# percentage width - 0 to 100, specific to tables
table_width_percent: _t.Union[_te.Annotated[int, _at.Interval(ge=0, le=100)], None] = pydantic.Field(
default=None, serialization_alias='tableWidthPercent'
)
class GoToEvent(BaseModel):
# can be a path or a full URL
url: Union[str, None] = None
query: Union[Dict[str, Union[str, float, None]], None] = None
target: Union[Literal['_blank'], None] = None
type: Literal['go-to'] = 'go-to'
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def users_view() -> list[AnyComponent]:
return demo_page(
*tabs(),
c.Table(
data=users,
columns=[
DisplayLookup(field='name', on_click=GoToEvent(url='/table/users/{id}/')),
DisplayLookup(field='dob', mode=DisplayMode.date),
DisplayLookup(field='enabled'),
],
),
title='Users',
) | null |
154,951 | from datetime import date
from functools import cache
from pathlib import Path
import pydantic
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.components.display import DisplayLookup, DisplayMode
from fastui.events import BackEvent, GoToEvent
from pydantic import BaseModel, Field, TypeAdapter
from .shared import demo_page
class User(BaseModel):
id: int = Field(title='ID')
name: str = Field(title='Name')
dob: date = Field(title='Date of Birth')
enabled: bool | None = None
users: list[User] = [
User(id=1, name='John', dob=date(1990, 1, 1), enabled=True),
User(id=2, name='Jane', dob=date(1991, 1, 1), enabled=False),
User(id=3, name='Jack', dob=date(1992, 1, 1)),
]
def tabs() -> list[AnyComponent]:
return [
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Cities')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table/cities',
),
c.Link(
components=[c.Text(text='Users')],
on_click=GoToEvent(url='/table/users'),
active='startswith:/table/users',
),
],
mode='tabs',
class_name='+ mb-4',
),
]
class DisplayMode(str, enum.Enum):
auto = 'auto' # default, same as None below
plain = 'plain'
datetime = 'datetime'
date = 'date'
duration = 'duration'
as_title = 'as_title'
markdown = 'markdown'
json = 'json'
inline_code = 'inline_code'
class DisplayLookup(DisplayBase, extra='forbid'):
"""
Description of how to display a value looked up from data, either in a table or detail view.
"""
field: str
# percentage width - 0 to 100, specific to tables
table_width_percent: _t.Union[_te.Annotated[int, _at.Interval(ge=0, le=100)], None] = pydantic.Field(
default=None, serialization_alias='tableWidthPercent'
)
class BackEvent(BaseModel):
type: Literal['back'] = 'back'
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def user_profile(id: int) -> list[AnyComponent]:
user: User | None = users[id - 1] if id <= len(users) else None
return demo_page(
*tabs(),
c.Link(components=[c.Text(text='Back')], on_click=BackEvent()),
c.Details(
data=user,
fields=[
DisplayLookup(field='name'),
DisplayLookup(field='dob', mode=DisplayMode.date),
DisplayLookup(field='enabled'),
],
),
title=user.name,
) | null |
154,952 | from __future__ import annotations as _annotations
import asyncio
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from .shared import demo_page
def panel(*components: AnyComponent) -> AnyComponent:
return c.Div(class_name='col border rounded m-1 p-2 pb-3', components=list(components)) | null |
154,953 | from __future__ import annotations as _annotations
import asyncio
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from .shared import demo_page
class PageEvent(BaseModel):
name: str
push_path: Union[str, None] = Field(default=None, serialization_alias='pushPath')
context: Union[ContextType, None] = None
clear: Union[bool, None] = None
next_event: 'Union[AnyEvent, None]' = Field(default=None, serialization_alias='nextEvent')
type: Literal['page'] = 'page'
class GoToEvent(BaseModel):
# can be a path or a full URL
url: Union[str, None] = None
query: Union[Dict[str, Union[str, float, None]], None] = None
target: Union[Literal['_blank'], None] = None
type: Literal['go-to'] = 'go-to'
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def components_view() -> list[AnyComponent]:
return demo_page(
c.Div(
components=[
c.Heading(text='Text', level=2),
c.Text(text='This is a text component.'),
]
),
c.Div(
components=[
c.Heading(text='Paragraph', level=2),
c.Paragraph(text='This is a paragraph component.'),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Heading', level=2),
c.Heading(text='This is an H3', level=3),
c.Heading(text='This is an H4', level=4),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Code', level=2),
c.Code(
language='python',
text="""\
from pydantic import BaseModel
class Delivery(BaseModel):
dimensions: tuple[int, int]
m = Delivery(dimensions=['10', '20'])
print(m.dimensions)
#> (10, 20)
""",
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Link List', level=2),
c.Markdown(
text=(
'This is a simple unstyled list of links, '
'LinkList is also used in `Navbar` and `Pagination`.'
)
),
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Internal Link - the the home page')],
on_click=GoToEvent(url='/'),
),
c.Link(
components=[c.Text(text='Pydantic (External link)')],
on_click=GoToEvent(url='https://pydantic.dev'),
),
c.Link(
components=[c.Text(text='FastUI repo (New tab)')],
on_click=GoToEvent(url='https://github.com/pydantic/FastUI', target='_blank'),
),
],
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Button and Modal', level=2),
c.Paragraph(text='The button below will open a modal with static content.'),
c.Button(text='Show Static Modal', on_click=PageEvent(name='static-modal')),
c.Button(text='Secondary Button', named_style='secondary', class_name='+ ms-2'),
c.Button(text='Warning Button', named_style='warning', class_name='+ ms-2'),
c.Modal(
title='Static Modal',
body=[c.Paragraph(text='This is some static content that was set when the modal was defined.')],
footer=[
c.Button(text='Close', on_click=PageEvent(name='static-modal', clear=True)),
],
open_trigger=PageEvent(name='static-modal'),
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Dynamic Modal', level=2),
c.Markdown(
text=(
'The button below will open a modal with content loaded from the server when '
"it's opened using `ServerLoad`."
)
),
c.Button(text='Show Dynamic Modal', on_click=PageEvent(name='dynamic-modal')),
c.Modal(
title='Dynamic Modal',
body=[c.ServerLoad(path='/components/dynamic-content')],
footer=[
c.Button(text='Close', on_click=PageEvent(name='dynamic-modal', clear=True)),
],
open_trigger=PageEvent(name='dynamic-modal'),
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Modal Form / Confirm prompt', level=2),
c.Markdown(text='The button below will open a modal with a form.'),
c.Button(text='Show Modal Form', on_click=PageEvent(name='modal-form')),
c.Modal(
title='Modal Form',
body=[
c.Paragraph(text='Form inside a modal!'),
c.Form(
form_fields=[
c.FormFieldInput(name='foobar', title='Foobar', required=True),
],
submit_url='/api/components/modal-form',
footer=[],
submit_trigger=PageEvent(name='modal-form-submit'),
),
],
footer=[
c.Button(
text='Cancel', named_style='secondary', on_click=PageEvent(name='modal-form', clear=True)
),
c.Button(text='Submit', on_click=PageEvent(name='modal-form-submit')),
],
open_trigger=PageEvent(name='modal-form'),
),
c.Button(text='Show Modal Prompt', on_click=PageEvent(name='modal-prompt'), class_name='+ ms-2'),
c.Modal(
title='Form Prompt',
body=[
c.Paragraph(text='Are you sure you want to do whatever?'),
c.Form(
form_fields=[],
submit_url='/api/components/modal-prompt',
loading=[c.Spinner(text='Okay, good luck...')],
footer=[],
submit_trigger=PageEvent(name='modal-form-submit'),
),
],
footer=[
c.Button(
text='Cancel', named_style='secondary', on_click=PageEvent(name='modal-prompt', clear=True)
),
c.Button(text='Submit', on_click=PageEvent(name='modal-form-submit')),
],
open_trigger=PageEvent(name='modal-prompt'),
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Server Load', level=2),
c.Paragraph(text='Even simpler example of server load, replacing existing content.'),
c.Button(text='Load Content from Server', on_click=PageEvent(name='server-load')),
c.Div(
components=[
c.ServerLoad(
path='/components/dynamic-content',
load_trigger=PageEvent(name='server-load'),
components=[c.Text(text='before')],
),
],
class_name='py-2',
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Server Load SSE', level=2),
c.Markdown(
text=(
'`ServerLoad` can also be used to load content from an SSE stream.\n\n'
"Here the response is the streamed output from OpenAI's GPT-4 chat model."
)
),
c.Button(text='Load SSE content', on_click=PageEvent(name='server-load-sse')),
c.Div(
components=[
c.ServerLoad(
path='/components/sse',
sse=True,
load_trigger=PageEvent(name='server-load-sse'),
components=[c.Text(text='before')],
),
],
class_name='my-2 p-2 border rounded',
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Iframe', level=2),
c.Markdown(text='`Iframe` can be used to embed external content.'),
c.Iframe(src='https://pydantic.dev', width='100%', height=400),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Image', level=2),
c.Paragraph(text='An image component.'),
c.Image(
src='https://avatars.githubusercontent.com/u/110818415',
alt='Pydantic Logo',
width=200,
height=200,
loading='lazy',
referrer_policy='no-referrer',
class_name='border rounded',
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Spinner', level=2),
c.Paragraph(
text=(
'A component displayed while waiting for content to load, '
'this is also used automatically while loading server content.'
)
),
c.Spinner(text='Content incoming...'),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Video', level=2),
c.Paragraph(text='A video component.'),
c.Video(
sources=['https://www.w3schools.com/html/mov_bbb.mp4'],
autoplay=False,
controls=True,
loop=False,
),
],
class_name='border-top mt-3 pt-1',
),
c.Div(
components=[
c.Heading(text='Custom', level=2),
c.Markdown(
text="""\
Below is a custom component, in this case it implements [cowsay](https://en.wikipedia.org/wiki/Cowsay),
but you might be able to do something even more useful with it.
The statement spoken by the famous cow is provided by the backend."""
),
c.Custom(data='This is a custom component', sub_type='cowsay'),
],
class_name='border-top mt-3 pt-1',
),
title='Components',
) | null |
154,954 | from __future__ import annotations as _annotations
import asyncio
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from .shared import demo_page
async def modal_view() -> list[AnyComponent]:
await asyncio.sleep(0.5)
return [c.Paragraph(text='This is some dynamic content. Open devtools to see me being fetched from the server.')] | null |
154,955 | from __future__ import annotations as _annotations
import asyncio
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from .shared import demo_page
class PageEvent(BaseModel):
name: str
push_path: Union[str, None] = Field(default=None, serialization_alias='pushPath')
context: Union[ContextType, None] = None
clear: Union[bool, None] = None
next_event: 'Union[AnyEvent, None]' = Field(default=None, serialization_alias='nextEvent')
type: Literal['page'] = 'page'
async def modal_form_submit() -> list[AnyComponent]:
await asyncio.sleep(0.5)
return [c.FireEvent(event=PageEvent(name='modal-form', clear=True))] | null |
154,956 | from __future__ import annotations as _annotations
import asyncio
from fastapi import APIRouter
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from .shared import demo_page
class PageEvent(BaseModel):
name: str
push_path: Union[str, None] = Field(default=None, serialization_alias='pushPath')
context: Union[ContextType, None] = None
clear: Union[bool, None] = None
next_event: 'Union[AnyEvent, None]' = Field(default=None, serialization_alias='nextEvent')
type: Literal['page'] = 'page'
async def modal_prompt_submit() -> list[AnyComponent]:
await asyncio.sleep(0.5)
return [c.FireEvent(event=PageEvent(name='modal-prompt', clear=True))] | null |
154,957 | import asyncio
from itertools import chain
from typing import AsyncIterable
from fastapi import APIRouter
from fastui import FastUI
from fastui import components as c
from starlette.responses import StreamingResponse
async def canned_ai_response_generator() -> AsyncIterable[str]:
prompt = '**User:** What is SSE? Please include a javascript code example.\n\n**AI:** '
output = ''
for time, text in chain([(0.5, prompt)], CANNED_RESPONSE):
await asyncio.sleep(time)
output += text
m = FastUI(root=[c.Markdown(text=output)])
yield f'data: {m.model_dump_json(by_alias=True, exclude_none=True)}\n\n'
async def sse_ai_response() -> StreamingResponse:
return StreamingResponse(canned_ai_response_generator(), media_type='text/event-stream') | null |
154,958 | import asyncio
from itertools import chain
from typing import AsyncIterable
from fastapi import APIRouter
from fastui import FastUI
from fastui import components as c
from starlette.responses import StreamingResponse
async def run_openai():
from time import perf_counter
from openai import AsyncOpenAI
messages = [
{'role': 'system', 'content': 'please response in markdown only.'},
{'role': 'user', 'content': 'What is SSE? Please include a javascript code example.'},
]
chunks = await AsyncOpenAI().chat.completions.create(
model='gpt-4',
messages=messages,
stream=True,
)
last = None
result_chunks = []
async for chunk in chunks:
now = perf_counter()
if last is not None:
t = now - last
else:
t = 0
text = chunk.choices[0].delta.content
print(repr(text), t)
if text is not None:
result_chunks.append((t, text))
last = now
print(result_chunks)
text = ''.join(text for _, text in result_chunks)
print(text) | null |
154,959 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
LoginKind: TypeAlias = Literal['password', 'github']
def auth_login_content(kind: LoginKind) -> list[AnyComponent]:
match kind:
case 'password':
return [
c.Heading(text='Password Login', level=3),
c.Paragraph(
text=(
'This is a very simple demo of password authentication, '
'here you can "login" with any email address and password.'
)
),
c.Paragraph(text='(Passwords are not saved and is email stored in the browser via a JWT only)'),
c.ModelForm(model=LoginForm, submit_url='/api/auth/login', display_mode='page'),
]
case 'github':
return [
c.Heading(text='GitHub Login', level=3),
c.Paragraph(text='Demo of GitHub authentication.'),
c.Paragraph(text='(Credentials are stored in the browser via a JWT only)'),
c.Button(text='Login with GitHub', on_click=GoToEvent(url='/auth/login/github/gen')),
]
case _:
raise ValueError(f'Invalid kind {kind!r}')
class PageEvent(BaseModel):
name: str
push_path: Union[str, None] = Field(default=None, serialization_alias='pushPath')
context: Union[ContextType, None] = None
clear: Union[bool, None] = None
next_event: 'Union[AnyEvent, None]' = Field(default=None, serialization_alias='nextEvent')
type: Literal['page'] = 'page'
class User:
email: str | None
extra: dict[str, Any]
def encode_token(self) -> str:
payload = asdict(self)
payload['exp'] = datetime.now() + timedelta(hours=1)
return jwt.encode(payload, JWT_SECRET, algorithm='HS256', json_encoder=CustomJsonEncoder)
def from_request(cls, authorization: Annotated[str, Header()] = '') -> Self:
user = cls.from_request_opt(authorization)
if user is None:
raise AuthRedirect('/auth/login/password')
else:
return user
def from_request_opt(cls, authorization: Annotated[str, Header()] = '') -> Self | None:
try:
token = authorization.split(' ', 1)[1]
except IndexError:
return None
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return None
except jwt.DecodeError:
raise HTTPException(status_code=401, detail='Invalid token')
else:
# existing token might not have 'exp' field
payload.pop('exp', None)
return cls(**payload)
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
return [
c.PageTitle(text=f'FastUI Demo — {title}' if title else 'FastUI Demo'),
c.Navbar(
title='FastUI Demo',
title_event=GoToEvent(url='/'),
start_links=[
c.Link(
components=[c.Text(text='Components')],
on_click=GoToEvent(url='/components'),
active='startswith:/components',
),
c.Link(
components=[c.Text(text='Tables')],
on_click=GoToEvent(url='/table/cities'),
active='startswith:/table',
),
c.Link(
components=[c.Text(text='Auth')],
on_click=GoToEvent(url='/auth/login/password'),
active='startswith:/auth',
),
c.Link(
components=[c.Text(text='Forms')],
on_click=GoToEvent(url='/forms/login'),
active='startswith:/forms',
),
],
),
c.Page(
components=[
*((c.Heading(text=title),) if title else ()),
*components,
],
),
c.Footer(
extra_text='FastUI Demo',
links=[
c.Link(
components=[c.Text(text='Github')], on_click=GoToEvent(url='https://github.com/pydantic/FastUI')
),
c.Link(components=[c.Text(text='PyPI')], on_click=GoToEvent(url='https://pypi.org/project/fastui/')),
c.Link(components=[c.Text(text='NPM')], on_click=GoToEvent(url='https://www.npmjs.com/org/pydantic/')),
],
),
]
def auth_login(
kind: LoginKind,
user: Annotated[User | None, Depends(User.from_request_opt)],
) -> list[AnyComponent]:
if user is not None:
# already logged in
raise AuthRedirect('/auth/profile')
return demo_page(
c.LinkList(
links=[
c.Link(
components=[c.Text(text='Password Login')],
on_click=PageEvent(name='tab', push_path='/auth/login/password', context={'kind': 'password'}),
active='/auth/login/password',
),
c.Link(
components=[c.Text(text='GitHub Login')],
on_click=PageEvent(name='tab', push_path='/auth/login/github', context={'kind': 'github'}),
active='/auth/login/github',
),
],
mode='tabs',
class_name='+ mb-4',
),
c.ServerLoad(
path='/auth/login/content/{kind}',
load_trigger=PageEvent(name='tab'),
components=auth_login_content(kind),
),
title='Authentication',
) | null |
154,960 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
class LoginForm(BaseModel):
email: EmailStr = Field(
title='Email Address', description='Enter whatever value you like', json_schema_extra={'autocomplete': 'email'}
)
password: SecretStr = Field(
title='Password',
description='Enter whatever value you like, password is not checked',
json_schema_extra={'autocomplete': 'current-password'},
)
class AuthEvent(BaseModel):
# False means clear the token and thereby logout the user
token: Union[str, Literal[False]]
url: Union[str, None] = None
type: Literal['auth'] = 'auth'
def fastui_form(model: _t.Type[FormModel]) -> fastapi_params.Depends:
async def run_fastui_form(request: fastapi.Request):
async with request.form() as form_data:
model_data = unflatten(form_data)
try:
return model.model_validate(model_data)
except pydantic.ValidationError as e:
raise fastapi.HTTPException(
status_code=422,
detail={'form': e.errors(include_input=False, include_url=False, include_context=False)},
)
return fastapi.Depends(run_fastui_form)
class User:
email: str | None
extra: dict[str, Any]
def encode_token(self) -> str:
payload = asdict(self)
payload['exp'] = datetime.now() + timedelta(hours=1)
return jwt.encode(payload, JWT_SECRET, algorithm='HS256', json_encoder=CustomJsonEncoder)
def from_request(cls, authorization: Annotated[str, Header()] = '') -> Self:
user = cls.from_request_opt(authorization)
if user is None:
raise AuthRedirect('/auth/login/password')
else:
return user
def from_request_opt(cls, authorization: Annotated[str, Header()] = '') -> Self | None:
try:
token = authorization.split(' ', 1)[1]
except IndexError:
return None
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return None
except jwt.DecodeError:
raise HTTPException(status_code=401, detail='Invalid token')
else:
# existing token might not have 'exp' field
payload.pop('exp', None)
return cls(**payload)
async def login_form_post(form: Annotated[LoginForm, fastui_form(LoginForm)]) -> list[AnyComponent]:
user = User(email=form.email, extra={})
token = user.encode_token()
return [c.FireEvent(event=AuthEvent(token=token, url='/auth/profile'))] | null |
154,961 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
class PageEvent(BaseModel):
class User:
def encode_token(self) -> str:
def from_request(cls, authorization: Annotated[str, Header()] = '') -> Self:
def from_request_opt(cls, authorization: Annotated[str, Header()] = '') -> Self | None:
def demo_page(*components: AnyComponent, title: str | None = None) -> list[AnyComponent]:
async def profile(user: Annotated[User, Depends(User.from_request)]) -> list[AnyComponent]:
return demo_page(
c.Paragraph(text=f'You are logged in as "{user.email}".'),
c.Button(text='Logout', on_click=PageEvent(name='submit-form')),
c.Heading(text='User Data:', level=3),
c.Code(language='json', text=json.dumps(asdict(user), indent=2)),
c.Form(
submit_url='/api/auth/logout',
form_fields=[c.FormFieldInput(name='test', title='', initial='data', html_type='hidden')],
footer=[],
submit_trigger=PageEvent(name='submit-form'),
),
title='Authentication',
) | null |
154,962 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
class AuthEvent(BaseModel):
# False means clear the token and thereby logout the user
token: Union[str, Literal[False]]
url: Union[str, None] = None
type: Literal['auth'] = 'auth'
async def logout_form_post() -> list[AnyComponent]:
return [c.FireEvent(event=AuthEvent(token=False, url='/auth/login/password'))] | null |
154,963 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
async def get_github_auth(request: Request) -> GitHubAuthProvider:
client: AsyncClient = request.app.state.httpx_client
return GitHubAuthProvider(
httpx_client=client,
github_client_id=GITHUB_CLIENT_ID,
github_client_secret=GITHUB_CLIENT_SECRET,
redirect_uri=GITHUB_REDIRECT,
scopes=['user:email'],
)
class GoToEvent(BaseModel):
# can be a path or a full URL
url: Union[str, None] = None
query: Union[Dict[str, Union[str, float, None]], None] = None
target: Union[Literal['_blank'], None] = None
type: Literal['go-to'] = 'go-to'
async def auth_github_gen(github_auth: Annotated[GitHubAuthProvider, Depends(get_github_auth)]) -> list[AnyComponent]:
auth_url = await github_auth.authorization_url()
return [c.FireEvent(event=GoToEvent(url=auth_url))] | null |
154,964 | from __future__ import annotations as _annotations
import asyncio
import json
import os
from dataclasses import asdict
from typing import Annotated, Literal, TypeAlias
from fastapi import APIRouter, Depends, Request
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.auth import AuthRedirect, GitHubAuthProvider
from fastui.events import AuthEvent, GoToEvent, PageEvent
from fastui.forms import fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr
from .auth_user import User
from .shared import demo_page
async def get_github_auth(request: Request) -> GitHubAuthProvider:
client: AsyncClient = request.app.state.httpx_client
return GitHubAuthProvider(
httpx_client=client,
github_client_id=GITHUB_CLIENT_ID,
github_client_secret=GITHUB_CLIENT_SECRET,
redirect_uri=GITHUB_REDIRECT,
scopes=['user:email'],
)
class AuthEvent(BaseModel):
# False means clear the token and thereby logout the user
token: Union[str, Literal[False]]
url: Union[str, None] = None
type: Literal['auth'] = 'auth'
class User:
email: str | None
extra: dict[str, Any]
def encode_token(self) -> str:
payload = asdict(self)
payload['exp'] = datetime.now() + timedelta(hours=1)
return jwt.encode(payload, JWT_SECRET, algorithm='HS256', json_encoder=CustomJsonEncoder)
def from_request(cls, authorization: Annotated[str, Header()] = '') -> Self:
user = cls.from_request_opt(authorization)
if user is None:
raise AuthRedirect('/auth/login/password')
else:
return user
def from_request_opt(cls, authorization: Annotated[str, Header()] = '') -> Self | None:
try:
token = authorization.split(' ', 1)[1]
except IndexError:
return None
try:
payload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return None
except jwt.DecodeError:
raise HTTPException(status_code=401, detail='Invalid token')
else:
# existing token might not have 'exp' field
payload.pop('exp', None)
return cls(**payload)
async def github_redirect(
code: str,
state: str | None,
github_auth: Annotated[GitHubAuthProvider, Depends(get_github_auth)],
) -> list[AnyComponent]:
exchange = await github_auth.exchange_code(code, state)
user_info, emails = await asyncio.gather(
github_auth.get_github_user(exchange), github_auth.get_github_user_emails(exchange)
)
user = User(
email=next((e.email for e in emails if e.primary and e.verified), None),
extra={
'github_user_info': user_info.model_dump(),
'github_emails': [e.model_dump() for e in emails],
},
)
token = user.encode_token()
return [c.FireEvent(event=AuthEvent(token=token, url='/auth/profile'))] | null |
154,965 | import numpy as np
import matplotlib.pyplot as plt
plt.plot([2002.5, 2021.5], [0, 0], color="black", linewidth=1.0, clip_on=False)
plt.scatter(
X,
Y,
s=50,
linewidth=1.0,
zorder=10,
clip_on=False,
edgecolor="black",
facecolor="white",
)
plt.tight_layout()
plt.savefig("../../figures/introduction/matplotlib-timeline.pdf")
plt.savefig("../../figures/introduction/matplotlib-timeline.png", dpi=300)
plt.show()
def annotate(ax, x, y, text, fc="#ff7777", y0=0):
y = y - 0.5
ax.annotate(
" " + text + " ",
xy=(x, y),
xycoords="data",
xytext=(0, 12),
textcoords="offset points",
color="white",
size="x-small",
va="center",
ha="center",
weight="bold",
bbox=dict(boxstyle="round", fc=fc, ec="none"),
arrowprops=dict(
arrowstyle="wedge,tail_width=1.", fc=fc, ec="none", patchA=None
),
)
plt.plot([x, x], [y, y0], color="black", linestyle=":", linewidth=0.75) | null |
154,966 | import numpy as np
import matplotlib.pyplot as plt
def style(index, e=0.001):
patterns = [
("densely dotted", (-0.5, (e, 2 - e))),
("dotted", (-0.5, (e, 3 - e))),
("loosely dotted", (-0.5, (e, 5 - e))),
("densely dashed", (-0.5, (2, 3))),
("dashed", (-0.5, (2, 4))),
("loosely dashed", (-0.5, (2, 7))),
("densely dashdotted", (-0.5, (2, 2, e, 2 - e))),
("dashdotted", (-0.5, (2, 3, e, 2 - e))),
("loosely dashdotted", (-0.5, (2, 5, e, 5 - e))),
("densely dashdotdotted", (-0.5, (2, 2, e, 2 - e, e, 2 - e))),
("dashdotdotted", (-0.5, (2, 3, e, 3 - e, e, 3 - e))),
("loosely dashdotdotted", (-0.5, (2, 5, e, 5 - e, e, 5 - e))),
]
return patterns[index] | null |
154,967 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.ticker import MultipleLocator
from matplotlib.patches import Circle, Rectangle
from matplotlib.collections import LineCollection
def line_intersect(p1, p2, P3, P4):
p1 = np.atleast_2d(p1)
p2 = np.atleast_2d(p2)
P3 = np.atleast_2d(P3)
P4 = np.atleast_2d(P4)
x1, y1 = p1[:, 0], p1[:, 1]
x2, y2 = p2[:, 0], p2[:, 1]
X3, Y3 = P3[:, 0], P3[:, 1]
X4, Y4 = P4[:, 0], P4[:, 1]
D = (Y4 - Y3) * (x2 - x1) - (X4 - X3) * (y2 - y1)
# Colinearity test
C = D != 0
UA = (X4 - X3) * (y1 - Y3) - (Y4 - Y3) * (x1 - X3)
UA = np.divide(UA, D, where=C)
UB = (x2 - x1) * (y1 - Y3) - (y2 - y1) * (x1 - X3)
UB = np.divide(UB, D, where=C)
# Test if intersections are inside each segment
C = C * (UA > 0) * (UA < 1) * (UB > 0) * (UB < 1)
X = np.where(C, x1 + UA * (x2 - x1), np.inf)
Y = np.where(C, y1 + UA * (y2 - y1), np.inf)
return np.stack([X, Y], axis=1) | null |
154,968 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.ticker import MultipleLocator
from matplotlib.patches import Circle, Rectangle
from matplotlib.collections import LineCollection
def update(frame):
# Update bot position according to sensors
dv = (bot.sensors["value"].ravel() * [-4.0, -3, -2, -1, 1, 2, 3, 4]).sum()
if abs(dv) > 0.5:
bot.orientation += 0.01 * dv
bot.position += 2 * np.array([np.cos(bot.orientation), np.sin(bot.orientation)])
bot.update(maze)
# Alternate wall moving to bias bot behavior
if bot.position[1] < 100:
maze.walls[12:] = [[(0, 250), (100, 300)], [(200, 200), (300, 250)]]
elif bot.position[1] > 400:
maze.walls[12:] = [[(0, 250), (100, 200)], [(200, 300), (300, 250)]]
# Sensor plots
n = len(bot.sensors["angle"])
if frame < 500:
P[frame] = bot.position
trace.set_xdata(P[:frame, 0])
trace.set_ydata(P[:frame, 1])
for i in range(n):
Y[i, frame] = bot.sensors["value"][i]
plots[i].set_ydata(Y[i, :frame])
plots[i].set_xdata(X[:frame])
else:
P[:-1] = P[1:]
P[-1] = bot.position
trace.set_xdata(P[:, 0])
trace.set_ydata(P[:, 1])
Y[:, 0:-1] = Y[:, 1:]
for i in range(n):
Y[i, -1] = bot.sensors["value"][i]
plots[i].set_ydata(Y[i])
plots[i].set_xdata(X)
return bot.artists, trace, plots | null |
154,969 | import bluenoise
import numpy as np
import scipy.spatial
import shapely.geometry
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
P = bluenoise.generate((10, 10), radius=0.5)
def hatch(n=4, theta=None):
theta = theta or np.random.uniform(0, np.pi)
P = np.zeros((n, 2, 2))
X = np.linspace(-0.5, +0.5, n, endpoint=True)
P[:, 0, 1] = -0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 1] = +0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 0] = X + np.random.normal(0, 0.025, n)
P[:, 0, 0] = X + np.random.normal(0, 0.025, n)
c, s = np.cos(theta), np.sin(theta)
Z = np.array([[c, s], [-s, c]])
return P @ Z.T | null |
154,970 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.patches import Circle
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvas
P = np.random.uniform(0, 5, (500, 2))
C = np.random.uniform(5, 25, 500)
def plot(ax):
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.yaxis.set_minor_formatter(ticker.FormatStrFormatter("%.2f"))
for i, label in enumerate(ax.get_yticklabels(which="minor")):
label.set_size(7)
ax.xaxis.set_minor_formatter(ticker.FormatStrFormatter("%.2f"))
for i, label in enumerate(ax.get_xticklabels(which="minor")):
label.set_size(7)
ax.grid(True, "minor", color="0.85", linewidth=0.50, zorder=-20)
ax.grid(True, "major", color="0.65", linewidth=0.75, zorder=-10)
ax.scatter(P[:, 0], P[:, 1], C, color="black", zorder=10) | null |
154,971 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.patches import Circle
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvas
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(xlim=(0.0, 5), ylim=(0.0, 5), aspect=1)
canvas = FigureCanvas(ifig)
canvas.draw()
background = fig.canvas.copy_from_bbox(ax.bbox)
circle_bg = Circle(
(1, 1),
1,
transform=ax.transData,
zorder=20,
clip_on=False,
edgecolor="none",
facecolor="white",
)
ax.add_artist(circle_bg)
circle_fg = Circle(
(1, 1),
1,
transform=ax.transData,
zorder=30,
clip_on=False,
linewidth=2,
edgecolor="black",
facecolor="None",
)
ax.add_artist(circle_fg)
image = ax.imshow(Z, extent=[0, 5, 0, 5], zorder=25, clip_on=True)
image.set_extent([0, 10, 0, 10])
image.set_clip_path(circle_bg)
def on_motion(event):
x, y = event.xdata, event.ydata
if x is None or y is None:
return
fig.canvas.restore_region(background)
circle_bg.set_center((x, y))
ax.draw_artist(circle_bg)
circle_fg.set_center((x, y))
ax.draw_artist(circle_fg)
image.set_extent([0 - x, 10 - x, 0 - y, 10 - y])
image.set_clip_path(circle_bg)
ax.draw_artist(image)
fig.canvas.blit(ax.bbox) | null |
154,972 | import numpy as np
import scipy.spatial
import shapely.geometry
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Polygon, Ellipse
import bluenoise
np.random.seed(1)
P = bluenoise.generate((15, 15), radius=radius) - (0.5, 0.5)
def hatch(n=4, theta=None):
theta = theta or np.random.uniform(0, np.pi)
P = np.zeros((n, 2, 2))
X = np.linspace(-0.5, +0.5, n, endpoint=True)
P[:, 0, 1] = -0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 1] = +0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 0] = X + np.random.normal(0, 0.025, n)
P[:, 0, 0] = X + np.random.normal(0, 0.025, n)
c, s = np.cos(theta), np.sin(theta)
Z = np.array([[c, s], [-s, c]])
return P @ Z.T | null |
154,973 | import numpy as np
import scipy.spatial
import shapely.geometry
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Polygon, Ellipse
import bluenoise
np.random.seed(1)
h = 4
The provided code snippet includes necessary dependencies for implementing the `seg_dists` function. Write a Python function `def seg_dists(p, a, b)` to solve the following problem:
Cartesian distance from point to line segment Args: - p: np.array of single point, shape (2,) or 2D array, shape (x, 2) - a: np.array of shape (x, 2) - b: np.array of shape (x, 2)
Here is the function:
def seg_dists(p, a, b):
"""Cartesian distance from point to line segment
Args:
- p: np.array of single point, shape (2,) or 2D array, shape (x, 2)
- a: np.array of shape (x, 2)
- b: np.array of shape (x, 2)
"""
# normalized tangent vectors
d_ba = b - a
d = np.divide(d_ba, (np.hypot(d_ba[:, 0], d_ba[:, 1]).reshape(-1, 1)))
# signed parallel distance components
# rowwise dot products of 2D vectors
s = np.multiply(a - p, d).sum(axis=1)
t = np.multiply(p - b, d).sum(axis=1)
# clamped parallel distance
h = np.maximum.reduce([s, t, np.zeros(len(s))])
# perpendicular distance component
# rowwise cross products of 2D vectors
d_pa = p - a
c = d_pa[:, 0] * d[:, 1] - d_pa[:, 1] * d[:, 0]
return np.hypot(h, c) | Cartesian distance from point to line segment Args: - p: np.array of single point, shape (2,) or 2D array, shape (x, 2) - a: np.array of shape (x, 2) - b: np.array of shape (x, 2) |
154,974 | import numpy as np
from math import cos, sin, floor, sqrt, pi, ceil
The provided code snippet includes necessary dependencies for implementing the `generate` function. Write a Python function `def generate(shape, radius, k=32, seed=None)` to solve the following problem:
Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
Here is the function:
def generate(shape, radius, k=32, seed=None):
"""
Generate blue noise over a two-dimensional rectangle of size (width,height)
Parameters
----------
shape : tuple
Two-dimensional domain (width x height)
radius : float
Minimum distance between samples
k : int, optional
Limit of samples to choose before rejection (typically k = 30)
seed : int, optional
If provided, this will set the random seed before generating noise,
for valid pseudo-random comparisons.
References
----------
.. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson,
Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
"""
def sqdist(a, b):
""" Squared Euclidean distance """
dx, dy = a[0] - b[0], a[1] - b[1]
return dx * dx + dy * dy
def grid_coords(p):
""" Return index of cell grid corresponding to p """
return int(floor(p[0] / cellsize)), int(floor(p[1] / cellsize))
def fits(p, radius):
""" Check whether p can be added to the queue """
radius2 = radius * radius
gx, gy = grid_coords(p)
for x in range(max(gx - 2, 0), min(gx + 3, grid_width)):
for y in range(max(gy - 2, 0), min(gy + 3, grid_height)):
g = grid[x + y * grid_width]
if g is None:
continue
if sqdist(p, g) <= radius2:
return False
return True
# When given a seed, we use a private random generator in order to not
# disturb the default global random generator
if seed is not None:
from numpy.random.mtrand import RandomState
rng = RandomState(seed=seed)
else:
rng = np.random
width, height = shape
cellsize = radius / sqrt(2)
grid_width = int(ceil(width / cellsize))
grid_height = int(ceil(height / cellsize))
grid = [None] * (grid_width * grid_height)
p = rng.uniform(0, shape, 2)
queue = [p]
grid_x, grid_y = grid_coords(p)
grid[grid_x + grid_y * grid_width] = p
while queue:
qi = rng.randint(len(queue))
qx, qy = queue[qi]
queue[qi] = queue[-1]
queue.pop()
for _ in range(k):
theta = rng.uniform(0, 2 * pi)
r = radius * np.sqrt(rng.uniform(1, 4))
p = qx + r * cos(theta), qy + r * sin(theta)
if not (0 <= p[0] < width and 0 <= p[1] < height) or not fits(p, radius):
continue
queue.append(p)
gx, gy = grid_coords(p)
grid[gx + gy * grid_width] = p
return np.array([p for p in grid if p is not None]) | Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807` |
154,975 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
The provided code snippet includes necessary dependencies for implementing the `circle` function. Write a Python function `def circle(center, radius)` to solve the following problem:
Regular circle path
Here is the function:
def circle(center, radius):
""" Regular circle path """
T = np.arange(0, np.pi * 2.0, 0.01)
T = T.reshape(-1, 1)
X = center[0] + radius * np.cos(T)
Y = center[1] + radius * np.sin(T)
vertices = np.hstack((X, Y))
codes = np.ones(len(vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO
return vertices, codes | Regular circle path |
154,976 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
x = subplot(rows, cols, 5, "A ∪ B")
x = subplot(rows, cols, 9, "A ∩ B")
The provided code snippet includes necessary dependencies for implementing the `rectangle` function. Write a Python function `def rectangle(center, size)` to solve the following problem:
Regular rectangle path
Here is the function:
def rectangle(center, size):
""" Regular rectangle path """
(x, y), (w, h) = center, size
vertices = np.array([(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)])
codes = np.array(
[
mpath.Path.MOVETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
]
)
return vertices, codes | Regular rectangle path |
154,977 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
The provided code snippet includes necessary dependencies for implementing the `patch` function. Write a Python function `def patch( ax, path, facecolor="0.9", edgecolor="black", linewidth=1, linestyle="-", clip=None )` to solve the following problem:
Build a patch with potential clipping path
Here is the function:
def patch(
ax, path, facecolor="0.9", edgecolor="black", linewidth=1, linestyle="-", clip=None
):
""" Build a patch with potential clipping path """
patch = mpatches.PathPatch(
path,
linewidth=linewidth,
linestyle=linestyle,
facecolor=facecolor,
edgecolor=edgecolor,
)
if clip:
# If the path is not drawn, clipping doesn't work
clip_patch = mpatches.PathPatch(
clip, linewidth=0, facecolor="None", edgecolor="None"
)
ax.add_patch(clip_patch)
patch.set_clip_path(clip_patch)
ax.add_patch(patch) | Build a patch with potential clipping path |
154,978 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
ax = subplot(rows, cols, 1, "A")
ax = subplot(rows, cols, 2, "B")
ax = subplot(rows, cols, 3, "¬A")
plt.setp(ax.spines.values(), linewidth=1.5)
ax = subplot(rows, cols, 4, "¬B")
plt.setp(ax.spines.values(), linewidth=1.5)
plt.setp(ax.spines.values(), linewidth=1.5)
plt.setp(ax.spines.values(), linewidth=1.5)
plt.setp(ax.spines.values(), linewidth=1.5)
plt.setp(ax.spines.values(), linewidth=1.5)
plt.tight_layout()
plt.savefig("../../figures/beyond/polygon-clipping.pdf")
plt.show()
The provided code snippet includes necessary dependencies for implementing the `subplot` function. Write a Python function `def subplot(cols, rows, index, title)` to solve the following problem:
Shortcut to subplot to factorize options
Here is the function:
def subplot(cols, rows, index, title):
""" Shortcut to subplot to factorize options"""
ax = plt.subplot(cols, rows, index, aspect=1)
ax.text(-1.25, 0.75, "A", size="large", ha="center", va="center")
ax.text(+1.25, 0.75, "B", size="large", ha="center", va="center")
ax.set_title(title, weight="bold")
ax.set_xlim(-1.5, +1.5), ax.set_xticks([])
ax.set_ylim(-1, +1), ax.set_yticks([])
return ax | Shortcut to subplot to factorize options |
154,979 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Rectangle, PathPatch
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, **kwargs):
x, y, z = xyz
if zdir == "y":
x, y, z = x, z, y
elif zdir == "x":
x, y, z = y, z, x
else:
x, y, z = x, y, z
text_path = TextPath((0, 0), s, size=size)
trans = Affine2D().rotate(angle).translate(x, y)
p = PathPatch(trans.transform_path(text_path), **kwargs)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=z, zdir=zdir) | null |
154,980 | import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
np.random.seed(123)
for n in range(3):
ax = plt.subplot(1, 3, n + 1, frameon=False, sharex=ax)
for i in range(50):
Y = curve()
X = np.linspace(-3, 3, len(Y))
ax.plot(X, 3 * Y + i, color="k", linewidth=0.75, zorder=100 - i)
color = cmap(i / 50)
ax.fill_between(X, 3 * Y + i, i, color=color, zorder=100 - i)
# Some random text on the right of the curve
v = np.random.uniform(0, 1)
if v < 0.4:
text = "*"
if v < 0.05:
text = "***"
elif v < 0.2:
text = "**"
ax.text(
3.0,
i,
text,
ha="right",
va="baseline",
size=8,
transform=ax.transData,
zorder=300,
)
ax.yaxis.set_tick_params(tick1On=False)
ax.set_xlim(-3, 3)
ax.set_ylim(-1, 53)
ax.axvline(0.0, ls="--", lw=0.75, color="black", zorder=250)
ax.text(
0.0,
1.0,
"Value %d" % (n + 1),
ha="left",
va="top",
weight="bold",
transform=ax.transAxes,
)
if n == 0:
ax.yaxis.set_tick_params(labelleft=True)
ax.set_yticks(np.arange(50))
ax.set_yticklabels(["Serie %d" % i for i in range(1, 51)])
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(6)
tick.label.set_verticalalignment("bottom")
else:
ax.yaxis.set_tick_params(labelleft=False)
def curve():
n = np.random.randint(1, 5)
centers = np.random.normal(0.0, 1.0, n)
widths = np.random.uniform(5.0, 50.0, n)
widths = 10 * widths / widths.sum()
scales = np.random.uniform(0.1, 1.0, n)
scales /= scales.sum()
X = np.zeros(500)
x = np.linspace(-3, 3, len(X))
for center, width, scale in zip(centers, widths, scales):
X = X + scale * np.exp(-(x - center) * (x - center) * width)
return X | null |
154,981 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
def minor_tick(x, pos):
if not x % 1.0:
return ""
return "%.2f" % x | null |
154,982 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
ax = fig.add_subplot(1, 1, 1, aspect=1)
ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.tick_params(which="major", width=1.0)
ax.tick_params(which="major", length=10)
ax.tick_params(which="minor", width=1.0, labelsize=10)
ax.tick_params(which="minor", length=5, labelsize=10, labelcolor="0.25")
ax.grid(linestyle="--", linewidth=0.5, color=".25", zorder=-10)
ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)
ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal")
ax.plot(X, Y3, linewidth=0, marker="o", markerfacecolor="w", markeredgecolor="k")
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment="bottom")
ax.set_xlabel("X axis label")
ax.set_ylabel("Y axis label")
ax.legend()
ax.annotate(
"Spines",
xy=(4.0, 0.35),
xytext=(3.3, 0.5),
color=color,
weight="regular", # fontsize="large", fontname="Yanone Kaffeesatz",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color=color),
)
ax.annotate(
"",
xy=(3.15, 0.0),
xytext=(3.45, 0.45),
color=color,
weight="regular", # fontsize="large", fontname="Yanone Kaffeesatz",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color=color),
)
def circle(x, y, radius=0.15):
from matplotlib.patches import Circle
from matplotlib.patheffects import withStroke
circle = Circle(
(x, y),
radius,
clip_on=False,
zorder=10,
linewidth=1,
edgecolor="black",
facecolor=(0, 0, 0, 0.0125),
path_effects=[withStroke(linewidth=5, foreground="w")],
)
ax.add_artist(circle) | null |
154,983 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
ax = fig.add_subplot(1, 1, 1, aspect=1)
ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
ax.tick_params(which="major", width=1.0)
ax.tick_params(which="major", length=10)
ax.tick_params(which="minor", width=1.0, labelsize=10)
ax.tick_params(which="minor", length=5, labelsize=10, labelcolor="0.25")
ax.grid(linestyle="--", linewidth=0.5, color=".25", zorder=-10)
ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)
ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal")
ax.plot(X, Y3, linewidth=0, marker="o", markerfacecolor="w", markeredgecolor="k")
ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment="bottom")
ax.set_xlabel("X axis label")
ax.set_ylabel("Y axis label")
ax.legend()
color = "#000099"
ax.annotate(
"Spines",
xy=(4.0, 0.35),
xytext=(3.3, 0.5),
color=color,
weight="regular", # fontsize="large", fontname="Yanone Kaffeesatz",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color=color),
)
ax.annotate(
"",
xy=(3.15, 0.0),
xytext=(3.45, 0.45),
color=color,
weight="regular", # fontsize="large", fontname="Yanone Kaffeesatz",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color=color),
)
def text(x, y, text):
ax.text(
x,
y,
text,
backgroundcolor="white",
# fontname="Yanone Kaffeesatz", fontsize="large",
ha="center",
va="top",
weight="regular",
color="#000099",
) | null |
154,984 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.patches import Rectangle
image = pixelated_text(75)
fig = plt.figure(figsize=(4.25, 2), dpi=100)
ax = plt.subplot(
1, 2, 1, frameon=False, aspect=1, xticks=[], yticks=[], xlim=[0, 1], ylim=[0, 1]
)
ax.imshow(image, extent=[0.1, 1.0, 0.1, 1.0], zorder=10, interpolation="nearest")
ax.imshow(image, extent=[0.0, 0.2, 0.0, 0.2], zorder=30, interpolation="nearest")
ax.text(0.55, 1.025, "Raster rendering", fontsize="small", ha="center", va="bottom")
ax.text(
0.6, 0.1 - 0.025, ".PNG / .JPG / .TIFF", fontsize="x-small", ha="center", va="top"
)
ax = plt.subplot(
1, 2, 2, frameon=False, aspect=1, xticks=[], yticks=[], xlim=[0, 1], ylim=[0, 1]
)
ax.text(0.55, 0.55, "a", fontsize=100, ha="center", va="center", color="#000099")
ax.text(
0.1,
0.1,
"a",
fontsize=22,
ha="center",
va="center",
clip_on=False,
zorder=30,
color="#000099",
)
ax.text(
0.55,
1.025,
"Vector rendering",
fontsize="small",
ha="center",
va="bottom",
color="#000099",
)
ax.text(
0.6,
0.1 - 0.025,
".PDF / .SVG / .PS",
fontsize="x-small",
ha="center",
va="top",
color="#000099",
)
def pixelated_text(dpi=100):
fig = Figure(figsize=(1, 1), dpi=dpi)
canvas, ax = FigureCanvasAgg(fig), fig.gca()
ax.text(0.5, 0.5, "a", fontsize=75, ha="center", va="center")
ax.axis("off")
canvas.draw()
image = np.frombuffer(canvas.tostring_argb(), dtype="uint8")
image = image.reshape(dpi, dpi, 4)
image = np.roll(image, 3, axis=2)
return image | null |
154,985 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.patches import Rectangle
ax = plt.subplot(
1, 2, 1, frameon=False, aspect=1, xticks=[], yticks=[], xlim=[0, 1], ylim=[0, 1]
)
ax.imshow(image, extent=[0.1, 1.0, 0.1, 1.0], zorder=10, interpolation="nearest")
ax.imshow(image, extent=[0.0, 0.2, 0.0, 0.2], zorder=30, interpolation="nearest")
ax.text(0.55, 1.025, "Raster rendering", fontsize="small", ha="center", va="bottom")
ax.text(
0.6, 0.1 - 0.025, ".PNG / .JPG / .TIFF", fontsize="x-small", ha="center", va="top"
)
ax = plt.subplot(
1, 2, 2, frameon=False, aspect=1, xticks=[], yticks=[], xlim=[0, 1], ylim=[0, 1]
)
ax.text(0.55, 0.55, "a", fontsize=100, ha="center", va="center", color="#000099")
ax.text(
0.1,
0.1,
"a",
fontsize=22,
ha="center",
va="center",
clip_on=False,
zorder=30,
color="#000099",
)
ax.text(
0.55,
1.025,
"Vector rendering",
fontsize="small",
ha="center",
va="bottom",
color="#000099",
)
ax.text(
0.6,
0.1 - 0.025,
".PDF / .SVG / .PS",
fontsize="x-small",
ha="center",
va="top",
color="#000099",
)
def square(position, size, edgecolor, facecolor, zorder):
rect = Rectangle(
position,
size,
size,
transform=ax.transAxes,
clip_on=False,
zorder=zorder,
linewidth=0.5,
edgecolor=edgecolor,
facecolor=facecolor,
)
ax.add_artist(rect) | null |
154,986 | import matplotlib.pyplot as plt
def figure(dpi):
fig = plt.figure(figsize=(4.25, 0.2))
ax = plt.subplot(1, 1, 1, frameon=False)
plt.xticks([]), plt.yticks([])
text = "A text rendered at 10pt size using {0} dpi".format(dpi)
ax.text(
0.5,
0.5,
text,
fontname="Source Serif Pro",
ha="center",
va="center",
fontsize=10,
fontweight="light",
)
plt.savefig("../../figures/anatomy/figure-dpi-{0:03d}.png".format(dpi), dpi=dpi) | null |
154,987 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.colors import LightSource
from matplotlib.transforms import Affine2D
from mpl_toolkits.mplot3d import Axes3D, art3d
from matplotlib.font_manager import FontProperties
for x in np.arange(xrange[0], xrange[1] + xticks[1], xticks[1]):
x = xtransform(x)
ax.plot(
[x, x, x],
[ymin, ymax, ymax],
[zmin, zmin, zmax],
linewidth=linewidth,
color=color,
zorder=-50,
)
for y in np.arange(yrange[0], yrange[1] + yticks[1], yticks[1]):
y = ytransform(y)
ax.plot(
[xmax, xmin, xmin],
[y, y, y],
[zmin, zmin, zmax],
linewidth=linewidth,
color=color,
zorder=-50,
)
for z in np.arange(zrange[0], zrange[1] + zticks[1], zticks[1]):
z = ztransform(z)
ax.plot(
[xmax, xmin, xmin],
[ymax, ymax, ymin],
[z, z, z],
linewidth=linewidth,
color=color,
zorder=-50,
)
for x in np.arange(xrange[0], xrange[1] + xticks[0], xticks[0]):
x = xtransform(x)
ax.plot(
[x, x, x],
[ymin, ymax, ymax],
[zmin, zmin, zmax],
linewidth=linewidth,
color=color,
zorder=-25,
)
for y in np.arange(yrange[0], yrange[1] + yticks[0], yticks[0]):
y = ytransform(y)
ax.plot(
[xmax, xmin, xmin],
[y, y, y],
[zmin, zmin, zmax],
linewidth=linewidth,
color=color,
zorder=-25,
)
for z in np.arange(zrange[0], zrange[1] + zticks[0], zticks[0]):
z = ztransform(z)
ax.plot(
[xmax, xmin, xmin],
[ymax, ymax, ymin],
[z, z, z],
linewidth=linewidth,
color=color,
zorder=-25,
)
for x in np.arange(xrange[0], xrange[1] + xticks[1], xticks[1]):
x = xtransform(x)
ax.plot(
[x, x],
[ymin, ymin - length],
[zmin, zmin],
linewidth=linewidth,
color=color,
zorder=-50,
)
for y in np.arange(yrange[0], yrange[1] + yticks[1], yticks[1]):
y = ytransform(y)
ax.plot(
[xmax, xmax + length],
[y, y],
[zmin, zmin],
linewidth=linewidth,
color=color,
zorder=-50,
)
for z in np.arange(zrange[0], zrange[1] + zticks[1], zticks[1]):
z = ztransform(z)
ax.plot(
[xmin, xmin - length],
[ymin, ymin],
[z, z],
linewidth=linewidth,
color=color,
zorder=-50,
)
for x in np.arange(xrange[0], xrange[1] + xticks[0], xticks[0]):
x_ = xtransform(x)
ax.plot(
[x_, x_],
[ymin, ymin - length],
[zmin, zmin],
linewidth=linewidth,
color=color,
zorder=-50,
)
text3d(
ax,
(x_, ymin - 2 * length, zmin),
"%.1f" % x,
size=0.04,
facecolor="black",
edgecolor="None",
)
for y in np.arange(yrange[0], yrange[1] + yticks[0], yticks[0]):
y_ = ytransform(y)
ax.plot(
[xmax, xmax + length],
[y_, y_],
[zmin, zmin],
linewidth=linewidth,
color=color,
zorder=-50,
)
text3d(
ax,
(xmax + 2 * length, y_, zmin),
"%.1f" % y,
angle=np.pi / 2,
size=0.04,
facecolor="black",
edgecolor="None",
)
for z in np.arange(zrange[0], zrange[1] + zticks[1], zticks[0]):
z_ = ztransform(z)
ax.plot(
[xmin, xmin - length],
[ymin, ymin],
[z_, z_],
linewidth=linewidth,
color=color,
zorder=-50,
)
text3d(
ax,
(xmin - 2 * length, ymin, z_),
"%.1f" % z,
zdir="y",
size=0.04,
facecolor="black",
edgecolor="None",
)
def text3d(ax, xyz, s, zdir="z", size=0.1, angle=0, **kwargs):
x, y, z = xyz
if zdir == "y":
xy, z = (x, z), y
elif zdir == "x":
xy, z = (y, z), x
else:
xy, z = (x, y), z
path = TextPath((0, 0), s, size=size, prop=FontProperties(family="Roboto"))
V = path.vertices
V[:, 0] -= (V[:, 0].max() - V[:, 0].min()) / 2
trans = Affine2D().rotate(angle).translate(xy[0], xy[1])
path = PathPatch(trans.transform_path(path), **kwargs)
ax.add_patch(path)
art3d.pathpatch_2d_to_3d(path, z=z, zdir=zdir) | null |
154,988 | import os
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["text.usetex"] = False
def plot(family):
plt.rcParams["mathtext.fontset"] = family
fig = plt.figure(figsize=(3, 1.75), dpi=100)
ax = plt.subplot(
1, 1, 1, frameon=False, xlim=(-1, 1), ylim=(-0.5, 1.5), xticks=[], yticks=[]
)
ax.text(
0,
0.0,
r"$\frac{\pi}{4} = \sum_{k=0}^\infty\frac{(-1)^k}{2k+1}$",
size=32,
ha="center",
va="bottom",
)
ax.text(
0,
-0.1,
'mathtext.fontset = "%s"' % family,
size=14,
ha="center",
va="top",
family="Roboto Condensed",
color="0.5",
)
# plt.tight_layout()
plt.savefig("../../figures/typography/typography-math-%s.pdf" % family, dpi=600)
plt.show() | null |
154,989 | import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import findfont, FontProperties
size = 20
ax = plt.subplot(
3, 1, 1, frameon=False, xlim=(xmin, xmax), ylim=(-1, 1), xticks=[], yticks=[]
)
ax = plt.subplot(
3, 1, 2, frameon=False, xlim=(xmin, xmax), ylim=(-1, 1), xticks=[], yticks=[]
)
ax = plt.subplot(
3, 1, 3, frameon=False, xlim=(xmin, xmax), ylim=(-1, 1), xticks=[], yticks=[]
)
def font_text(x, y, text, family, dy=0):
ax.text(x, y + dy, text, family=family, size=size, va="bottom")
font = findfont(FontProperties(family=family))
filename = os.path.basename(font)
ax.text(
x,
y,
filename,
va="top",
family="Roboto Condensed",
weight=400,
size=10,
color="0.5",
) | null |
154,990 | import scipy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties
def interpolate(X, Y, T):
ax = fig.add_subplot(1, 2, 1, aspect=1, xticks=[], yticks=[])
ax.clabel(CS, CS.levels)
ax = fig.add_subplot(1, 2, 2, aspect=1, xticks=[], yticks=[])
plt.tight_layout()
plt.savefig("../../figures/typography/typography-text-path.png", dpi=600)
plt.savefig("../../figures/typography/typography-text-path.pdf", dpi=600)
plt.show()
def contour(X, Y, text, offset=0):
# Interpolate text along curve
# X0,Y0 for position + X1,Y1 for normal vectors
path = TextPath(
(0, -0.75), text, prop=FontProperties(size=2, family="Roboto", weight="bold")
)
V = path.vertices
X0, Y0, D = interpolate(X, Y, offset + V[:, 0])
X1, Y1, _ = interpolate(X, Y, offset + V[:, 0] + 0.1)
# Here we interpolate the original path to get the "remainder"
# (path minus text)
X, Y, _ = interpolate(X, Y, np.linspace(V[:, 0].max() + 1, D - 1, 200))
plt.plot(
X, Y, color="black", linewidth=0.5, markersize=1, marker="o", markevery=[0, -1]
)
# Transform text vertices
dX, dY = X1 - X0, Y1 - Y0
norm = np.sqrt(dX ** 2 + dY ** 2)
dX, dY = dX / norm, dY / norm
X0 += -V[:, 1] * dY
Y0 += +V[:, 1] * dX
V[:, 0], V[:, 1] = X0, Y0
# Faint outline
patch = PathPatch(
path,
facecolor="white",
zorder=10,
alpha=0.25,
edgecolor="white",
linewidth=1.25,
)
ax.add_artist(patch)
# Actual text
patch = PathPatch(
path, facecolor="black", zorder=30, edgecolor="black", linewidth=0.0
)
ax.add_artist(patch) | null |
154,991 | import scipy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-(x ** 2) - y ** 2) | null |
154,992 | import tqdm
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from scipy.ndimage import gaussian_filter
from matplotlib.collections import LineCollection
from matplotlib.backends.backend_agg import FigureCanvas
np.random.seed(12345)
if 1: # Set to 0 after computation
edges = metropolis(width, height)
np.save("egdes.npy", edges)
else:
edges = np.load("egdes.npy")
def metropolis(width=10000, height=10000, n=11000, step=75, branching=0.1, noise=2.0):
delta = noise * np.pi / 180
points = np.zeros(
n, dtype=[("x", float), ("y", float), ("dir", float), ("level", int)]
)
edges = np.zeros(
n,
dtype=[
("x0", float),
("y0", float),
("x1", float),
("y1", float),
("level", int),
],
)
points[0] = width / 2, height / 2, np.random.uniform(-2 * np.pi, 2 * np.pi), 1
for i in tqdm.trange(1, n):
while True:
point = np.random.choice(points[:i])
branch = 1 if np.random.uniform(0, 1) <= branching else 0
alpha = point["dir"] + delta * np.random.uniform(-1, +1)
alpha += branch * np.random.choice([-np.pi / 2, +np.pi / 2])
v = np.array((np.cos(alpha), np.sin(alpha)))
v = v * step * (1 + 1 / (point["level"] + branch))
x = point["x"] + v[0]
y = point["y"] + v[1]
level = point["level"] + branch
if x < 0 or x > width or y < 0 or y > height:
continue
dist = np.sqrt((points["x"] - x) ** 2 + (points["y"] - y) ** 2)
if dist.min() >= step:
points[i] = x, y, alpha, level
edges[i] = x, y, point["x"], point["y"], level
break
return edges[edges["level"] > 0] | null |
154,993 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def lighten_color(color, amount=0.66):
import colorsys
try:
c = mcolors.cnames[color]
except:
c = color
c = np.array(colorsys.rgb_to_hls(*mcolors.to_rgb(c)))
return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2]) | null |
154,994 | import os
import numpy as np
import html.parser
import urllib.request
import dateutil.parser
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
n = 5
The provided code snippet includes necessary dependencies for implementing the `github_contrib` function. Write a Python function `def github_contrib(user, year)` to solve the following problem:
Get GitHub user daily contribution
Here is the function:
def github_contrib(user, year):
""" Get GitHub user daily contribution """
# Check for a cached version (file)
filename = "github-{0}-{1}.html".format(user, year)
if os.path.exists(filename):
with open(filename) as file:
contents = file.read()
# Else get file from GitHub
else:
url = "https://github.com/users/{0}/contributions?to={1}-12-31"
url = url.format(user, year)
contents = str(urllib.request.urlopen(url).read())
with open(filename, "w") as file:
file.write(contents)
# Parse result (html)
n = 1 + (date(year, 12, 31) - date(year, 1, 1)).days
C = -np.ones(n, dtype=int)
class HTMLParser(html.parser.HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == "rect":
data = {key: value for (key, value) in attrs}
date = dateutil.parser.parse(data["data-date"])
count = int(data["data-count"])
day = date.timetuple().tm_yday - 1
if count > 0:
C[day] = count
parser = HTMLParser()
parser.feed(contents)
return C | Get GitHub user daily contribution |
154,995 | import os
import numpy as np
import html.parser
import urllib.request
import dateutil.parser
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
plt.tight_layout()
plt.show()
def calmap(ax, year, data, origin="upper", weekstart="sun"):
ax.tick_params("x", length=0, labelsize="medium", which="major")
ax.tick_params("y", length=0, labelsize="x-small", which="major")
# Month borders
xticks, labels = [], []
start = datetime(year, 1, 1).weekday()
_data = np.zeros(7 * 53) * np.nan
_data[start : start + len(data)] = data
data = _data.reshape(53, 7).T
for month in range(1, 13):
first = datetime(year, month, 1)
last = first + relativedelta(months=1, days=-1)
if origin == "lower":
y0 = first.weekday()
y1 = last.weekday()
x0 = (int(first.strftime("%j")) + start - 1) // 7
x1 = (int(last.strftime("%j")) + start - 1) // 7
P = [
(x0, y0),
(x0, 7),
(x1, 7),
(x1, y1 + 1),
(x1 + 1, y1 + 1),
(x1 + 1, 0),
(x0 + 1, 0),
(x0 + 1, y0),
]
else:
y0 = 6 - first.weekday()
y1 = 6 - last.weekday()
x0 = (int(first.strftime("%j")) + start - 1) // 7
x1 = (int(last.strftime("%j")) + start - 1) // 7
P = [
(x0, y0 + 1),
(x0, 0),
(x1, 0),
(x1, y1),
(x1 + 1, y1),
(x1 + 1, 7),
(x0 + 1, 7),
(x0 + 1, y0 + 1),
]
xticks.append(x0 + (x1 - x0 + 1) / 2)
labels.append(first.strftime("%b"))
poly = Polygon(
P,
edgecolor="black",
facecolor="None",
linewidth=1,
zorder=20,
clip_on=False,
)
ax.add_artist(poly)
ax.set_xticks(xticks)
ax.set_xticklabels(labels)
ax.set_yticks(0.5 + np.arange(7))
labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
if origin == "upper":
labels = labels[::-1]
ax.set_yticklabels(labels)
ax.set_title("{}".format(year), size="medium", weight="bold")
# Showing data
cmap = plt.cm.get_cmap("Purples")
ax.imshow(
data, extent=[0, 53, 0, 7], zorder=10, vmin=0, vmax=10, cmap=cmap, origin=origin
) | null |
154,996 | import numpy as np
import imageio
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.text import TextPath
import matplotlib.patches as mpatches
import matplotlib.patheffects as path_effects
from matplotlib.font_manager import FontProperties
def box(ax, index, x, y, width, height):
rectangle = mpatches.Rectangle(
(x, y), width, height, zorder=10, facecolor="none", edgecolor="black"
)
ax.add_artist(rectangle)
ax.text(
x + (width - 1) / 2,
y + (height - 1) / 2,
"%d" % index,
weight="bold",
zorder=50,
size="32",
va="center",
ha="center",
color="k",
alpha=0.25,
family="GlassJaw BB",
) | null |
154,997 | import git
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
def calmap(ax, year, data, origin="upper", weekstart="sun"):
ax.tick_params("x", length=0, labelsize="medium", which="major")
ax.tick_params("y", length=0, labelsize="x-small", which="major")
# Month borders
xticks, labels = [], []
start = datetime(year, 1, 1).weekday()
_data = np.zeros(7 * 53) * np.nan
_data[start : start + len(data)] = data
data = _data.reshape(53, 7).T
for month in range(1, 13):
first = datetime(year, month, 1)
last = first + relativedelta(months=1, days=-1)
if origin == "lower":
y0 = first.weekday()
y1 = last.weekday()
x0 = (int(first.strftime("%j")) + start - 1) // 7
x1 = (int(last.strftime("%j")) + start - 1) // 7
P = [
(x0, y0),
(x0, 7),
(x1, 7),
(x1, y1 + 1),
(x1 + 1, y1 + 1),
(x1 + 1, 0),
(x0 + 1, 0),
(x0 + 1, y0),
]
else:
y0 = 6 - first.weekday()
y1 = 6 - last.weekday()
x0 = (int(first.strftime("%j")) + start - 1) // 7
x1 = (int(last.strftime("%j")) + start - 1) // 7
P = [
(x0, y0 + 1),
(x0, 0),
(x1, 0),
(x1, y1),
(x1 + 1, y1),
(x1 + 1, 7),
(x0 + 1, 7),
(x0 + 1, y0 + 1),
]
xticks.append(x0 + (x1 - x0 + 1) / 2)
labels.append(first.strftime("%b"))
poly = Polygon(
P,
edgecolor="black",
facecolor="None",
linewidth=1,
zorder=20,
clip_on=False,
)
ax.add_artist(poly)
ax.set_xticks(xticks)
ax.set_xticklabels(labels)
ax.set_yticks(0.5 + np.arange(7))
labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
if origin == "upper":
labels = labels[::-1]
ax.set_yticklabels(labels)
ax.text(
1.01,
0.5,
"{}".format(year),
rotation=90,
ha="left",
va="center",
transform=ax.transAxes,
size="28",
weight="bold",
alpha=0.5,
)
# Showing data
cmap = plt.cm.get_cmap("Purples")
im = ax.imshow(
data, extent=[0, 53, 0, 7], zorder=10, vmin=0, vmax=8, cmap=cmap, origin=origin
) | null |
154,998 | import git
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
The provided code snippet includes necessary dependencies for implementing the `get_commits` function. Write a Python function `def get_commits(year=2021, path="../..")` to solve the following problem:
Collect commit dates for a given year
Here is the function:
def get_commits(year=2021, path="../.."):
"Collect commit dates for a given year"
n = 1 + (date(year, 12, 31) - date(year, 1, 1)).days
C = np.zeros(n, dtype=int)
repo = git.Repo(path)
for commit in repo.iter_commits("master"):
timestamp = datetime.fromtimestamp(commit.committed_date)
if timestamp.year == year:
day = timestamp.timetuple().tm_yday
C[day - 1] += 1
return C | Collect commit dates for a given year |
154,999 | import noise
import numpy as np
import scipy.spatial
import shapely.geometry
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.collections import PolyCollection
from math import cos, sin, floor, sqrt, pi, ceil
np.random.seed(1)
The provided code snippet includes necessary dependencies for implementing the `blue_noise` function. Write a Python function `def blue_noise(shape, radius, k=32, seed=None)` to solve the following problem:
Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
Here is the function:
def blue_noise(shape, radius, k=32, seed=None):
"""
Generate blue noise over a two-dimensional rectangle of size (width,height)
Parameters
----------
shape : tuple
Two-dimensional domain (width x height)
radius : float
Minimum distance between samples
k : int, optional
Limit of samples to choose before rejection (typically k = 30)
seed : int, optional
If provided, this will set the random seed before generating noise,
for valid pseudo-random comparisons.
References
----------
.. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson,
Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
"""
def sqdist(a, b):
""" Squared Euclidean distance """
dx, dy = a[0] - b[0], a[1] - b[1]
return dx * dx + dy * dy
def grid_coords(p):
""" Return index of cell grid corresponding to p """
return int(floor(p[0] / cellsize)), int(floor(p[1] / cellsize))
def fits(p, radius):
""" Check whether p can be added to the queue """
radius2 = radius * radius
gx, gy = grid_coords(p)
for x in range(max(gx - 2, 0), min(gx + 3, grid_width)):
for y in range(max(gy - 2, 0), min(gy + 3, grid_height)):
g = grid[x + y * grid_width]
if g is None:
continue
if sqdist(p, g) <= radius2:
return False
return True
# When given a seed, we use a private random generator in order to not
# disturb the default global random generator
if seed is not None:
from numpy.random.mtrand import RandomState
rng = RandomState(seed=seed)
else:
rng = np.random
width, height = shape
cellsize = radius / sqrt(2)
grid_width = int(ceil(width / cellsize))
grid_height = int(ceil(height / cellsize))
grid = [None] * (grid_width * grid_height)
p = rng.uniform(0, shape, 2)
queue = [p]
grid_x, grid_y = grid_coords(p)
grid[grid_x + grid_y * grid_width] = p
while queue:
qi = rng.randint(len(queue))
qx, qy = queue[qi]
queue[qi] = queue[-1]
queue.pop()
for _ in range(k):
theta = rng.uniform(0, 2 * pi)
r = radius * np.sqrt(rng.uniform(1, 4))
p = qx + r * cos(theta), qy + r * sin(theta)
if not (0 <= p[0] < width and 0 <= p[1] < height) or not fits(p, radius):
continue
queue.append(p)
gx, gy = grid_coords(p)
grid[gx + gy * grid_width] = p
return np.array([p for p in grid if p is not None]) | Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807` |
155,000 | import noise
import numpy as np
import scipy.spatial
import shapely.geometry
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.collections import PolyCollection
from math import cos, sin, floor, sqrt, pi, ceil
np.random.seed(1)
P = blue_noise((11, 11), radius=radius) - (0.5, 0.5)
Z = np.zeros(shape)
X = np.linspace(0, 10, 256)
def hatch(n=4, theta=None):
theta = theta or np.random.uniform(0, np.pi)
P = np.zeros((n, 2, 2))
X = np.linspace(-0.5, +0.5, n, endpoint=True)
P[:, 0, 1] = -0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 1] = +0.5 + np.random.normal(0, 0.05, n)
P[:, 1, 0] = X + np.random.normal(0, 0.025, n)
P[:, 0, 0] = X + np.random.normal(0, 0.025, n)
c, s = np.cos(theta), np.sin(theta)
Z = np.array([[c, s], [-s, c]])
return P @ Z.T | null |
155,001 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
The provided code snippet includes necessary dependencies for implementing the `tetrahedron` function. Write a Python function `def tetrahedron()` to solve the following problem:
Tetrahedron with 4 faces, 6 edges and 4 vertices
Here is the function:
def tetrahedron():
""" Tetrahedron with 4 faces, 6 edges and 4 vertices """
a = 2 * np.pi / 3
vertices = [
(0, 0.5, 0),
(0.5 * np.cos(0 * a), -0.25, 0.5 * np.sin(0 * a)),
(0.5 * np.cos(1 * a), -0.25, 0.5 * np.sin(1 * a)),
(0.5 * np.cos(2 * a), -0.25, 0.5 * np.sin(2 * a)),
]
faces = [(1, 2, 3), (1, 2, 0), (2, 3, 0), (3, 1, 0)]
return np.array(vertices), np.array(faces) | Tetrahedron with 4 faces, 6 edges and 4 vertices |
155,002 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
The provided code snippet includes necessary dependencies for implementing the `octahedron` function. Write a Python function `def octahedron()` to solve the following problem:
Octahedron with 8 faces, 12 edges and 6 vertices
Here is the function:
def octahedron():
""" Octahedron with 8 faces, 12 edges and 6 vertices """
r = 0.5 * 1 / np.sqrt(2)
vertices = [
(0, 0.5, 0),
(0, -0.5, 0),
(-r, 0, -r),
(r, 0, -r),
(r, 0, r),
(-r, 0, r),
]
faces = [
(2, 3, 0),
(3, 4, 0),
(4, 5, 0),
(5, 2, 0),
(3, 2, 1),
(4, 3, 1),
(5, 4, 1),
(2, 5, 1),
]
return np.array(vertices), np.array(faces) | Octahedron with 8 faces, 12 edges and 6 vertices |
155,003 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
The provided code snippet includes necessary dependencies for implementing the `dodecahedron` function. Write a Python function `def dodecahedron()` to solve the following problem:
Regular dodecahedron with 12 faces, 30 edges and 20 vertices
Here is the function:
def dodecahedron():
""" Regular dodecahedron with 12 faces, 30 edges and 20 vertices """
r = (1 + np.sqrt(5)) / 2
vertices = [
(-1, -1, +1),
(r, 1 / r, 0),
(r, -1 / r, 0),
(-r, 1 / r, 0),
(-r, -1 / r, 0),
(0, r, 1 / r),
(0, r, -1 / r),
(1 / r, 0, -r),
(-1 / r, 0, -r),
(0, -r, -1 / r),
(0, -r, 1 / r),
(1 / r, 0, r),
(-1 / r, 0, r),
(+1, +1, -1),
(+1, +1, +1),
(-1, +1, -1),
(-1, +1, +1),
(+1, -1, -1),
(+1, -1, +1),
(-1, -1, -1),
]
# faces = [ (19, 3, 2), (12, 19, 2), (15, 12, 2),
# (8, 14, 2), (18, 8, 2), (3, 18, 2),
# (20, 5, 4), (9, 20, 4), (16, 9, 4),
# (13, 17, 4), (1, 13, 4), (5, 1, 4),
# (7, 16, 4), (6, 7, 4), (17, 6, 4),
# (6, 15, 2), (7, 6, 2), (14, 7, 2),
# (10, 18, 3), (11, 10, 3), (19, 11, 3),
# (11, 1, 5), (10, 11, 5), (20, 10, 5),
# (20, 9, 8), (10, 20, 8), (18, 10, 8),
# (9, 16, 7), (8, 9, 7), (14, 8, 7),
# (12, 15, 6), (13, 12, 6), (17, 13, 6),
# (13, 1, 11), (12, 13, 11), (19, 12, 11) ]
faces = [
(19, 3, 2, 15, 12),
(8, 14, 2, 3, 18),
(20, 5, 4, 16, 9),
(13, 17, 4, 5, 1),
(7, 16, 4, 17, 6),
(6, 15, 2, 14, 7),
(10, 18, 3, 19, 11),
(11, 1, 5, 20, 10),
(20, 9, 8, 18, 10),
(9, 16, 7, 14, 8),
(12, 15, 6, 17, 13),
(13, 1, 11, 19, 12),
]
vertices = np.array(vertices) / np.sqrt(3) / 2
faces = np.array(faces) - 1
return vertices, faces | Regular dodecahedron with 12 faces, 30 edges and 20 vertices |
155,004 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
The provided code snippet includes necessary dependencies for implementing the `icosahedron` function. Write a Python function `def icosahedron()` to solve the following problem:
Regular icosahedron with 20 faces, 30 edges and 12 vertices
Here is the function:
def icosahedron():
""" Regular icosahedron with 20 faces, 30 edges and 12 vertices """
a = (1 + np.sqrt(5)) / 2
vertices = [
(-1, a, 0),
(1, a, 0),
(-1, -a, 0),
(1, -a, 0),
(0, -1, a),
(0, 1, a),
(0, -1, -a),
(0, 1, -a),
(a, 0, -1),
(a, 0, 1),
(-a, 0, -1),
(-a, 0, 1),
]
faces = [
[0, 11, 5],
[0, 5, 1],
[0, 1, 7],
[0, 7, 10],
[0, 10, 11],
[1, 5, 9],
[5, 11, 4],
[11, 10, 2],
[10, 7, 6],
[7, 1, 8],
[3, 9, 4],
[3, 4, 2],
[3, 2, 6],
[3, 6, 8],
[3, 8, 9],
[4, 9, 5],
[2, 4, 11],
[6, 2, 10],
[8, 6, 7],
[9, 8, 1],
]
vertices = np.array(vertices) / np.sqrt(a + 2) / 2
faces = np.array(faces)
return vertices, faces | Regular icosahedron with 20 faces, 30 edges and 12 vertices |
155,005 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
def cube():
vertices = [
(0, 0, 0),
(1, 0, 0),
(1, 0, 1),
(0, 0, 1),
(0, 1, 0),
(1, 1, 0),
(1, 1, 1),
(0, 1, 1),
]
faces = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[0, 1, 5, 4],
[1, 2, 6, 5],
[2, 3, 7, 6],
[3, 0, 4, 7],
]
return (np.array(vertices) - 0.5) / np.sqrt(2), np.array(faces) | null |
155,006 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
def plot(ax, camera, V, F):
ax.axis("off")
T = glm.transform(V[F], camera)
V, Z = T[..., :2], T[..., 2].mean(axis=-1)
V = V[np.argsort(-Z)]
collection = PolyCollection(
V,
antialiased=True,
linewidth=1.0,
facecolor=(0.9, 0.9, 1, 0.75),
edgecolor=(0, 0, 0.75, 0.25),
)
ax.add_collection(collection) | null |
155,007 | import glm
import plot
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-(x ** 2) - y ** 2) | null |
155,008 | import glm
import plot
import numpy as np
import matplotlib.pyplot as plt
V, F = obj_load("bunny.obj")
V = glm.fit_unit_cube(V)
def obj_load(filename):
V, Vi = [], []
with open(filename) as f:
for line in f.readlines():
if line.startswith("#"):
continue
values = line.split()
if not values:
continue
if values[0] == "v":
V.append([float(x) for x in values[1:4]])
elif values[0] == "f":
Vi.append([int(x) for x in values[1:4]])
return np.array(V), np.array(Vi) - 1 | null |
155,009 | import glm
import plot
import numpy as np
import matplotlib.pyplot as plt
def sphere(radius=1.0, slices=32, stacks=32):
slices += 1
stacks += 1
n = slices * stacks
vertices = np.zeros((n, 3))
theta1 = np.repeat(np.linspace(0, np.pi, stacks, endpoint=True), slices)
theta2 = np.tile(np.linspace(0, 2 * np.pi, slices, endpoint=True), stacks)
vertices[:, 1] = np.sin(theta1) * np.cos(theta2) * radius
vertices[:, 2] = np.cos(theta1) * radius
vertices[:, 0] = np.sin(theta1) * np.sin(theta2) * radius
indices = []
for i in range(stacks - 1):
for j in range(slices - 1):
indices.append(i * (slices) + j)
indices.append(i * (slices) + j + 1)
indices.append(i * (slices) + j + slices + 1)
indices.append(i * (slices) + j + slices + 1)
indices.append(i * (slices) + j + slices)
indices.append(i * (slices) + j)
indices = np.array(indices)
indices = indices.reshape(len(indices) // 3, 3)
return vertices, indices | null |
155,010 | import glm
import plot
import numpy as np
import matplotlib.pyplot as plt
def lighting(F, direction=(1, 1, 1), color=(1, 0, 0), specular=False):
# Faces center
C = F.mean(axis=1)
# Faces normal
N = glm.normalize(np.cross(F[:, 2] - F[:, 0], F[:, 1] - F[:, 0]))
# Relative light direction
D = glm.normalize(C - direction)
# Diffuse term
diffuse = glm.clip((N * D).sum(-1).reshape(-1, 1))
# Specular term
if specular:
specular = np.power(diffuse, 24)
return np.maximum(diffuse * color, specular)
return diffuse * color | null |
155,011 | import numpy as np
def center(V):
return V - (V.min(axis=-1) + V.max(axis=-1)) / 2 | null |
155,012 | import numpy as np
def degrees(angle):
return 180 * angle / np.pi | null |
155,013 | import numpy as np
def radians(angle):
return np.pi * angle / 180
def zrotate(theta=0):
t = radians(theta)
c, s = np.cos(t), np.sin(t)
return np.array(
[[c, -s, 0, 0], [s, c, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.float32
) | null |
155,014 | import numpy as np
def scale(x=1, y=1, z=1):
return np.array(
[[x, 0, 0, 0], [0, y, 0, 0], [0, 0, z, 0], [0, 0, 0, 1]], dtype=np.float32
)
def fit_unit_cube(V):
xmin, xmax = V[:, 0].min(), V[:, 0].max()
ymin, ymax = V[:, 1].min(), V[:, 1].max()
zmin, zmax = V[:, 2].min(), V[:, 2].max()
scale = max([xmax - xmin, ymax - ymin, zmax - zmin])
V /= scale
V[:, 0] -= (xmax + xmin) / 2 / scale
V[:, 1] -= (ymax + ymin) / 2 / scale
V[:, 2] -= (zmax + zmin) / 2 / scale
return V | null |
155,015 | import numpy as np
def perspective(fovy, aspect, znear, zfar):
h = np.tan(0.5 * radians(fovy)) * znear
w = h * aspect
return frustum(-w, w, -h, h, znear, zfar)
def ortho(left, right, bottom, top, znear, zfar):
M = np.zeros((4, 4), dtype=np.float32)
M[0, 0] = +2.0 / (right - left)
M[1, 1] = +2.0 / (top - bottom)
M[2, 2] = -2.0 / (zfar - znear)
M[3, 3] = 1.0
M[0, 2] = -(right + left) / float(right - left)
M[1, 3] = -(top + bottom) / float(top - bottom)
M[2, 3] = -(zfar + znear) / float(zfar - znear)
return M
def scale(x=1, y=1, z=1):
return np.array(
[[x, 0, 0, 0], [0, y, 0, 0], [0, 0, z, 0], [0, 0, 0, 1]], dtype=np.float32
)
def translate(x=0, y=0, z=0):
return np.array(
[[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]], dtype=np.float32
)
def xrotate(theta=0):
t = radians(theta)
c, s = np.cos(t), np.sin(t)
return np.array(
[[1, 0, 0, 0], [0, c, -s, 0], [0, s, c, 0], [0, 0, 0, 1]], dtype=np.float32
)
def yrotate(theta=0):
t = radians(theta)
c, s = np.cos(t), np.sin(t)
return np.array(
[[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype=np.float32
)
def camera(xrotation=25, yrotation=45, zoom=1, mode="perspective"):
xrotation = min(max(xrotation, 0), 90)
yrotation = min(max(yrotation, 0), 90)
zoom = max(0.1, zoom)
model = scale(zoom, zoom, zoom) @ xrotate(xrotation) @ yrotate(yrotation)
view = translate(0, 0, -4.5)
if mode == "ortho":
proj = ortho(-1, +1, -1, +1, 1, 100)
else:
proj = perspective(25, 1, 1, 100)
return proj @ view @ model | null |
155,016 | import glm
import plot
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
V, F = obj_load("bunny.obj")
V = glm.fit_unit_cube(V)
def obj_load(filename):
V, Vi = [], []
with open(filename) as f:
for line in f.readlines():
if line.startswith("#"):
continue
values = line.split()
if not values:
continue
if values[0] == "v":
V.append([float(x) for x in values[1:4]])
elif values[0] == "f":
Vi.append([int(x) for x in values[1:4]])
return np.array(V), np.array(Vi) - 1 | null |
155,017 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.collections import PolyCollection
def axis(ax, camera, ticks=True):
"""
Draw three dimension axis with ticks and tick labels.
Parameters:
-----------
ax : matplotlib.axes instance
The regulmat axes where to draw
camera : 4x4 numpy array
A transformation matrix in homogenous coordinates (4x4)
ticks : bool
Whether to draw tick and tick labels
Note:
-----
The axis is drawn inside the unit cube centered on the origin:
- XZ lies on the plane Y = -0.5
- XY lies on the plane Z = -0.5
- YZ lies on the plane X = +0.5
- xticks goes from (-0.5, -0.5, +0.5) to (+0.5, -0.5, +0.5)
- zticks goes from (-0.5, -0.5, -0.5) to (-0.5, -0.5, +0.5)
- yticks goes from (-0.5, -0.5, -0.5) to (-0.5, +0.5, -0.5)
"""
# Mandatory settings for matplotlib axes
# --------------------------------------
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
# Parameters
# ---------------------------------
axis_linewidth = 1.00
grid_linewidth = 0.50
ticks_linewidth = 0.75
grid_color = "0.5"
axis_color = "0.0"
ticks_color = "0.0"
ticks_length = 0.025
ticks_pad = 0.05
# ticks and ticklabels
nx = 11
xticks = np.linspace(-0.5, +0.5, nx, endpoint=True)
xticklabels = ["%.1f" % x for x in xticks]
ny = 11
yticks = np.linspace(-0.5, +0.5, ny, endpoint=True)
yticklabels = ["%.1f" % y for y in yticks]
nz = 11
zticks = np.linspace(-0.5, +0.5, nz, endpoint=True)
zticklabels = ["%.1f" % z for z in zticks]
colors = []
segments = []
linewidths = []
# XZ axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 0, 1]
X2 = X1 + [0, 0, ticks_length]
X3 = X2 + [0, 0, ticks_pad]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
X2 = glm.transform(X2, camera)[..., :2]
X3 = glm.transform(X3, camera)[..., :2]
Z0 = np.linspace([0, 0, 0], [0, 0, 1], nz) - 0.5
Z1 = Z0 + [1, 0, 0]
Z2 = Z0 - [ticks_length, 0, 0]
Z3 = Z2 - [ticks_pad, 0, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Z2 = glm.transform(Z2, camera)[..., :2]
Z3 = glm.transform(Z3, camera)[..., :2]
for p0, p1, p2, p3, label in zip(X0, X1, X2, X3, xticklabels):
# grid line
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# tick
segments.append([p1, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
for p0, p1, p2, p3, label in zip(Z0, Z1, Z2, Z3, zticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# XY axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 1, 0]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
Y0 = np.linspace([0, 0, 0], [0, 1, 0], ny) - 0.5
Y1 = Y0 + [1, 0, 0]
Y2 = Y0 - [ticks_length, 0, 0]
Y3 = Y2 - [ticks_pad, 0, 0]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
Y2 = glm.transform(Y2, camera)[..., :2]
Y3 = glm.transform(Y3, camera)[..., :2]
for p0, p1 in zip(X0, X1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1, p2, p3, label in zip(Y0, Y1, Y2, Y3, yticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# ZY axis
# ---------------------------------
Z0 = np.linspace([1, 0, 0], [1, 0, 1], nx) - 0.5
Z1 = Z0 + [0, 1, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Y0 = np.linspace([1, 0, 0], [1, 1, 0], ny) - 0.5
Y1 = Y0 + [0, 0, 1]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
for p0, p1 in zip(Z0, Z1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1 in zip(Y0, Y1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
# axis border
segments.append([Y0[0], Y0[-1], Y1[-1], Y1[0], Y0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# Actual rendering
collection = PolyCollection(
segments,
closed=False,
clip_on=False,
linewidths=linewidths,
facecolors="None",
edgecolor=colors,
)
ax.add_collection(collection)
def mesh(
ax,
camera,
vertices,
faces,
cmap=None,
facecolor="white",
edgecolor="none",
linewidth=1.0,
mode="all",
):
# Mandatory settings for matplotlib axes
# --------------------------------------
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
facecolor = mpl.colors.to_rgba_array(facecolor)
edgecolor = mpl.colors.to_rgba_array(edgecolor)
T = glm.transform(vertices, camera)[faces]
Z = -T[:, :, 2].mean(axis=1)
# Facecolor using depth buffer
if cmap is not None:
cmap = plt.get_cmap("magma")
norm = mpl.colors.Normalize(vmin=Z.min(), vmax=Z.max())
facecolor = cmap(norm(Z))
# Back face culling
if mode == "front":
front, back = glm.frontback(T)
T, Z = T[front], Z[front]
if len(facecolor) == len(faces):
facecolor = facecolor[front]
if len(edgecolor) == len(faces):
facecolor = edgecolor[front]
# Front face culling
elif mode == "back":
front, back = glm.frontback(T)
T, Z = T[back], Z[back]
if len(facecolor) == len(faces):
facecolor = facecolor[back]
if len(edgecolor) == len(faces):
facecolor = edgecolor[back]
# Separate 2d triangles from zbuffer
triangles = T[:, :, :2]
antialiased = True
if linewidth == 0.0:
antialiased = False
# Sort triangles according to z buffer
I = np.argsort(Z)
triangles = triangles[I, :]
if len(facecolor) == len(I):
facecolor = facecolor[I, :]
if len(edgecolor) == len(I):
edgecolor = edgecolor[I, :]
collection = PolyCollection(
triangles,
linewidth=linewidth,
antialiased=antialiased,
facecolor=facecolor,
edgecolor=edgecolor,
)
ax.add_collection(collection) | null |
155,018 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.collections import PolyCollection
def axis(ax, camera, ticks=True):
"""
Draw three dimension axis with ticks and tick labels.
Parameters:
-----------
ax : matplotlib.axes instance
The regulmat axes where to draw
camera : 4x4 numpy array
A transformation matrix in homogenous coordinates (4x4)
ticks : bool
Whether to draw tick and tick labels
Note:
-----
The axis is drawn inside the unit cube centered on the origin:
- XZ lies on the plane Y = -0.5
- XY lies on the plane Z = -0.5
- YZ lies on the plane X = +0.5
- xticks goes from (-0.5, -0.5, +0.5) to (+0.5, -0.5, +0.5)
- zticks goes from (-0.5, -0.5, -0.5) to (-0.5, -0.5, +0.5)
- yticks goes from (-0.5, -0.5, -0.5) to (-0.5, +0.5, -0.5)
"""
# Mandatory settings for matplotlib axes
# --------------------------------------
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
# Parameters
# ---------------------------------
axis_linewidth = 1.00
grid_linewidth = 0.50
ticks_linewidth = 0.75
grid_color = "0.5"
axis_color = "0.0"
ticks_color = "0.0"
ticks_length = 0.025
ticks_pad = 0.05
# ticks and ticklabels
nx = 11
xticks = np.linspace(-0.5, +0.5, nx, endpoint=True)
xticklabels = ["%.1f" % x for x in xticks]
ny = 11
yticks = np.linspace(-0.5, +0.5, ny, endpoint=True)
yticklabels = ["%.1f" % y for y in yticks]
nz = 11
zticks = np.linspace(-0.5, +0.5, nz, endpoint=True)
zticklabels = ["%.1f" % z for z in zticks]
colors = []
segments = []
linewidths = []
# XZ axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 0, 1]
X2 = X1 + [0, 0, ticks_length]
X3 = X2 + [0, 0, ticks_pad]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
X2 = glm.transform(X2, camera)[..., :2]
X3 = glm.transform(X3, camera)[..., :2]
Z0 = np.linspace([0, 0, 0], [0, 0, 1], nz) - 0.5
Z1 = Z0 + [1, 0, 0]
Z2 = Z0 - [ticks_length, 0, 0]
Z3 = Z2 - [ticks_pad, 0, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Z2 = glm.transform(Z2, camera)[..., :2]
Z3 = glm.transform(Z3, camera)[..., :2]
for p0, p1, p2, p3, label in zip(X0, X1, X2, X3, xticklabels):
# grid line
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# tick
segments.append([p1, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
for p0, p1, p2, p3, label in zip(Z0, Z1, Z2, Z3, zticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# XY axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 1, 0]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
Y0 = np.linspace([0, 0, 0], [0, 1, 0], ny) - 0.5
Y1 = Y0 + [1, 0, 0]
Y2 = Y0 - [ticks_length, 0, 0]
Y3 = Y2 - [ticks_pad, 0, 0]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
Y2 = glm.transform(Y2, camera)[..., :2]
Y3 = glm.transform(Y3, camera)[..., :2]
for p0, p1 in zip(X0, X1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1, p2, p3, label in zip(Y0, Y1, Y2, Y3, yticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# ZY axis
# ---------------------------------
Z0 = np.linspace([1, 0, 0], [1, 0, 1], nx) - 0.5
Z1 = Z0 + [0, 1, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Y0 = np.linspace([1, 0, 0], [1, 1, 0], ny) - 0.5
Y1 = Y0 + [0, 0, 1]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
for p0, p1 in zip(Z0, Z1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1 in zip(Y0, Y1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
# axis border
segments.append([Y0[0], Y0[-1], Y1[-1], Y1[0], Y0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# Actual rendering
collection = PolyCollection(
segments,
closed=False,
clip_on=False,
linewidths=linewidths,
facecolors="None",
edgecolor=colors,
)
ax.add_collection(collection)
def surf(
ax,
camera,
Y,
facecolor="white",
edgecolor="black",
facecolors=None,
edgecolors=None,
linewidth=0.5,
shading=(1.00, 1.00, 1.00, 0.75, 0.50, 1.00),
):
# Mandatory settings for matplotlib axes
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
# Facecolor
if facecolors is None:
facecolors = np.zeros((Y.shape[0], Y.shape[1], 3))
facecolors[...] = mpl.colors.to_rgb(facecolor)
facecolors[...] = facecolors[..., :3]
# Facecolor
if edgecolors is None:
edgecolors = np.zeros((Y.shape[0], Y.shape[1], 3))
edgecolors[...] = mpl.colors.to_rgb(edgecolor)
edgecolors[...] = edgecolors[..., :3]
# Surface
n = Y.shape[0]
T = np.linspace(-0.5, +0.5, n)
X, Z = np.meshgrid(T, T)
V = np.c_[X.ravel(), Y.ravel() - 0.5, Z.ravel()]
F = (np.arange((n - 1) * (n)).reshape(n - 1, n))[:, :-1].T
F = np.repeat(F.ravel(), 6).reshape(n - 1, n - 1, 6)
F[:, :] += np.array([0, n + 1, 1, 0, n, n + 1])
F = F.reshape(-1, 3)
V = glm.transform(V, camera)
T = V[F]
# Create list from array such that we can add lines
polys = T[..., :2].tolist()
zbuffer = (-T[..., 2].mean(axis=1)).tolist()
edgecolors = ["none",] * len(polys)
antialiased = [False,] * len(polys)
linewidths = [1.0,] * len(polys)
facecolors = ((facecolors.reshape(-1, 3))[F].mean(axis=1)).tolist()
# Helper function for creating a line segment between two points
def segment(p0, p1, linewidth=1.5, epsilon=0.01):
polys.append([p0[:2], p1[:2]])
facecolors.append("none")
edgecolors.append("black")
antialiased.append(True)
linewidths.append(linewidth)
zbuffer.append(-(p0[2] + p1[2]) / 2 + epsilon)
# Border + grid over the surface
V = V.reshape(n, n, -1)
# Border
for i in range(0, n - 1):
segment(V[i, 0], V[i + 1, 0])
segment(V[i, -1], V[i + 1, -1])
segment(V[0, i], V[0, i + 1])
segment(V[-1, i], V[-1, i + 1])
for i in range(0, n - 1):
for j in range(0, n - 1):
segment(V[i, j], V[i + 1, j], 0.5)
segment(V[j, i], V[j, i + 1], 0.5)
# Sort everything
I = np.argsort(zbuffer)
polys = [polys[i] for i in I]
facecolors = [facecolors[i] for i in I]
edgecolors = [edgecolors[i] for i in I]
linewidths = [linewidths[i] for i in I]
antialiased = [antialiased[i] for i in I]
# Display
collection = PolyCollection(
polys,
linewidth=linewidths,
antialiased=antialiased,
facecolors=facecolors,
edgecolors=edgecolors,
)
ax.add_collection(collection) | null |
155,019 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.collections import PolyCollection
def axis(ax, camera, ticks=True):
"""
Draw three dimension axis with ticks and tick labels.
Parameters:
-----------
ax : matplotlib.axes instance
The regulmat axes where to draw
camera : 4x4 numpy array
A transformation matrix in homogenous coordinates (4x4)
ticks : bool
Whether to draw tick and tick labels
Note:
-----
The axis is drawn inside the unit cube centered on the origin:
- XZ lies on the plane Y = -0.5
- XY lies on the plane Z = -0.5
- YZ lies on the plane X = +0.5
- xticks goes from (-0.5, -0.5, +0.5) to (+0.5, -0.5, +0.5)
- zticks goes from (-0.5, -0.5, -0.5) to (-0.5, -0.5, +0.5)
- yticks goes from (-0.5, -0.5, -0.5) to (-0.5, +0.5, -0.5)
"""
# Mandatory settings for matplotlib axes
# --------------------------------------
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
# Parameters
# ---------------------------------
axis_linewidth = 1.00
grid_linewidth = 0.50
ticks_linewidth = 0.75
grid_color = "0.5"
axis_color = "0.0"
ticks_color = "0.0"
ticks_length = 0.025
ticks_pad = 0.05
# ticks and ticklabels
nx = 11
xticks = np.linspace(-0.5, +0.5, nx, endpoint=True)
xticklabels = ["%.1f" % x for x in xticks]
ny = 11
yticks = np.linspace(-0.5, +0.5, ny, endpoint=True)
yticklabels = ["%.1f" % y for y in yticks]
nz = 11
zticks = np.linspace(-0.5, +0.5, nz, endpoint=True)
zticklabels = ["%.1f" % z for z in zticks]
colors = []
segments = []
linewidths = []
# XZ axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 0, 1]
X2 = X1 + [0, 0, ticks_length]
X3 = X2 + [0, 0, ticks_pad]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
X2 = glm.transform(X2, camera)[..., :2]
X3 = glm.transform(X3, camera)[..., :2]
Z0 = np.linspace([0, 0, 0], [0, 0, 1], nz) - 0.5
Z1 = Z0 + [1, 0, 0]
Z2 = Z0 - [ticks_length, 0, 0]
Z3 = Z2 - [ticks_pad, 0, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Z2 = glm.transform(Z2, camera)[..., :2]
Z3 = glm.transform(Z3, camera)[..., :2]
for p0, p1, p2, p3, label in zip(X0, X1, X2, X3, xticklabels):
# grid line
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# tick
segments.append([p1, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
for p0, p1, p2, p3, label in zip(Z0, Z1, Z2, Z3, zticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# XY axis
# ---------------------------------
X0 = np.linspace([0, 0, 0], [1, 0, 0], nx) - 0.5
X1 = X0 + [0, 1, 0]
X0 = glm.transform(X0, camera)[..., :2]
X1 = glm.transform(X1, camera)[..., :2]
Y0 = np.linspace([0, 0, 0], [0, 1, 0], ny) - 0.5
Y1 = Y0 + [1, 0, 0]
Y2 = Y0 - [ticks_length, 0, 0]
Y3 = Y2 - [ticks_pad, 0, 0]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
Y2 = glm.transform(Y2, camera)[..., :2]
Y3 = glm.transform(Y3, camera)[..., :2]
for p0, p1 in zip(X0, X1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1, p2, p3, label in zip(Y0, Y1, Y2, Y3, yticklabels):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
if not ticks:
continue
# ticks
segments.append([p0, p2])
linewidths.append(ticks_linewidth)
colors.append(ticks_color)
# label
ax.text(p3[0], p3[1], label, ha="center", va="center", size="x-small")
# axis border
segments.append([X0[0], X0[-1], X1[-1], X1[0], X0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# ZY axis
# ---------------------------------
Z0 = np.linspace([1, 0, 0], [1, 0, 1], nx) - 0.5
Z1 = Z0 + [0, 1, 0]
Z0 = glm.transform(Z0, camera)[..., :2]
Z1 = glm.transform(Z1, camera)[..., :2]
Y0 = np.linspace([1, 0, 0], [1, 1, 0], ny) - 0.5
Y1 = Y0 + [0, 0, 1]
Y0 = glm.transform(Y0, camera)[..., :2]
Y1 = glm.transform(Y1, camera)[..., :2]
for p0, p1 in zip(Z0, Z1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
for p0, p1 in zip(Y0, Y1):
# grid lines
segments.append([p0, p1])
linewidths.append(grid_linewidth)
colors.append(grid_color)
# axis border
segments.append([Y0[0], Y0[-1], Y1[-1], Y1[0], Y0[0]])
linewidths.append(axis_linewidth)
colors.append(axis_color)
# Actual rendering
collection = PolyCollection(
segments,
closed=False,
clip_on=False,
linewidths=linewidths,
facecolors="None",
edgecolor=colors,
)
ax.add_collection(collection)
def bar(
ax,
camera,
Y,
facecolor="white",
edgecolor="black",
facecolors=None,
edgecolors=None,
linewidth=0.5,
shading=(1.00, 1.00, 1.00, 0.75, 0.50, 1.00),
):
# Mandatory settings for matplotlib axes
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
ax.axis("off")
# Facecolor
if facecolors is None:
facecolors = np.zeros((Y.shape[0], Y.shape[1], 3))
facecolors[...] = mpl.colors.to_rgb(facecolor)
facecolors[...] = facecolors[..., :3]
# Facecolor
if edgecolors is None:
edgecolors = np.zeros((Y.shape[0], Y.shape[1], 3))
edgecolors[...] = mpl.colors.to_rgb(edgecolor)
edgecolors[...] = edgecolors[..., :3]
# Here we compute the eight 3D vertices necessary to render a bar
shape = Y.shape
dx, dz = 0.5 / shape[0], 0.5 / shape[1]
X, Z = np.meshgrid(
np.linspace(-0.5 + dx, 0.5 - dx, shape[0]),
np.linspace(-0.5 + dz, 0.5 - dz, shape[1]),
)
P = np.c_[X.ravel(), np.zeros(X.size), Z.ravel()]
P = P.reshape(shape[0], shape[1], 3)
dx = np.array([dx, 0, 0])
dz = np.array([0, 0, dz])
dy = np.zeros((shape[0], shape[1], 3))
V = np.zeros((8, shape[0], shape[1], 3))
dy[..., 1] = -0.5
V[0] = P + dx - dz + dy
V[1] = P - dx - dz + dy
V[2] = P + dx + dz + dy
V[3] = P - dx + dz + dy
dy[..., 1] = -0.5 + Y
V[4] = P + dx - dz + dy
V[5] = P - dx - dz + dy
V[6] = P + dx + dz + dy
V[7] = P - dx + dz + dy
# Transformation of the vertices in 2D + z
T = glm.transform(V, camera)
V = T[:, :2].reshape(8, shape[0], shape[1], 2)
Z = -T[:, 2].reshape(8 * shape[0] * shape[1])
# Normalization of the z value such that we can manipulate zbar / zface
# Drawback is that it cannot be sorted anymore with other 3d objects
Z = glm.rescale(Z, 0, 1)
# Building of individual bars (without bottom face)
# and a new z buffer that is a combination of the bar and face mean z
faces, colors, zbuffer = [], [], []
indices = (
[4, 5, 7, 6], # +Y
[0, 1, 3, 2], # -Y
[0, 1, 5, 4], # +X
[1, 3, 7, 5], # -X
[2, 3, 7, 6], # -Z
[0, 2, 6, 4],
) # +Z
FC = np.zeros((shape[0], shape[1], len(indices), 3))
EC = np.zeros((shape[0], shape[1], len(indices), 3))
F = np.zeros((shape[0], shape[1], len(indices), 4, 2))
Z_ = np.zeros((shape[0], shape[1], len(indices)))
# This could probably be vectorized but it might be tricky
for i in range(shape[0]):
for j in range(shape[1]):
index = np.arange(8) * shape[0] * shape[1] + i * shape[1] + j
zbar = 1 * Z[index].mean()
for k, ((v0, v1, v2, v3), shade) in enumerate(zip(indices, shading)):
zface = (Z[index[v0]] + Z[index[v1]] + Z[index[v2]] + Z[index[v3]]) / 4
F[i, j, k] = V[v0, i, j], V[v1, i, j], V[v2, i, j], V[v3, i, j]
Z_[i, j, k] = 10 * zbar + zface
FC[i, j, k] = facecolors[i, j] * shade
EC[i, j, k] = edgecolors[i, j]
# Final reshape for sorting quads
Z = Z_.reshape(shape[0] * shape[1] * len(indices))
F = F.reshape(shape[0] * shape[1] * len(indices), 4, 2)
FC = FC.reshape(shape[0] * shape[1] * len(indices), 3)
EC = EC.reshape(shape[0] * shape[1] * len(indices), 3)
I = np.argsort(Z)
collection = PolyCollection(
F[I], linewidth=0.25, facecolors=FC[I], edgecolors=EC[I]
)
ax.add_collection(collection) | null |
155,020 | import glm
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.textpath import TextPath
from matplotlib.patches import PathPatch
from matplotlib.collections import PolyCollection
def contour(ax, camera, Y, n_levels=32):
n = Y.shape[0]
T = np.linspace(-0.5, +0.5, n)
X, Z = np.meshgrid(T, T)
C = ax.contour(X, Z, Y, n_levels)
cmap = plt.get_cmap("magma")
ymin, ymax = Y.min(), Y.max()
norm = mpl.colors.Normalize(vmin=2 * ymin, vmax=ymax)
dy = 0.99 * (ymax - ymin) / n_levels
segments = []
facecolors = []
edgecolors = []
closed = []
antialiased = []
epsilon = 0.0025
for level, collection in zip(C.levels, C.collections):
local_segments = []
local_zbuffer = []
local_antialiased = []
local_edgecolors = []
local_facecolors = []
local_closed = []
# Collect and transform all paths
paths = []
for path in collection.get_paths():
V = np.array(path.vertices)
V = np.c_[V[:, 0], level * np.ones(len(path)), V[:, 1]]
V0 = V
V1 = V0 - [0, dy, 0]
T0 = glm.transform(V0, camera)
T1 = glm.transform(V1, camera)
V0, Z0 = T0[:, :2], T0[:, 2]
V1, Z1 = T1[:, :2], T1[:, 2]
paths.append([V, V0, Z0, V1, Z1])
for (V, V0, Z0, V1, Z1) in paths:
for i in range(len(V0) - 1):
local_segments.append([V0[i], V0[i + 1], V1[i + 1], V1[i]])
local_zbuffer.append(-(Z0[i] + Z0[i + 1] + Z1[i + 1] + Z1[i]) / 4)
local_antialiased.append(False)
local_edgecolors.append("none")
facecolor = np.array(cmap(norm(level))[:3])
local_facecolors.append(0.75 * facecolor)
local_closed.append(True)
local_segments.append([V1[i + 1], V1[i]])
local_zbuffer.append(-(Z1[i + 1] + Z1[i]) / 2 + epsilon)
local_antialiased.append(True)
facecolor = np.array(cmap(norm(level))[:3])
local_edgecolors.append(facecolor * 0.25)
local_facecolors.append("none")
local_closed.append(False)
if ((V[0] - V[-1]) ** 2).sum() > 0.00001:
local_segments.append([V0[i + 1], V0[i]])
local_zbuffer.append(-(Z0[i + 1] + Z0[i]) / 2 + epsilon)
local_antialiased.append(True)
facecolor = np.array(cmap(norm(level))[:3])
local_edgecolors.append(facecolor * 0.25)
local_facecolors.append("none")
local_closed.append(False)
I = np.argsort(local_zbuffer)
local_segments = [local_segments[i] for i in I]
local_facecolors = [local_facecolors[i] for i in I]
local_edgecolors = [local_edgecolors[i] for i in I]
local_closed = [local_closed[i] for i in I]
local_antialiased = [local_antialiased[i] for i in I]
segments.extend(local_segments)
facecolors.extend(local_facecolors)
edgecolors.extend(local_edgecolors)
closed.extend(local_closed)
antialiased.extend(local_antialiased)
for (V, V0, Z0, V1, Z1) in paths:
if ((V[0] - V[-1]) ** 2).sum() < 0.00001:
segments.append(V0)
antialiased.append(True)
facecolor = cmap(norm(level))[:3]
facecolors.append(facecolor)
edgecolors.append("black")
closed.append(True)
collection.remove()
collection = PolyCollection(
segments,
linewidth=0.5,
antialiased=antialiased,
closed=closed,
facecolors=facecolors,
edgecolors=edgecolors,
)
ax.add_collection(collection) | null |
155,021 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
np.random.seed(123)
def lighten_color(color, amount=0.66):
import matplotlib.colors as mc
import colorsys
try:
c = mc.cnames[color]
except:
c = color
c = np.array(colorsys.rgb_to_hls(*mc.to_rgb(c)))
return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2]) | null |
155,023 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
x = subplot(rows, cols, 9, ""
The provided code snippet includes necessary dependencies for implementing the `rectangle` function. Write a Python function `def rectangle(center, size)` to solve the following problem:
Regular rectangle path
Here is the function:
def rectangle(center, size):
""" Regular rectangle path """
(x, y), (w, h) = center, size
vertices = np.array([(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)])
codes = np.array(
[
mpath.Path.MOVETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
mpath.Path.LINETO,
]
)
return vertices, codes | Regular rectangle path |
155,024 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
The provided code snippet includes necessary dependencies for implementing the `patch` function. Write a Python function `def patch( ax, path, facecolor="0.9", edgecolor="black", linewidth=0, linestyle="-", antialiased=True, clip=None, )` to solve the following problem:
Build a patch with potential clipping path
Here is the function:
def patch(
ax,
path,
facecolor="0.9",
edgecolor="black",
linewidth=0,
linestyle="-",
antialiased=True,
clip=None,
):
""" Build a patch with potential clipping path """
patch = mpatches.PathPatch(
path,
antialiased=antialiased,
linewidth=linewidth,
linestyle=linestyle,
facecolor=facecolor,
edgecolor=edgecolor,
)
if clip:
# If the path is not drawn, clipping doesn't work
clip_patch = mpatches.PathPatch(
clip, linewidth=0, facecolor="None", edgecolor="None"
)
ax.add_patch(clip_patch)
patch.set_clip_path(clip_patch)
ax.add_patch(patch) | Build a patch with potential clipping path |
155,025 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
ax = subplot(rows, cols, 1, "No blend")
ax = subplot(rows, cols, 2, "Default blend")
ax = subplot(rows, cols, 3, "Multiply")
ax = subplot(rows, cols, 4, "Screen")
ax = subplot(rows, cols, 5, "Darken")
ax = subplot(rows, cols, 6, "Lighten")
ax = subplot(rows, cols, 7, "Color dodge")
ax = subplot(rows, cols, 8, "Color burn")
plt.tight_layout()
plt.show()
The provided code snippet includes necessary dependencies for implementing the `subplot` function. Write a Python function `def subplot(cols, rows, index, title)` to solve the following problem:
Shortcut to subplot to factorize options
Here is the function:
def subplot(cols, rows, index, title):
""" Shortcut to subplot to factorize options"""
ax = plt.subplot(cols, rows, index, aspect=1)
# ax.text(-1.25, 0.75, "A", size="large", ha="center", va="center")
# ax.text(+1.25, 0.75, "B", size="large", ha="center", va="center")
ax.set_title(title, weight="bold")
ax.set_xlim(-1.5, +1.5), ax.set_xticks([])
ax.set_ylim(-1, +1), ax.set_yticks([])
return ax | Shortcut to subplot to factorize options |
155,026 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
xA, xB = np.array(A), np.array(B)
aA, aB = xA[3], xB[3]
aR = aA + aB * (1 - aA)
xaA, xaB = aA * xA, aB * xB
xR = 1.0 / aR * ((1 - aB) * xaA + (1 - aA) * xaB + aA * aB * f(xA, xB))
return xR[:3]
x = subplot(rows, cols, 9, ""
def blend_multiply(A, B):
return blend(A, B, lambda x, y: x * y) | null |
155,027 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
xA, xB = np.array(A), np.array(B)
aA, aB = xA[3], xB[3]
aR = aA + aB * (1 - aA)
xaA, xaB = aA * xA, aB * xB
xR = 1.0 / aR * ((1 - aB) * xaA + (1 - aA) * xaB + aA * aB * f(xA, xB))
return xR[:3]
x = subplot(rows, cols, 9, ""
def blend_screen(A, B):
return blend(A, B, lambda x, y: x + y - x * y) | null |
155,028 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
xA, xB = np.array(A), np.array(B)
aA, aB = xA[3], xB[3]
aR = aA + aB * (1 - aA)
xaA, xaB = aA * xA, aB * xB
xR = 1.0 / aR * ((1 - aB) * xaA + (1 - aA) * xaB + aA * aB * f(xA, xB))
return xR[:3]
x = subplot(rows, cols, 9, ""
def blend_darken(A, B):
return blend(A, B, lambda x, y: np.minimum(x, y)) | null |
155,029 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
x = subplot(rows, cols, 9, ""
def blend_lighten(A, B):
return blend(A, B, lambda x, y: np.minimum(x, y)) | null |
155,030 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
x = subplot(rows, cols, 9, ""
def blend_color_dodge(A, B):
return blend(A, B, lambda x, y: np.where(A < 1, np.minimum(1, B / (1 - A)), 1)) | null |
155,031 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
def blend(A, B, f):
x = subplot(rows, cols, 9, ""
def blend_color_burn(A, B):
return blend(A, B, lambda x, y: np.where(A > 0, 1 - np.minimum(1, (1 - B) / A), 0)) | null |
155,032 | import scipy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvas
from matplotlib.patheffects import Stroke, Normal
from scipy.ndimage import gaussian_filter
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-(x ** 2) - y ** 2) | null |
155,033 | import scipy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvas
from matplotlib.patheffects import Stroke, Normal
from scipy.ndimage import gaussian_filter
levels = np.linspace(Z.min(), Z.max(), n, endpoint=True)
fig = plt.figure(figsize=(8, 8), dpi=100)
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(-2.9, 2.9)
ax.set_ylim(-2.9, 2.9)
The provided code snippet includes necessary dependencies for implementing the `drop_shadow` function. Write a Python function `def drop_shadow(Z, l0, l1, sigma=5, alpha=0.5)` to solve the following problem:
Compute the drop shadow for a contour between l0 and l1. This works by first: 1. render the contour in black using an offline image 2. blue the contour using a Guassian filter 3. set the alpha channel accordingly
Here is the function:
def drop_shadow(Z, l0, l1, sigma=5, alpha=0.5):
"""Compute the drop shadow for a contour between l0 and l1.
This works by first:
1. render the contour in black using an offline image
2. blue the contour using a Guassian filter
3. set the alpha channel accordingly
"""
fig = Figure(figsize=(5, 5))
canvas = FigureCanvas(fig)
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.contourf(
Z,
vmin=Z.min(),
vmax=Z.max(),
levels=[l0, l1],
origin="lower",
colors="black",
extent=[-1, 1, -1, 1],
)
ax.set_xlim(-1, 1), ax.set_ylim(-1, 1)
canvas.draw()
A = np.array(canvas.renderer.buffer_rgba())[:, :, 0]
del fig
A = gaussian_filter(A, sigma)
A = (A - A.min()) / (A.max() - A.min())
I = np.zeros((A.shape[0], A.shape[1], 4))
I[:, :, 3] = (1 - A) * alpha
return I | Compute the drop shadow for a contour between l0 and l1. This works by first: 1. render the contour in black using an offline image 2. blue the contour using a Guassian filter 3. set the alpha channel accordingly |
155,034 | import numpy as np
import scipy.spatial
import matplotlib.pyplot as plt
import matplotlib.path as mpath
from shapely.geometry import Polygon
from matplotlib.collections import PolyCollection
from math import sqrt, ceil, floor, pi, cos, sin
def bounded_voronoi(points):
"""
Reconstruct infinite voronoi regions in a 2D diagram to finite regions.
Parameters
----------
vor : Voronoi
Input diagram
Returns
-------
regions : list of tuples
Indices of vertices in each revised Voronoi regions.
vertices : list of tuples
Coordinates for revised Voronoi vertices. Same as coordinates
of input vertices, with 'points at infinity' appended to the
end.
"""
vor = scipy.spatial.Voronoi(points)
new_regions = []
new_vertices = vor.vertices.tolist()
center = vor.points.mean(axis=0)
radius = vor.points.ptp().max() * 2
# Construct a map containing all ridges for a given point
all_ridges = {}
for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
all_ridges.setdefault(p1, []).append((p2, v1, v2))
all_ridges.setdefault(p2, []).append((p1, v1, v2))
# Reconstruct infinite regions
for p1, region in enumerate(vor.point_region):
vertices = vor.regions[region]
if all(v >= 0 for v in vertices):
# finite region
new_regions.append(vertices)
continue
# reconstruct a non-finite region
ridges = all_ridges[p1]
new_region = [v for v in vertices if v >= 0]
for p2, v1, v2 in ridges:
if v2 < 0:
v1, v2 = v2, v1
if v1 >= 0:
# finite ridge: already in the region
continue
# Compute the missing endpoint of an infinite ridge
t = vor.points[p2] - vor.points[p1] # tangent
t /= np.linalg.norm(t)
n = np.array([-t[1], t[0]]) # normal
midpoint = vor.points[[p1, p2]].mean(axis=0)
direction = np.sign(np.dot(midpoint - center, n)) * n
far_point = vor.vertices[v2] + direction * radius
new_region.append(len(new_vertices))
new_vertices.append(far_point.tolist())
# sort region counterclockwise
vs = np.asarray([new_vertices[v] for v in new_region])
c = vs.mean(axis=0)
angles = np.arctan2(vs[:, 1] - c[1], vs[:, 0] - c[0])
new_region = np.array(new_region)[np.argsort(angles)]
# finish
new_regions.append(new_region.tolist())
return new_regions, np.asarray(new_vertices)
def poly_random_points(V, n=10):
path = mpath.Path(V)
xmin, xmax = V[:, 0].min(), V[:, 0].max()
ymin, ymax = V[:, 1].min(), V[:, 1].max()
xscale, yscale = xmax - xmin, ymax - ymin
if xscale > yscale:
xscale, yscale = 1, yscale / xscale
else:
xscale, yscale = xscale / yscale, 1
radius = 0.85 * np.sqrt(2 * xscale * yscale / (n * np.pi))
points = blue_noise((xscale, yscale), radius)
points = [xmin, ymin] + points * [xmax - xmin, ymax - ymin]
inside = path.contains_points(points)
P = points[inside]
if len(P) < 5:
return poly_random_points_safe(V, n)
np.random.shuffle(P)
return P[:n]
np.random.seed(12345)
cells = voronoi(V, 11, level=0, maxlevel=5)
zorder = [cell[-1] for cell in cells]
cells = [cells[i] for i in np.argsort(zorder)]
linewidths = [cell[1] for cell in cells]
edgecolors = [cell[2] for cell in cells]
def voronoi(V, npoints, level, maxlevel, color=None):
if level == maxlevel:
return []
linewidths = [1.50, 1.00, 0.75, 0.50, 0.25, 0.10]
edgecolors = [
(0, 0, 0, 1.00),
(0, 0, 0, 0.50),
(0, 0, 0, 0.25),
(0, 0, 0, 0.10),
(0, 0, 0, 0.10),
(0, 0, 0, 0.10),
]
if level == 1:
color = np.random.uniform(0, 1, 4)
color[3] = 0.5
points = poly_random_points(V, npoints - level)
regions, vertices = bounded_voronoi(points)
clip = Polygon(V)
cells = []
for region in regions:
polygon = Polygon(vertices[region]).intersection(clip)
polygon = np.array([point for point in polygon.exterior.coords])
linewidth = linewidths[level]
edgecolor = edgecolors[level]
facecolor = "none"
if level > 1:
alpha = color[3] + (1 / (level + 1)) * 0.25 * np.random.uniform(-1, 0.5)
color = color[0], color[1], color[2], min(max(alpha, 0.1), 1)
if level == maxlevel - 1:
facecolor = color
zorder = -level
cells.append((polygon, linewidth, edgecolor, facecolor, zorder))
cells.extend(voronoi(polygon, npoints, level + 1, maxlevel, color))
return cells | null |
155,035 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from shapely.geometry import box, Polygon
from scipy.ndimage import gaussian_filter1d
from matplotlib.collections import PolyCollection
from matplotlib.transforms import Affine2D
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from mpl_toolkits.mplot3d import Axes3D, art3d
from matplotlib.font_manager import FontProperties
def text3d(ax, xyz, s, zdir="z", size=0.1, angle=0, **kwargs):
x, y, z = xyz
if zdir == "y":
xy, z = (x, z), y
elif zdir == "x":
xy, z = (y, z), x
else:
xy, z = (x, y), z
path = TextPath((0, 0), s, size=size, prop=FontProperties(family="Roboto"))
V = path.vertices
V[:, 0] -= (V[:, 0].max() - V[:, 0].min()) / 2
trans = Affine2D().rotate(angle).translate(xy[0], xy[1])
path = PathPatch(trans.transform_path(path), **kwargs)
ax.add_patch(path)
art3d.pathpatch_2d_to_3d(path, z=z, zdir=zdir) | null |
155,036 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from shapely.geometry import box, Polygon
from scipy.ndimage import gaussian_filter1d
from matplotlib.collections import PolyCollection
from matplotlib.transforms import Affine2D
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from mpl_toolkits.mplot3d import Axes3D, art3d
from matplotlib.font_manager import FontProperties
np.random.seed(1)
def random_curve(n=100):
Y = np.random.uniform(0, 1, n)
Y = gaussian_filter1d(Y, 1)
X = np.linspace(-1, 1, len(Y))
Y *= np.exp(-2 * (X * X))
return Y | null |
155,037 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from shapely.geometry import box, Polygon
from scipy.ndimage import gaussian_filter1d
from matplotlib.collections import PolyCollection
from matplotlib.transforms import Affine2D
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from mpl_toolkits.mplot3d import Axes3D, art3d
from matplotlib.font_manager import FontProperties
np.random.seed(1)
plt.tight_layout()
plt.savefig("../../figures/showcases/waterfall-3d.pdf")
plt.show()
def cmap_plot(Y, ymin=0, ymax=1, n=50, cmap="magma", y0=0):
X = np.linspace(0.3, 0.7, len(Y))
Y = gaussian_filter1d(Y, 2)
verts = []
colors = []
P = Polygon([(X[0], 0), *zip(X, Y), (X[-1], 0)])
dy = (ymax - ymin) / n
cmap = plt.cm.get_cmap(cmap)
cnorm = matplotlib.colors.Normalize(vmin=ymin, vmax=ymax)
for y in np.arange(Y.min(), Y.max(), dy):
B = box(0, y, 10, y + dy)
I = P.intersection(B)
if hasattr(I, "geoms"):
for p in I.geoms:
V = np.array(p.exterior.coords)
V[:, 1] += y0
verts.append(V)
colors.append(cmap(cnorm(y)))
else:
if I.exterior.coords:
V = np.array(I.exterior.coords)
V[:, 1] += y0
verts.append(V)
colors.append(cmap(cnorm(y)))
return verts, colors | null |
155,038 | import numpy as np
from matplotlib import colors
import matplotlib.pyplot as plt
Z, N = mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon)
with np.errstate(invalid="ignore"):
M = np.nan_to_num(N + 1 - np.log(np.log(abs(Z))) / np.log(2) + log_horizon)
def mandelbrot_set(xmin, xmax, ymin, ymax, xn, yn, maxiter, horizon=2.0):
X = np.linspace(xmin, xmax, xn, dtype=np.float32)
Y = np.linspace(ymin, ymax, yn, dtype=np.float32)
C = X + Y[:, None] * 1j
N = np.zeros(C.shape, dtype=int)
Z = np.zeros(C.shape, np.complex64)
for n in range(maxiter):
I = np.less(abs(Z), horizon)
N[I] = n
Z[I] = Z[I] ** 2 + C[I]
N[N == maxiter - 1] = 0
return Z, N | null |
155,039 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patheffects import Stroke, Normal
def normalize(Z):
zmin, zmax = Z.min(), Z.max()
return (Z - zmin) / (zmax - zmin) | null |
155,040 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
X = np.exp(-5 * np.linspace(-1, 1, n, endpoint=True) ** 2)
def line(A, B, thickness=0.005, n=100):
T = (B - A) / np.linalg.norm(B - A)
O = np.array([-T[1], T[0]])
P0 = A + thickness * O
P1 = B + thickness * O
P2 = B - thickness * O
P3 = A - thickness * O
P = np.concatenate(
[
np.linspace(P0, P1, n),
np.linspace(P1, P2, n // 10),
np.linspace(P2, P3, n),
np.linspace(P3, P0, n // 10),
]
)
X, Y = P[:, 0], P[:, 1]
return np.dstack([np.exp(X) * np.cos(Y), np.exp(X) * np.sin(Y)]).squeeze() | null |
155,041 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, writers
from matplotlib.collections import LineCollection
import types
from matplotlib.backend_bases import GraphicsContextBase, RendererBase
class GC(GraphicsContextBase):
def __init__(self):
super().__init__()
self._capstyle = "round"
def custom_new_gc(self):
return GC() | null |
155,042 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
def line(A, B, thickness=0.005, n=100):
T = (B - A) / np.linalg.norm(B - A)
O = np.array([-T[1], T[0]])
P0 = A + thickness * O
P1 = B + thickness * O
P2 = B - thickness * O
P3 = A - thickness * O
P = np.concatenate(
[
np.linspace(P0, P1, n),
np.linspace(P1, P2, n // 10),
np.linspace(P2, P3, n),
np.linspace(P3, P0, n // 10),
]
)
X, Y = P[:, 0], P[:, 1]
return np.dstack([np.exp(X) * np.cos(Y), np.exp(X) * np.sin(Y)]).squeeze() | null |
155,043 | import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi
from math import sqrt, ceil, floor, pi, cos, sin
from matplotlib.collections import PolyCollection
The provided code snippet includes necessary dependencies for implementing the `blue_noise` function. Write a Python function `def blue_noise(shape, radius, k=30, seed=None)` to solve the following problem:
Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
Here is the function:
def blue_noise(shape, radius, k=30, seed=None):
"""
Generate blue noise over a two-dimensional rectangle of size (width,height)
Parameters
----------
shape : tuple
Two-dimensional domain (width x height)
radius : float
Minimum distance between samples
k : int, optional
Limit of samples to choose before rejection (typically k = 30)
seed : int, optional
If provided, this will set the random seed before generating noise,
for valid pseudo-random comparisons.
References
----------
.. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson,
Siggraph, 2007. :DOI:`10.1145/1278780.1278807`
"""
def sqdist(a, b):
""" Squared Euclidean distance """
dx, dy = a[0] - b[0], a[1] - b[1]
return dx * dx + dy * dy
def grid_coords(p):
""" Return index of cell grid corresponding to p """
return int(floor(p[0] / cellsize)), int(floor(p[1] / cellsize))
def fits(p, radius):
""" Check whether p can be added to the queue """
radius2 = radius * radius
gx, gy = grid_coords(p)
for x in range(max(gx - 2, 0), min(gx + 3, grid_width)):
for y in range(max(gy - 2, 0), min(gy + 3, grid_height)):
g = grid[x + y * grid_width]
if g is None:
continue
if sqdist(p, g) <= radius2:
return False
return True
# When given a seed, we use a private random generator in order to not
# disturb the default global random generator
if seed is not None:
from numpy.random.mtrand import RandomState
rng = RandomState(seed=seed)
else:
rng = np.random
width, height = shape
cellsize = radius / sqrt(2)
grid_width = int(ceil(width / cellsize))
grid_height = int(ceil(height / cellsize))
grid = [None] * (grid_width * grid_height)
p = rng.uniform(0, shape, 2)
queue = [p]
grid_x, grid_y = grid_coords(p)
grid[grid_x + grid_y * grid_width] = p
while queue:
qi = rng.randint(len(queue))
qx, qy = queue[qi]
queue[qi] = queue[-1]
queue.pop()
for _ in range(k):
theta = rng.uniform(0, 2 * pi)
r = radius * np.sqrt(rng.uniform(1, 4))
p = qx + r * cos(theta), qy + r * sin(theta)
if not (0 <= p[0] < width and 0 <= p[1] < height) or not fits(p, radius):
continue
queue.append(p)
gx, gy = grid_coords(p)
grid[gx + gy * grid_width] = p
return np.array([p for p in grid if p is not None]) | Generate blue noise over a two-dimensional rectangle of size (width,height) Parameters ---------- shape : tuple Two-dimensional domain (width x height) radius : float Minimum distance between samples k : int, optional Limit of samples to choose before rejection (typically k = 30) seed : int, optional If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. References ---------- .. [1] Fast Poisson Disk Sampling in Arbitrary Dimensions, Robert Bridson, Siggraph, 2007. :DOI:`10.1145/1278780.1278807` |
155,044 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
material = {
"red": {
0: "#ffebee",
1: "#ffcdd2",
2: "#ef9a9a",
3: "#e57373",
4: "#ef5350",
5: "#f44336",
6: "#e53935",
7: "#d32f2f",
8: "#c62828",
9: "#b71c1c",
},
"pink": {
0: "#fce4ec",
1: "#f8bbd0",
2: "#f48fb1",
3: "#f06292",
4: "#ec407a",
5: "#e91e63",
6: "#d81b60",
7: "#c2185b",
8: "#ad1457",
9: "#880e4f",
},
"purple": {
0: "#f3e5f5",
1: "#e1bee7",
2: "#ce93d8",
3: "#ba68c8",
4: "#ab47bc",
5: "#9c27b0",
6: "#8e24aa",
7: "#7b1fa2",
8: "#6a1b9a",
9: "#4a148c",
},
"deep purple": {
0: "#ede7f6",
1: "#d1c4e9",
2: "#b39ddb",
3: "#9575cd",
4: "#7e57c2",
5: "#673ab7",
6: "#5e35b1",
7: "#512da8",
8: "#4527a0",
9: "#311b92",
},
"indigo": {
0: "#e8eaf6",
1: "#c5cae9",
2: "#9fa8da",
3: "#7986cb",
4: "#5c6bc0",
5: "#3f51b5",
6: "#3949ab",
7: "#303f9f",
8: "#283593",
9: "#1a237e",
},
"blue": {
0: "#e3f2fd",
1: "#bbdefb",
2: "#90caf9",
3: "#64b5f6",
4: "#42a5f5",
5: "#2196f3",
6: "#1e88e5",
7: "#1976d2",
8: "#1565c0",
9: "#0d47a1",
},
"light blue": {
0: "#e1f5fe",
1: "#b3e5fc",
2: "#81d4fa",
3: "#4fc3f7",
4: "#29b6f6",
5: "#03a9f4",
6: "#039be5",
7: "#0288d1",
8: "#0277bd",
9: "#01579b",
},
"cyan": {
0: "#e0f7fa",
1: "#b2ebf2",
2: "#80deea",
3: "#4dd0e1",
4: "#26c6da",
5: "#00bcd4",
6: "#00acc1",
7: "#0097a7",
8: "#00838f",
9: "#006064",
},
"teal": {
0: "#e0f2f1",
1: "#b2dfdb",
2: "#80cbc4",
3: "#4db6ac",
4: "#26a69a",
5: "#009688",
6: "#00897b",
7: "#00796b",
8: "#00695c",
9: "#004d40",
},
"green": {
0: "#e8f5e9",
1: "#c8e6c9",
2: "#a5d6a7",
3: "#81c784",
4: "#66bb6a",
5: "#4caf50",
6: "#43a047",
7: "#388e3c",
8: "#2e7d32",
9: "#1b5e20",
},
"light green": {
0: "#f1f8e9",
1: "#dcedc8",
2: "#c5e1a5",
3: "#aed581",
4: "#9ccc65",
5: "#8bc34a",
6: "#7cb342",
7: "#689f38",
8: "#558b2f",
9: "#33691e",
},
"lime": {
0: "#f9fbe7",
1: "#f0f4c3",
2: "#e6ee9c",
3: "#dce775",
4: "#d4e157",
5: "#cddc39",
6: "#c0ca33",
7: "#afb42b",
8: "#9e9d24",
9: "#827717",
},
"yellow": {
0: "#fffde7",
1: "#fff9c4",
2: "#fff59d",
3: "#fff176",
4: "#ffee58",
5: "#ffeb3b",
6: "#fdd835",
7: "#fbc02d",
8: "#f9a825",
9: "#f57f17",
},
"amber": {
0: "#fff8e1",
1: "#ffecb3",
2: "#ffe082",
3: "#ffd54f",
4: "#ffca28",
5: "#ffc107",
6: "#ffb300",
7: "#ffa000",
8: "#ff8f00",
9: "#ff6f00",
},
"orange": {
0: "#fff3e0",
1: "#ffe0b2",
2: "#ffcc80",
3: "#ffb74d",
4: "#ffa726",
5: "#ff9800",
6: "#fb8c00",
7: "#f57c00",
8: "#ef6c00",
9: "#e65100",
},
"deep orange": {
0: "#fbe9e7",
1: "#ffccbc",
2: "#ffab91",
3: "#ff8a65",
4: "#ff7043",
5: "#ff5722",
6: "#f4511e",
7: "#e64a19",
8: "#d84315",
9: "#bf360c",
},
"brown": {
0: "#efebe9",
1: "#d7ccc8",
2: "#bcaaa4",
3: "#a1887f",
4: "#8d6e63",
5: "#795548",
6: "#6d4c41",
7: "#5d4037",
8: "#4e342e",
9: "#3e2723",
},
"grey": {
0: "#fafafa",
1: "#f5f5f5",
2: "#eeeeee",
3: "#e0e0e0",
4: "#bdbdbd",
5: "#9e9e9e",
6: "#757575",
7: "#616161",
8: "#424242",
9: "#212121",
},
"blue grey": {
0: "#eceff1",
1: "#cfd8dc",
2: "#b0bec5",
3: "#90a4ae",
4: "#78909c",
5: "#607d8b",
6: "#546e7a",
7: "#455a64",
8: "#37474f",
9: "#263238",
},
}
np.random.seed(123)
ax = plt.subplot(1, 1, 1, frameon=False)
ax.axhline(50, 0.05, 1, color="0.5", linewidth=0.5, linestyle="--", zorder=-10)
ax.axhline(100, 0.05, 1, color="0.5", linewidth=0.5, linestyle="--", zorder=-10)
ax.set_xlim(-2, 6 * (n + 2) - 1.5)
ax.set_xticks([])
ax.set_ylim(0, 111)
ax.set_yticks([0, 50, 100])
ax.set_yticklabels(["0%", "50%", "100%"])
def bars(origin, color, n, index):
X = origin + np.arange(n)
H = 20 * np.random.uniform(1.0, 5.0, n)
H.sort()
ax.bar(
X,
H,
width=1.0,
align="edge",
color=[material[color][1 + 2 * i] for i in range(n)],
)
ax.plot([origin - 0.5, origin + n + 0.5], [0, 0], color="black", lw=2.5)
ax.text(origin + n / 2, -1, "Group " + index, va="top", ha="center") | null |
155,045 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.collections import PolyCollection
def flower(ax, n_branches=24, n_sections=4, lw=1):
R = np.linspace(0.1, 1.0, 25)
paths = []
facecolors = []
n_sections += 1
for i in range(n_branches):
for j in range(n_sections - 1):
R_, T_ = [], []
T = np.linspace(
i * 2 * np.pi / n_branches,
(i + n_sections / 2) * 2 * np.pi / n_branches,
len(R),
)
t = np.interp(
np.linspace(j + 1, j + 2, 20), np.linspace(0, n_sections, len(T)), T
)
r = np.interp(
np.linspace(j + 1, j + 2, 20), np.linspace(0, n_sections, len(R)), R
)
R_.extend(r[::1].tolist())
T_.extend(t[::1].tolist())
T = np.linspace(
(i + 1 + j + 1) * 2 * np.pi / n_branches,
(i + 1 + j + 1 - n_sections / 2) * 2 * np.pi / n_branches,
len(R),
)
t = np.interp(
np.linspace(j + 1, j + 2, 20), np.linspace(0, n_sections, len(T)), T
)
r = np.interp(
np.linspace(j + 1, j + 2, 20), np.linspace(0, n_sections, len(R)), R
)
R_.extend(r[::-1].tolist())
T_.extend(t[::-1].tolist())
T = np.linspace(
(i + 1) * 2 * np.pi / n_branches,
(i + 1 + n_sections / 2) * 2 * np.pi / n_branches,
len(R),
)
t = np.interp(
np.linspace(j, j + 1, 20), np.linspace(0, n_sections, len(T)), T
)
r = np.interp(
np.linspace(j, j + 1, 20), np.linspace(0, n_sections, len(R)), R
)
R_.extend(r[::-1].tolist())
T_.extend(t[::-1].tolist())
T = np.linspace(
(i + 1 + j) * 2 * np.pi / n_branches,
(i + 1 + j - n_sections / 2) * 2 * np.pi / n_branches,
len(R),
)
t = np.interp(
np.linspace(j, j + 1, 20), np.linspace(0, n_sections, len(T)), T
)
r = np.interp(
np.linspace(j, j + 1, 20), np.linspace(0, n_sections, len(R)), R
)
R_.extend(r[::1].tolist())
T_.extend(t[::1].tolist())
P = np.dstack([T_, R_]).squeeze()
paths.append(P)
h = i / n_branches
s = 0.5 + 0.5 * j / (n_sections - 1)
v = 1.00
facecolors.append(colors.hsv_to_rgb([h, s, v]))
collection = PolyCollection(
paths, linewidths=5.5 * lw, facecolors="None", edgecolors="black"
)
ax.add_collection(collection)
collection = PolyCollection(
paths, linewidths=4 * lw, facecolors="None", edgecolors="white"
)
ax.add_collection(collection)
ax.fill_between(np.linspace(0, 2 * np.pi, 100), 0.0, 0.5, facecolor="white")
collection = PolyCollection(
paths, linewidths=lw, facecolors=facecolors, edgecolors="white"
)
ax.add_collection(collection) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.