code
stringlengths 501
4.91M
| package
stringlengths 2
88
| path
stringlengths 11
291
| filename
stringlengths 4
197
| parsed_code
stringlengths 0
4.91M
| quality_prob
float64 0
0.99
| learning_prob
float64 0.02
1
|
---|---|---|---|---|---|---|
import functools
from ..transforms import convert, to_primitive
from ..validate import validate
def _callback_wrap(data, schema, transform, *args, **kwargs):
return transform(schema, data, *args, **kwargs)
class Machine:
"""A poor man's state machine."""
states = ("raw", "converted", "validated", "serialized")
transitions = (
{"trigger": "init", "to": "raw"},
{"trigger": "convert", "from": "raw", "to": "converted"},
{"trigger": "validate", "from": "converted", "to": "validated"},
{"trigger": "serialize", "from": "validated", "to": "serialized"},
)
callbacks = {
"convert": functools.partial(_callback_wrap, transform=convert, partial=True),
"validate": functools.partial(
_callback_wrap, transform=validate, convert=False, partial=False
),
"serialize": functools.partial(_callback_wrap, transform=to_primitive),
}
def __init__(self, data, *args):
self.state = self._transition(trigger="init")["to"]
self.data = data
self.args = args
def __getattr__(self, name):
return functools.partial(self.trigger, name)
def _transition(self, trigger=None, src_state=None, dst_state=None):
try:
return next(
self._transitions(
trigger=trigger, src_state=src_state, dst_state=dst_state
)
)
except StopIteration:
return None
def _transitions(self, trigger=None, src_state=None, dst_state=None):
def pred(d, key, var):
return d.get(key) == var if var is not None else True
return (
d
for d in self.transitions
if pred(d, "trigger", trigger)
and pred(d, "from", src_state)
and pred(d, "to", dst_state)
)
def trigger(self, trigger):
transition = self._transition(trigger=trigger, src_state=self.state)
if not transition:
raise AttributeError(trigger)
callback = self.callbacks.get(trigger)
self.data = callback(self.data, *self.args) if callback else self.data
self.state = transition["to"]
def can(self, state):
return bool(self._transition(src_state=self.state, dst_state=state))
def cannot(self, state):
return not self.can(state)
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/contrib/machine.py
|
machine.py
|
import functools
from ..transforms import convert, to_primitive
from ..validate import validate
def _callback_wrap(data, schema, transform, *args, **kwargs):
return transform(schema, data, *args, **kwargs)
class Machine:
"""A poor man's state machine."""
states = ("raw", "converted", "validated", "serialized")
transitions = (
{"trigger": "init", "to": "raw"},
{"trigger": "convert", "from": "raw", "to": "converted"},
{"trigger": "validate", "from": "converted", "to": "validated"},
{"trigger": "serialize", "from": "validated", "to": "serialized"},
)
callbacks = {
"convert": functools.partial(_callback_wrap, transform=convert, partial=True),
"validate": functools.partial(
_callback_wrap, transform=validate, convert=False, partial=False
),
"serialize": functools.partial(_callback_wrap, transform=to_primitive),
}
def __init__(self, data, *args):
self.state = self._transition(trigger="init")["to"]
self.data = data
self.args = args
def __getattr__(self, name):
return functools.partial(self.trigger, name)
def _transition(self, trigger=None, src_state=None, dst_state=None):
try:
return next(
self._transitions(
trigger=trigger, src_state=src_state, dst_state=dst_state
)
)
except StopIteration:
return None
def _transitions(self, trigger=None, src_state=None, dst_state=None):
def pred(d, key, var):
return d.get(key) == var if var is not None else True
return (
d
for d in self.transitions
if pred(d, "trigger", trigger)
and pred(d, "from", src_state)
and pred(d, "to", dst_state)
)
def trigger(self, trigger):
transition = self._transition(trigger=trigger, src_state=self.state)
if not transition:
raise AttributeError(trigger)
callback = self.callbacks.get(trigger)
self.data = callback(self.data, *self.args) if callback else self.data
self.state = transition["to"]
def can(self, state):
return bool(self._transition(src_state=self.state, dst_state=state))
def cannot(self, state):
return not self.can(state)
| 0.68437 | 0.328987 |
from enum import Enum
from ..exceptions import ConversionError
from ..translator import _
from ..types import BaseType
class EnumType(BaseType):
"""A field type allowing to use native enums as values.
Restricts values to enum members and (optionally) enum values.
`use_values` - if set to True allows do assign enumerated values to the field.
>>> import enum
>>> class E(enum.Enum):
... A = 1
... B = 2
>>> from schematics import Model
>>> class AModel(Model):
... foo = EnumType(E)
>>> a = AModel()
>>> a.foo = E.A
>>> a.foo.value == 1
"""
MESSAGES = {
"convert": _("Couldn't interpret '{0}' as member of {1}."),
}
def __init__(self, enum, use_values=False, **kwargs):
"""
:param enum: Enum class to which restrict values assigned to the field.
:param use_values: If true, also values of the enum (right-hand side) can be assigned here.
Other args are passed to superclass.
"""
self._enum_class = enum
self._use_values = use_values
super().__init__(**kwargs)
def to_native(self, value, context=None):
if isinstance(value, self._enum_class):
return value
by_name = self._find_by_name(value)
if by_name:
return by_name
by_value = self._find_by_value(value)
if by_value:
return by_value
raise ConversionError(self.messages["convert"].format(value, self._enum_class))
def _find_by_name(self, value):
if isinstance(value, str):
try:
return self._enum_class[value]
except KeyError:
pass
return None
def _find_by_value(self, value):
if not self._use_values:
return None
for member in self._enum_class:
if member.value == value:
return member
return None
def to_primitive(self, value, context=None):
if isinstance(value, Enum):
if self._use_values:
return value.value
return value.name
return str(value)
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/contrib/enum_type.py
|
enum_type.py
|
from enum import Enum
from ..exceptions import ConversionError
from ..translator import _
from ..types import BaseType
class EnumType(BaseType):
"""A field type allowing to use native enums as values.
Restricts values to enum members and (optionally) enum values.
`use_values` - if set to True allows do assign enumerated values to the field.
>>> import enum
>>> class E(enum.Enum):
... A = 1
... B = 2
>>> from schematics import Model
>>> class AModel(Model):
... foo = EnumType(E)
>>> a = AModel()
>>> a.foo = E.A
>>> a.foo.value == 1
"""
MESSAGES = {
"convert": _("Couldn't interpret '{0}' as member of {1}."),
}
def __init__(self, enum, use_values=False, **kwargs):
"""
:param enum: Enum class to which restrict values assigned to the field.
:param use_values: If true, also values of the enum (right-hand side) can be assigned here.
Other args are passed to superclass.
"""
self._enum_class = enum
self._use_values = use_values
super().__init__(**kwargs)
def to_native(self, value, context=None):
if isinstance(value, self._enum_class):
return value
by_name = self._find_by_name(value)
if by_name:
return by_name
by_value = self._find_by_value(value)
if by_value:
return by_value
raise ConversionError(self.messages["convert"].format(value, self._enum_class))
def _find_by_name(self, value):
if isinstance(value, str):
try:
return self._enum_class[value]
except KeyError:
pass
return None
def _find_by_value(self, value):
if not self._use_values:
return None
for member in self._enum_class:
if member.value == value:
return member
return None
def to_primitive(self, value, context=None):
if isinstance(value, Enum):
if self._use_values:
return value.value
return value.name
return str(value)
| 0.838845 | 0.330201 |
import itertools
from collections.abc import Iterable, Mapping, Sequence
from typing import Type, TypeVar
from ..common import DROP, NONEMPTY, NOT_NONE
from ..exceptions import BaseError, CompoundError, ConversionError, ValidationError
from ..transforms import (
convert,
export_loop,
get_export_context,
get_import_context,
to_native_converter,
to_primitive_converter,
)
from ..translator import _
from ..util import get_all_subclasses, import_string
from .base import BaseType, get_value_in
T = TypeVar("T")
__all__ = [
"CompoundType",
"MultiType",
"ModelType",
"ListType",
"DictType",
"PolyModelType",
]
class CompoundType(BaseType):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.is_compound = True
try:
self.field.parent_field = self
except AttributeError:
pass
def _setup(self, field_name, owner_model):
# Recursively set up inner fields.
try:
field = self.field
except AttributeError:
pass
else:
field._setup(None, owner_model)
super()._setup(field_name, owner_model)
def convert(self, value, context=None):
context = context or get_import_context()
return self._convert(value, context)
def _convert(self, value, context):
raise NotImplementedError
def export(self, value, format, context=None):
context = context or get_export_context()
return self._export(value, format, context)
def _export(self, value, format, context):
raise NotImplementedError
def to_native(self, value, context=None):
context = context or get_export_context(to_native_converter)
return to_native_converter(self, value, context)
def to_primitive(self, value, context=None):
context = context or get_export_context(to_primitive_converter)
return to_primitive_converter(self, value, context)
def _init_field(self, field, options):
"""
Instantiate the inner field that represents each element within this compound type.
In case the inner field is itself a compound type, its inner field can be provided
as the ``nested_field`` keyword argument.
"""
if not isinstance(field, BaseType):
nested_field = options.pop("nested_field", None) or options.pop(
"compound_field", None
)
if nested_field:
field = field(field=nested_field, **options)
else:
field = field(**options)
return field
MultiType = CompoundType
class ModelType(CompoundType):
"""A field that can hold an instance of the specified model."""
primitive_type = dict
@property
def native_type(self):
return self.model_class
@property
def fields(self):
return self.model_class.fields
@property
def model_class(self):
if self._model_class:
return self._model_class
model_class = import_string(self.model_name)
self._model_class = model_class
return model_class
def __init__(self, model_spec: Type[T], **kwargs):
from ..models import ModelMeta
if isinstance(model_spec, ModelMeta):
self._model_class = model_spec
self.model_name = self.model_class.__name__
elif isinstance(model_spec, str):
self._model_class = None
self.model_name = model_spec
else:
raise TypeError(
"ModelType: Expected a model, got an argument "
"of the type '{}'.".format(model_spec.__class__.__name__)
)
super().__init__(**kwargs)
def _repr_info(self):
return self.model_class.__name__
def _mock(self, context=None):
return self.model_class.get_mock_object(context)
def _setup(self, field_name, owner_model):
# Resolve possible name-based model reference.
if not self._model_class:
if self.model_name == owner_model.__name__:
self._model_class = owner_model
else:
pass # Intentionally left blank, it will be setup later.
super()._setup(field_name, owner_model)
def pre_setattr(self, value):
from ..models import Model
if value is not None and not isinstance(value, Model):
if not isinstance(value, dict):
raise ConversionError(_("Model conversion requires a model or dict"))
value = self.model_class(value)
return value
def _convert(self, value, context):
field_model_class = self.model_class
if isinstance(value, field_model_class):
model_class = type(value)
elif isinstance(value, dict):
model_class = field_model_class
else:
raise ConversionError(
_("Input must be a mapping or '%s' instance")
% field_model_class.__name__
)
if context.convert and context.oo:
return model_class(value, context=context)
return convert(model_class._schema, value, context=context)
def _export(self, value, format, context):
from ..models import Model
if isinstance(value, Model):
model_class = type(value)
else:
model_class = self.model_class
return export_loop(model_class, value, context=context)
class ListType(CompoundType):
"""A field for storing a list of items, all of which must conform to the type
specified by the ``field`` parameter.
Use it like this::
...
categories = ListType(StringType)
"""
primitive_type = list
native_type = list
def __init__(self, field: T, min_size=None, max_size=None, **kwargs):
"""Create a list of objects of type `field`."""
self.field = self._init_field(field, kwargs)
self.min_size = min_size
self.max_size = max_size
validators = [self.check_length] + kwargs.pop("validators", [])
super().__init__(validators=validators, **kwargs)
@property
def model_class(self):
return self.field.model_class
def _repr_info(self):
return self.field.__class__.__name__
def _mock(self, context=None):
random_length = get_value_in(self.min_size, self.max_size)
return [self.field._mock(context) for dummy in range(random_length)]
def _coerce(self, value):
if isinstance(value, list):
return value
if isinstance(value, (str, Mapping)): # unacceptable iterables
pass
elif isinstance(value, Sequence):
return value
elif isinstance(value, Iterable):
return value
raise ConversionError(_("Could not interpret the value as a list"))
def _convert(self, value, context):
value = self._coerce(value)
data = []
errors = {}
for index, item in enumerate(value):
try:
data.append(context.field_converter(self.field, item, context))
except BaseError as exc:
errors[index] = exc
if errors:
raise CompoundError(errors)
return data
def check_length(self, value, context):
list_length = len(value) if value else 0
if self.min_size is not None and list_length < self.min_size:
message = (
{
True: _("Please provide at least %d item."),
False: _("Please provide at least %d items."),
}[self.min_size == 1]
) % self.min_size
raise ValidationError(message)
if self.max_size is not None and list_length > self.max_size:
message = (
{
True: _("Please provide no more than %d item."),
False: _("Please provide no more than %d items."),
}[self.max_size == 1]
) % self.max_size
raise ValidationError(message)
def _export(self, list_instance, format, context):
"""Loops over each item in the model and applies either the field
transform or the multitype transform. Essentially functions the same
as `transforms.export_loop`.
"""
data = []
_export_level = self.field.get_export_level(context)
if _export_level == DROP:
return data
for value in list_instance:
shaped = self.field.export(value, format, context)
if shaped is None:
if _export_level <= NOT_NONE:
continue
elif self.field.is_compound and len(shaped) == 0:
if _export_level <= NONEMPTY:
continue
data.append(shaped)
return data
class DictType(CompoundType):
"""A field for storing a mapping of items, the values of which must conform to the type
specified by the ``field`` parameter.
Use it like this::
...
categories = DictType(StringType)
"""
primitive_type = dict
native_type = dict
def __init__(self, field, coerce_key=None, **kwargs):
"""Create a dict with str keys and type `field` values."""
self.field = self._init_field(field, kwargs)
self.coerce_key = coerce_key or str
super().__init__(**kwargs)
@property
def model_class(self):
return self.field.model_class
def _repr_info(self):
return self.field.__class__.__name__
def _convert(self, value, context, safe=False):
if not isinstance(value, Mapping):
raise ConversionError(_("Only mappings may be used in a DictType"))
data = {}
errors = {}
for k, v in value.items():
try:
data[self.coerce_key(k)] = context.field_converter(
self.field, v, context
)
except BaseError as exc:
errors[k] = exc
if errors:
raise CompoundError(errors)
return data
def _export(self, dict_instance, format, context):
"""Loops over each item in the model and applies either the field
transform or the multitype transform. Essentially functions the same
as `transforms.export_loop`.
"""
data = {}
_export_level = self.field.get_export_level(context)
if _export_level == DROP:
return data
for key, value in dict_instance.items():
shaped = self.field.export(value, format, context)
if shaped is None:
if _export_level <= NOT_NONE:
continue
elif self.field.is_compound and len(shaped) == 0:
if _export_level <= NONEMPTY:
continue
data[key] = shaped
return data
class PolyModelType(CompoundType):
"""A field that accepts an instance of any of the specified models."""
primitive_type = dict
native_type = None # cannot be determined from a PolyModelType instance
def __init__(self, model_spec, **kwargs):
from ..models import ModelMeta
if isinstance(model_spec, (ModelMeta, str)):
self.model_classes = (model_spec,)
allow_subclasses = True
elif isinstance(model_spec, Iterable):
self.model_classes = tuple(model_spec)
allow_subclasses = False
else:
raise Exception(
"The first argument to PolyModelType.__init__() "
"must be a model or an iterable."
)
self.claim_function = kwargs.pop("claim_function", None)
self.allow_subclasses = kwargs.pop("allow_subclasses", allow_subclasses)
CompoundType.__init__(self, **kwargs)
def _setup(self, field_name, owner_model):
# Resolve possible name-based model references.
resolved_classes = []
for m in self.model_classes:
if isinstance(m, str):
if m == owner_model.__name__:
resolved_classes.append(owner_model)
else:
raise Exception(
"PolyModelType: Unable to resolve model '{}'.".format(m)
)
else:
resolved_classes.append(m)
self.model_classes = tuple(resolved_classes)
super()._setup(field_name, owner_model)
def is_allowed_model(self, model_instance):
if self.allow_subclasses:
if isinstance(model_instance, self.model_classes):
return True
else:
if model_instance.__class__ in self.model_classes:
return True
return False
def _convert(self, value, context):
if value is None:
return None
if not context.validate:
if self.is_allowed_model(value):
return value
if not isinstance(value, dict):
if len(self.model_classes) > 1:
instanceof_msg = "one of: {}".format(
", ".join(cls.__name__ for cls in self.model_classes)
)
else:
instanceof_msg = self.model_classes[0].__name__
raise ConversionError(
_(
"Please use a mapping for this field or " "an instance of {}"
).format(instanceof_msg)
)
model_class = self.find_model(value)
return model_class(value, context=context)
def find_model(self, data):
"""Finds the intended type by consulting potential classes or `claim_function`."""
if self.claim_function:
kls = self.claim_function(self, data)
if not kls:
raise Exception("Input for polymorphic field did not match any model")
return kls
fallback = None
matching_classes = []
for kls in self._get_candidates():
try:
# If a model defines a _claim_polymorphic method, use
# it to see if the model matches the data.
kls_claim = kls._claim_polymorphic
except AttributeError:
# The first model that doesn't define the hook can be
# used as a default if there's no match.
if not fallback:
fallback = kls
else:
if kls_claim(data):
matching_classes.append(kls)
if not matching_classes and fallback:
return fallback
if len(matching_classes) != 1:
raise Exception("Got ambiguous input for polymorphic field")
return matching_classes[0]
def _export(self, model_instance, format, context):
model_class = model_instance.__class__
if not self.is_allowed_model(model_instance):
raise Exception(
"Cannot export: {} is not an allowed type".format(model_class)
)
return model_instance.export(context=context)
def _get_candidates(self):
candidates = self.model_classes
if self.allow_subclasses:
candidates = itertools.chain.from_iterable(
([m] + get_all_subclasses(m) for m in candidates)
)
return candidates
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/types/compound.py
|
compound.py
|
import itertools
from collections.abc import Iterable, Mapping, Sequence
from typing import Type, TypeVar
from ..common import DROP, NONEMPTY, NOT_NONE
from ..exceptions import BaseError, CompoundError, ConversionError, ValidationError
from ..transforms import (
convert,
export_loop,
get_export_context,
get_import_context,
to_native_converter,
to_primitive_converter,
)
from ..translator import _
from ..util import get_all_subclasses, import_string
from .base import BaseType, get_value_in
T = TypeVar("T")
__all__ = [
"CompoundType",
"MultiType",
"ModelType",
"ListType",
"DictType",
"PolyModelType",
]
class CompoundType(BaseType):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.is_compound = True
try:
self.field.parent_field = self
except AttributeError:
pass
def _setup(self, field_name, owner_model):
# Recursively set up inner fields.
try:
field = self.field
except AttributeError:
pass
else:
field._setup(None, owner_model)
super()._setup(field_name, owner_model)
def convert(self, value, context=None):
context = context or get_import_context()
return self._convert(value, context)
def _convert(self, value, context):
raise NotImplementedError
def export(self, value, format, context=None):
context = context or get_export_context()
return self._export(value, format, context)
def _export(self, value, format, context):
raise NotImplementedError
def to_native(self, value, context=None):
context = context or get_export_context(to_native_converter)
return to_native_converter(self, value, context)
def to_primitive(self, value, context=None):
context = context or get_export_context(to_primitive_converter)
return to_primitive_converter(self, value, context)
def _init_field(self, field, options):
"""
Instantiate the inner field that represents each element within this compound type.
In case the inner field is itself a compound type, its inner field can be provided
as the ``nested_field`` keyword argument.
"""
if not isinstance(field, BaseType):
nested_field = options.pop("nested_field", None) or options.pop(
"compound_field", None
)
if nested_field:
field = field(field=nested_field, **options)
else:
field = field(**options)
return field
MultiType = CompoundType
class ModelType(CompoundType):
"""A field that can hold an instance of the specified model."""
primitive_type = dict
@property
def native_type(self):
return self.model_class
@property
def fields(self):
return self.model_class.fields
@property
def model_class(self):
if self._model_class:
return self._model_class
model_class = import_string(self.model_name)
self._model_class = model_class
return model_class
def __init__(self, model_spec: Type[T], **kwargs):
from ..models import ModelMeta
if isinstance(model_spec, ModelMeta):
self._model_class = model_spec
self.model_name = self.model_class.__name__
elif isinstance(model_spec, str):
self._model_class = None
self.model_name = model_spec
else:
raise TypeError(
"ModelType: Expected a model, got an argument "
"of the type '{}'.".format(model_spec.__class__.__name__)
)
super().__init__(**kwargs)
def _repr_info(self):
return self.model_class.__name__
def _mock(self, context=None):
return self.model_class.get_mock_object(context)
def _setup(self, field_name, owner_model):
# Resolve possible name-based model reference.
if not self._model_class:
if self.model_name == owner_model.__name__:
self._model_class = owner_model
else:
pass # Intentionally left blank, it will be setup later.
super()._setup(field_name, owner_model)
def pre_setattr(self, value):
from ..models import Model
if value is not None and not isinstance(value, Model):
if not isinstance(value, dict):
raise ConversionError(_("Model conversion requires a model or dict"))
value = self.model_class(value)
return value
def _convert(self, value, context):
field_model_class = self.model_class
if isinstance(value, field_model_class):
model_class = type(value)
elif isinstance(value, dict):
model_class = field_model_class
else:
raise ConversionError(
_("Input must be a mapping or '%s' instance")
% field_model_class.__name__
)
if context.convert and context.oo:
return model_class(value, context=context)
return convert(model_class._schema, value, context=context)
def _export(self, value, format, context):
from ..models import Model
if isinstance(value, Model):
model_class = type(value)
else:
model_class = self.model_class
return export_loop(model_class, value, context=context)
class ListType(CompoundType):
"""A field for storing a list of items, all of which must conform to the type
specified by the ``field`` parameter.
Use it like this::
...
categories = ListType(StringType)
"""
primitive_type = list
native_type = list
def __init__(self, field: T, min_size=None, max_size=None, **kwargs):
"""Create a list of objects of type `field`."""
self.field = self._init_field(field, kwargs)
self.min_size = min_size
self.max_size = max_size
validators = [self.check_length] + kwargs.pop("validators", [])
super().__init__(validators=validators, **kwargs)
@property
def model_class(self):
return self.field.model_class
def _repr_info(self):
return self.field.__class__.__name__
def _mock(self, context=None):
random_length = get_value_in(self.min_size, self.max_size)
return [self.field._mock(context) for dummy in range(random_length)]
def _coerce(self, value):
if isinstance(value, list):
return value
if isinstance(value, (str, Mapping)): # unacceptable iterables
pass
elif isinstance(value, Sequence):
return value
elif isinstance(value, Iterable):
return value
raise ConversionError(_("Could not interpret the value as a list"))
def _convert(self, value, context):
value = self._coerce(value)
data = []
errors = {}
for index, item in enumerate(value):
try:
data.append(context.field_converter(self.field, item, context))
except BaseError as exc:
errors[index] = exc
if errors:
raise CompoundError(errors)
return data
def check_length(self, value, context):
list_length = len(value) if value else 0
if self.min_size is not None and list_length < self.min_size:
message = (
{
True: _("Please provide at least %d item."),
False: _("Please provide at least %d items."),
}[self.min_size == 1]
) % self.min_size
raise ValidationError(message)
if self.max_size is not None and list_length > self.max_size:
message = (
{
True: _("Please provide no more than %d item."),
False: _("Please provide no more than %d items."),
}[self.max_size == 1]
) % self.max_size
raise ValidationError(message)
def _export(self, list_instance, format, context):
"""Loops over each item in the model and applies either the field
transform or the multitype transform. Essentially functions the same
as `transforms.export_loop`.
"""
data = []
_export_level = self.field.get_export_level(context)
if _export_level == DROP:
return data
for value in list_instance:
shaped = self.field.export(value, format, context)
if shaped is None:
if _export_level <= NOT_NONE:
continue
elif self.field.is_compound and len(shaped) == 0:
if _export_level <= NONEMPTY:
continue
data.append(shaped)
return data
class DictType(CompoundType):
"""A field for storing a mapping of items, the values of which must conform to the type
specified by the ``field`` parameter.
Use it like this::
...
categories = DictType(StringType)
"""
primitive_type = dict
native_type = dict
def __init__(self, field, coerce_key=None, **kwargs):
"""Create a dict with str keys and type `field` values."""
self.field = self._init_field(field, kwargs)
self.coerce_key = coerce_key or str
super().__init__(**kwargs)
@property
def model_class(self):
return self.field.model_class
def _repr_info(self):
return self.field.__class__.__name__
def _convert(self, value, context, safe=False):
if not isinstance(value, Mapping):
raise ConversionError(_("Only mappings may be used in a DictType"))
data = {}
errors = {}
for k, v in value.items():
try:
data[self.coerce_key(k)] = context.field_converter(
self.field, v, context
)
except BaseError as exc:
errors[k] = exc
if errors:
raise CompoundError(errors)
return data
def _export(self, dict_instance, format, context):
"""Loops over each item in the model and applies either the field
transform or the multitype transform. Essentially functions the same
as `transforms.export_loop`.
"""
data = {}
_export_level = self.field.get_export_level(context)
if _export_level == DROP:
return data
for key, value in dict_instance.items():
shaped = self.field.export(value, format, context)
if shaped is None:
if _export_level <= NOT_NONE:
continue
elif self.field.is_compound and len(shaped) == 0:
if _export_level <= NONEMPTY:
continue
data[key] = shaped
return data
class PolyModelType(CompoundType):
"""A field that accepts an instance of any of the specified models."""
primitive_type = dict
native_type = None # cannot be determined from a PolyModelType instance
def __init__(self, model_spec, **kwargs):
from ..models import ModelMeta
if isinstance(model_spec, (ModelMeta, str)):
self.model_classes = (model_spec,)
allow_subclasses = True
elif isinstance(model_spec, Iterable):
self.model_classes = tuple(model_spec)
allow_subclasses = False
else:
raise Exception(
"The first argument to PolyModelType.__init__() "
"must be a model or an iterable."
)
self.claim_function = kwargs.pop("claim_function", None)
self.allow_subclasses = kwargs.pop("allow_subclasses", allow_subclasses)
CompoundType.__init__(self, **kwargs)
def _setup(self, field_name, owner_model):
# Resolve possible name-based model references.
resolved_classes = []
for m in self.model_classes:
if isinstance(m, str):
if m == owner_model.__name__:
resolved_classes.append(owner_model)
else:
raise Exception(
"PolyModelType: Unable to resolve model '{}'.".format(m)
)
else:
resolved_classes.append(m)
self.model_classes = tuple(resolved_classes)
super()._setup(field_name, owner_model)
def is_allowed_model(self, model_instance):
if self.allow_subclasses:
if isinstance(model_instance, self.model_classes):
return True
else:
if model_instance.__class__ in self.model_classes:
return True
return False
def _convert(self, value, context):
if value is None:
return None
if not context.validate:
if self.is_allowed_model(value):
return value
if not isinstance(value, dict):
if len(self.model_classes) > 1:
instanceof_msg = "one of: {}".format(
", ".join(cls.__name__ for cls in self.model_classes)
)
else:
instanceof_msg = self.model_classes[0].__name__
raise ConversionError(
_(
"Please use a mapping for this field or " "an instance of {}"
).format(instanceof_msg)
)
model_class = self.find_model(value)
return model_class(value, context=context)
def find_model(self, data):
"""Finds the intended type by consulting potential classes or `claim_function`."""
if self.claim_function:
kls = self.claim_function(self, data)
if not kls:
raise Exception("Input for polymorphic field did not match any model")
return kls
fallback = None
matching_classes = []
for kls in self._get_candidates():
try:
# If a model defines a _claim_polymorphic method, use
# it to see if the model matches the data.
kls_claim = kls._claim_polymorphic
except AttributeError:
# The first model that doesn't define the hook can be
# used as a default if there's no match.
if not fallback:
fallback = kls
else:
if kls_claim(data):
matching_classes.append(kls)
if not matching_classes and fallback:
return fallback
if len(matching_classes) != 1:
raise Exception("Got ambiguous input for polymorphic field")
return matching_classes[0]
def _export(self, model_instance, format, context):
model_class = model_instance.__class__
if not self.is_allowed_model(model_instance):
raise Exception(
"Cannot export: {} is not an allowed type".format(model_class)
)
return model_instance.export(context=context)
def _get_candidates(self):
candidates = self.model_classes
if self.allow_subclasses:
candidates = itertools.chain.from_iterable(
([m] + get_all_subclasses(m) for m in candidates)
)
return candidates
| 0.820326 | 0.17075 |
import copy
import datetime
import decimal
import itertools
import numbers
import random
import re
import string
import uuid
from collections import OrderedDict
from collections.abc import Iterable
from typing import Any, Optional, Type
from ..common import DEFAULT, NATIVE, NONEMPTY, PRIMITIVE
from ..exceptions import (
ConversionError,
MockCreationError,
StopValidationError,
ValidationError,
)
from ..translator import _
from ..undefined import Undefined
from ..util import listify
from ..validate import get_validation_context, prepare_validator
__all__ = [
"BaseType",
"UUIDType",
"StringType",
"MultilingualStringType",
"NumberType",
"IntType",
"LongType",
"FloatType",
"DecimalType",
"HashType",
"MD5Type",
"SHA1Type",
"BooleanType",
"GeoPointType",
"DateType",
"DateTimeType",
"UTCDateTimeType",
"TimestampType",
"TimedeltaType",
]
def fill_template(template, min_length, max_length):
return template % random_string(
get_value_in(
min_length, max_length, padding=len(template) - 2, required_length=1
)
)
def get_range_endpoints(min_length, max_length, padding=0, required_length=0):
if min_length is None:
min_length = 0
if max_length is None:
max_length = max(min_length * 2, 16)
if padding:
max_length = max_length - padding
min_length = max(min_length - padding, 0)
if max_length < required_length:
raise MockCreationError("This field is too short to hold the mock data")
min_length = max(min_length, required_length)
if max_length < min_length:
raise MockCreationError("Minimum is greater than maximum")
return min_length, max_length
def get_value_in(min_length, max_length, padding=0, required_length=0):
return random.randint(
*get_range_endpoints(min_length, max_length, padding, required_length)
)
_alphanumeric = string.ascii_letters + string.digits
def random_string(length, chars=_alphanumeric):
return "".join(random.choice(chars) for _ in range(length))
_last_position_hint = -1
_next_position_hint = itertools.count()
class TypeMeta(type):
"""
Meta class for BaseType. Merges `MESSAGES` dict and accumulates
validator methods.
"""
def __new__(mcs, name, bases, attrs):
messages = {}
validators = OrderedDict()
for base in reversed(bases):
try:
messages.update(base.MESSAGES)
except AttributeError:
pass
try:
validators.update(base._validators)
except AttributeError:
pass
try:
messages.update(attrs["MESSAGES"])
except KeyError:
pass
attrs["MESSAGES"] = messages
for attr_name, attr in attrs.items():
if attr_name.startswith("validate_"):
validators[attr_name] = 1
attrs[attr_name] = prepare_validator(attr, 3)
attrs["_validators"] = validators
return type.__new__(mcs, name, bases, attrs)
class BaseType(metaclass=TypeMeta):
"""A base class for Types in a Schematics model. Instances of this
class may be added to subclasses of ``Model`` to define a model schema.
Validators that need to access variables on the instance
can be defined be implementing methods whose names start with ``validate_``
and accept one parameter (in addition to ``self``)
:param required:
Invalidate field when value is None or is not supplied. Default:
False.
:param default:
When no data is provided default to this value. May be a callable.
Default: None.
:param serialized_name:
The name of this field defaults to the class attribute used in the
model. However if the field has another name in foreign data set this
argument. Serialized data will use this value for the key name too.
:param deserialize_from:
A name or list of named fields for which foreign data sets are
searched to provide a value for the given field. This only effects
inbound data.
:param choices:
A list of valid choices. This is the last step of the validator
chain.
:param validators:
A list of callables. Each callable receives the value after it has been
converted into a rich python type. Default: []
:param serialize_when_none:
Dictates if the field should appear in the serialized data even if the
value is None. Default: None.
:param messages:
Override the error messages with a dict. You can also do this by
subclassing the Type and defining a `MESSAGES` dict attribute on the
class. A metaclass will merge all the `MESSAGES` and override the
resulting dict with instance level `messages` and assign to
`self.messages`.
:param metadata:
Dictionary for storing custom metadata associated with the field.
To encourage compatibility with external tools, we suggest these keys
for common metadata:
- *label* : Brief human-readable label
- *description* : Explanation of the purpose of the field. Used for
help, tooltips, documentation, etc.
"""
primitive_type: Optional[Type] = None
native_type: Optional[Type] = None
MESSAGES = {
"required": _("This field is required."),
"choices": _("Value must be one of {0}."),
}
EXPORT_METHODS = {
NATIVE: "to_native",
PRIMITIVE: "to_primitive",
}
def __init__(
self,
required=False,
default=Undefined,
serialized_name=None,
choices=None,
validators=None,
deserialize_from=None,
export_level=None,
serialize_when_none=None,
messages=None,
metadata=None,
):
super().__init__()
self.required = required
self._default = default
self.serialized_name = serialized_name
if choices and (isinstance(choices, str) or not isinstance(choices, Iterable)):
raise TypeError('"choices" must be a non-string Iterable')
self.choices = choices
self.deserialize_from = listify(deserialize_from)
self.validators = [
getattr(self, validator_name) for validator_name in self._validators
]
if validators:
self.validators += (prepare_validator(func, 2) for func in validators)
self._set_export_level(export_level, serialize_when_none)
self.messages = dict(self.MESSAGES, **(messages or {}))
self.metadata = metadata or {}
self._position_hint = next(_next_position_hint) # For ordering of fields
self.name = None
self.owner_model = None
self.parent_field = None
self.typeclass = self.__class__
self.is_compound = False
self.export_mapping = dict(
(format, getattr(self, fname))
for format, fname in self.EXPORT_METHODS.items()
)
def __repr__(self):
type_ = f"{self.__class__.__name__}({self._repr_info() or ''}) instance"
model = f" on {self.owner_model.__name__}" if self.owner_model else ""
field = f" as '{self.name}'" if self.name else ""
return f"<{type_}{model}{field}>"
def _repr_info(self):
return None
def __call__(self, value, context=None):
return self.convert(value, context)
def __deepcopy__(self, memo):
return copy.copy(self)
def _mock(self, context=None):
return None
def _setup(self, field_name, owner_model):
"""Perform late-stage setup tasks that are run after the containing model
has been created.
"""
self.name = field_name
self.owner_model = owner_model
self._input_keys = self._get_input_keys()
def _set_export_level(self, export_level, serialize_when_none):
if export_level is not None:
self.export_level = export_level
elif serialize_when_none is True:
self.export_level = DEFAULT
elif serialize_when_none is False:
self.export_level = NONEMPTY
else:
self.export_level = None
def get_export_level(self, context):
if self.owner_model:
level = self.owner_model._schema.options.export_level
else:
level = DEFAULT
if self.export_level is not None:
level = self.export_level
if context.export_level is not None:
level = context.export_level
return level
def get_input_keys(self, mapping=None):
if mapping:
return self._get_input_keys(mapping)
return self._input_keys
def _get_input_keys(self, mapping=None):
input_keys = [self.name]
if self.serialized_name:
input_keys.append(self.serialized_name)
if mapping and self.name in mapping:
input_keys.extend(listify(mapping[self.name]))
if self.deserialize_from:
input_keys.extend(self.deserialize_from)
return input_keys
@property
def default(self):
default = self._default
if callable(default):
default = default()
return default
def pre_setattr(self, value):
return value
def convert(self, value, context=None):
return self.to_native(value, context)
def export(self, value, format, context=None):
return self.export_mapping[format](value, context)
def to_primitive(self, value, context=None):
"""Convert internal data to a value safe to serialize."""
return value
def to_native(self, value, context=None):
"""
Convert untrusted data to a richer Python construct.
"""
return value
def validate(self, value, context=None):
"""
Validate the field and return a converted value or raise a
``ValidationError`` with a list of errors raised by the validation
chain. Stop the validation process from continuing through the
validators by raising ``StopValidationError`` instead of ``ValidationError``.
"""
context = context or get_validation_context()
if context.convert:
value = self.convert(value, context)
elif self.is_compound:
self.convert(value, context)
errors = []
for validator in self.validators:
try:
validator(value, context)
except ValidationError as exc:
errors.append(exc)
if isinstance(exc, StopValidationError):
break
if errors:
raise ValidationError(errors)
return value
def check_required(self, value, context):
if self.required and (value is None or value is Undefined):
if self.name is None or context and not context.partial:
raise ConversionError(self.messages["required"])
def validate_choices(self, value, context):
if self.choices is not None:
if value not in self.choices:
raise ValidationError(
self.messages["choices"].format(str(self.choices))
)
def mock(self, context=None):
if not self.required and not random.choice([True, False]):
return self.default
if self.choices is not None:
return random.choice(self.choices)
return self._mock(context)
class UUIDType(BaseType):
"""A field that stores a valid UUID value."""
primitive_type = str
native_type = uuid.UUID
MESSAGES = {
"convert": _("Couldn't interpret '{0}' value as UUID."),
}
def __init__(self, **kwargs):
"""Create a UUID field."""
super().__init__(**kwargs)
def _mock(self, context=None):
return uuid.uuid4()
def to_native(self, value, context=None):
if not isinstance(value, uuid.UUID):
try:
value = uuid.UUID(value)
except (TypeError, ValueError) as exc:
raise ConversionError(self.messages["convert"].format(value)) from exc
return value
def to_primitive(self, value, context=None):
return str(value)
class StringType(BaseType):
"""A Unicode string field."""
primitive_type = str
native_type = str
allow_casts = (int, bytes)
MESSAGES = {
"convert": _("Couldn't interpret '{0}' as string."),
"decode": _("Invalid UTF-8 data."),
"max_length": _("String value is too long."),
"min_length": _("String value is too short."),
"regex": _("String value did not match validation regex."),
}
def __init__(self, regex=None, max_length=None, min_length=None, **kwargs):
"""Create a typing.Text field."""
self.regex = re.compile(regex) if regex else None
self.max_length = max_length
self.min_length = min_length
super().__init__(**kwargs)
def _mock(self, context=None):
return random_string(get_value_in(self.min_length, self.max_length))
def to_native(self, value, context=None):
if isinstance(value, str):
return value
if isinstance(value, self.allow_casts):
if isinstance(value, bytes):
try:
return str(value, "utf-8")
except UnicodeError as exc:
raise ConversionError(
self.messages["decode"].format(value)
) from exc
elif isinstance(value, bool):
pass
else:
return str(value)
raise ConversionError(self.messages["convert"].format(value))
def validate_length(self, value, context=None):
length = len(value)
if self.max_length is not None and length > self.max_length:
raise ValidationError(self.messages["max_length"])
if self.min_length is not None and length < self.min_length:
raise ValidationError(self.messages["min_length"])
def validate_regex(self, value, context=None):
if self.regex is not None and self.regex.match(value) is None:
raise ValidationError(self.messages["regex"])
class NumberType(BaseType):
"""A generic number field.
Converts to and validates against `number_type` parameter.
"""
primitive_type: Optional[Type] = None
native_type: Optional[Type] = None
number_type: Optional[str] = None
MESSAGES = {
"number_coerce": _("Value '{0}' is not {1}."),
"number_min": _("{0} value should be greater than or equal to {1}."),
"number_max": _("{0} value should be less than or equal to {1}."),
}
def __init__(self, min_value=None, max_value=None, strict=False, **kwargs):
"""Create an int|float field."""
self.min_value = min_value
self.max_value = max_value
self.strict = strict
super().__init__(**kwargs)
def _mock(self, context=None):
number = random.uniform(*get_range_endpoints(self.min_value, self.max_value))
return self.native_type(number) if self.native_type else number
def to_native(self, value, context=None):
if isinstance(value, bool):
value = int(value)
if isinstance(value, self.native_type):
return value
try:
native_value = self.native_type(value)
except (TypeError, ValueError):
pass
else:
if self.native_type is float: # Float conversion is strict enough.
return native_value
if not self.strict and native_value == value: # Match numeric types.
return native_value
if isinstance(value, (str, numbers.Integral)):
return native_value
raise ConversionError(
self.messages["number_coerce"].format(value, self.number_type.lower())
)
def validate_range(self, value, context=None):
if self.min_value is not None and value < self.min_value:
raise ValidationError(
self.messages["number_min"].format(self.number_type, self.min_value)
)
if self.max_value is not None and value > self.max_value:
raise ValidationError(
self.messages["number_max"].format(self.number_type, self.max_value)
)
return value
class IntType(NumberType):
"""A field that validates input as an Integer"""
primitive_type = int
native_type = int
number_type = "Int"
def __init__(self, **kwargs):
"""Create an int field."""
super().__init__(**kwargs)
LongType = IntType
class FloatType(NumberType):
"""A field that validates input as a Float"""
primitive_type = float
native_type = float
number_type = "Float"
def __init__(self, **kwargs):
"""Create a float field."""
super().__init__(**kwargs)
class DecimalType(NumberType):
"""A fixed-point decimal number field."""
primitive_type = str
native_type = decimal.Decimal
number_type = "Decimal"
def to_primitive(self, value, context=None):
return str(value)
def to_native(self, value, context=None):
if isinstance(value, decimal.Decimal):
return value
if not isinstance(value, (str, bool)):
value = str(value)
try:
value = decimal.Decimal(value)
except (TypeError, decimal.InvalidOperation) as exc:
raise ConversionError(
self.messages["number_coerce"].format(value, self.number_type.lower())
) from exc
return value
class HashType(StringType):
MESSAGES = {
"hash_length": _("Hash value is wrong length."),
"hash_hex": _("Hash value is not hexadecimal."),
}
LENGTH = -1
def _mock(self, context=None):
return random_string(self.LENGTH, string.hexdigits)
def to_native(self, value, context=None):
value = super().to_native(value, context)
if len(value) != self.LENGTH:
raise ValidationError(self.messages["hash_length"])
try:
int(value, 16)
except ValueError as exc:
raise ConversionError(self.messages["hash_hex"]) from exc
return value
class MD5Type(HashType):
"""A field that validates input as resembling an MD5 hash."""
LENGTH = 32
class SHA1Type(HashType):
"""A field that validates input as resembling an SHA1 hash."""
LENGTH = 40
class BooleanType(BaseType):
"""A boolean field type. In addition to ``True`` and ``False``, coerces these
values:
+ For ``True``: "True", "true", "1"
+ For ``False``: "False", "false", "0"
"""
primitive_type = bool
native_type = bool
TRUE_VALUES = ("True", "true", "1")
FALSE_VALUES = ("False", "false", "0")
def __init__(self, **kwargs):
"""Create a bool field."""
super().__init__(**kwargs)
def _mock(self, context=None):
return random.choice([True, False])
def to_native(self, value, context=None):
if isinstance(value, str):
if value in self.TRUE_VALUES:
value = True
elif value in self.FALSE_VALUES:
value = False
elif isinstance(value, int) and value in [0, 1]:
value = bool(value)
if not isinstance(value, bool):
raise ConversionError(_("Must be either true or false."))
return value
class DateType(BaseType):
"""Defaults to converting to and from ISO8601 date values."""
primitive_type = str
native_type = datetime.date
SERIALIZED_FORMAT = "%Y-%m-%d"
MESSAGES = {
"parse": _("Could not parse {0}. Should be ISO 8601 (YYYY-MM-DD)."),
"parse_formats": _("Could not parse {0}. Valid formats: {1}"),
}
def __init__(self, formats=None, **kwargs):
"""Create a datetime.date field."""
if formats:
self.formats = listify(formats)
self.conversion_errmsg = self.MESSAGES["parse_formats"]
else:
self.formats = ["%Y-%m-%d"]
self.conversion_errmsg = self.MESSAGES["parse"]
self.serialized_format = self.SERIALIZED_FORMAT
super().__init__(**kwargs)
def _mock(self, context=None):
return datetime.date(
year=random.randrange(600) + 1900,
month=random.randrange(12) + 1,
day=random.randrange(28) + 1,
)
def to_native(self, value, context=None):
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
for fmt in self.formats:
try:
return datetime.datetime.strptime(value, fmt).date()
except (ValueError, TypeError):
continue
raise ConversionError(
self.conversion_errmsg.format(value, ", ".join(self.formats))
)
def to_primitive(self, value, context=None):
return value.strftime(self.serialized_format)
class DateTimeType(BaseType):
"""A field that holds a combined date and time value.
The built-in parser accepts input values conforming to the ISO 8601 format
``<YYYY>-<MM>-<DD>T<hh>:<mm>[:<ss.ssssss>][<z>]``. A space may be substituted
for the delimiter ``T``. The time zone designator ``<z>`` may be either ``Z``
or ``±<hh>[:][<mm>]``.
Values are stored as standard ``datetime.datetime`` instances with the time zone
offset in the ``tzinfo`` component if available. Raw values that do not specify a time
zone will be converted to naive ``datetime`` objects unless ``tzd='utc'`` is in effect.
Unix timestamps are also valid input values and will be converted to UTC datetimes.
:param formats:
(Optional) A value or iterable of values suitable as ``datetime.datetime.strptime`` format
strings, for example ``('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f')``. If the parameter is
present, ``strptime()`` will be used for parsing instead of the built-in parser.
:param serialized_format:
The output format suitable for Python ``strftime``. Default: ``'%Y-%m-%dT%H:%M:%S.%f%z'``
:param parser:
(Optional) An external function to use for parsing instead of the built-in parser. It should
return a ``datetime.datetime`` instance.
:param tzd:
Sets the time zone policy.
Default: ``'allow'``
============== ======================================================================
``'require'`` Values must specify a time zone.
``'allow'`` Values both with and without a time zone designator are allowed.
``'utc'`` Like ``allow``, but values with no time zone information are assumed
to be in UTC.
``'reject'`` Values must not specify a time zone. This also prohibits timestamps.
============== ======================================================================
:param convert_tz:
Indicates whether values with a time zone designator should be automatically converted to UTC.
Default: ``False``
* ``True``: Convert the datetime to UTC based on its time zone offset.
* ``False``: Don't convert. Keep the original time and offset intact.
:param drop_tzinfo:
Can be set to automatically remove the ``tzinfo`` objects. This option should generally
be used in conjunction with the ``convert_tz`` option unless you only care about local
wall clock times. Default: ``False``
* ``True``: Discard the ``tzinfo`` components and make naive ``datetime`` objects instead.
* ``False``: Preserve the ``tzinfo`` components if present.
"""
primitive_type: Type[Any] = str
native_type = datetime.datetime
SERIALIZED_FORMAT = "%Y-%m-%dT%H:%M:%S.%f%z"
MESSAGES = {
"parse": _("Could not parse {0}. Should be ISO 8601 or timestamp."),
"parse_formats": _("Could not parse {0}. Valid formats: {1}"),
"parse_external": _("Could not parse {0}."),
"parse_tzd_require": _("Could not parse {0}. Time zone offset required."),
"parse_tzd_reject": _("Could not parse {0}. Time zone offset not allowed."),
"tzd_require": _("Could not convert {0}. Time zone required but not found."),
"tzd_reject": _("Could not convert {0}. Time zone offsets not allowed."),
"validate_tzd_require": _("Time zone information required but not found."),
"validate_tzd_reject": _("Time zone information not allowed."),
"validate_utc_none": _("Time zone must be UTC but was None."),
"validate_utc_wrong": _("Time zone must be UTC."),
}
REGEX = re.compile(
r"""
(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)(?:T|\ )
(?P<hour>\d\d):(?P<minute>\d\d)
(?::(?P<second>\d\d)(?:(?:\.|,)(?P<sec_frac>\d{1,6}))?)?
(?:(?P<tzd_offset>(?P<tzd_sign>[+−-])(?P<tzd_hour>\d\d):?(?P<tzd_minute>\d\d)?)
|(?P<tzd_utc>Z))?$""",
re.X,
)
TIMEDELTA_ZERO = datetime.timedelta(0)
class fixed_timezone(datetime.tzinfo):
def utcoffset(self, dt):
return self.offset
def fromutc(self, dt):
return dt + self.offset
def dst(self, dt):
return None
def tzname(self, dt):
return self.str
def __str__(self):
return self.str
def __repr__(self, info=""):
return f"{type(self).__name__}({info})"
class utc_timezone(fixed_timezone):
offset = datetime.timedelta(0)
name = str = "UTC"
class offset_timezone(fixed_timezone):
def __init__(self, hours=0, minutes=0):
self.offset = datetime.timedelta(hours=hours, minutes=minutes)
total_seconds = self.offset.days * 86400 + self.offset.seconds
self.str = "{0:s}{1:02d}:{2:02d}".format(
"+" if total_seconds >= 0 else "-",
int(abs(total_seconds) / 3600),
int(abs(total_seconds) % 3600 / 60),
)
def __repr__(self):
return DateTimeType.fixed_timezone.__repr__(self, self.str)
UTC = utc_timezone()
EPOCH = datetime.datetime(1970, 1, 1, tzinfo=UTC)
def __init__(
self,
formats=None,
serialized_format=None,
parser=None,
tzd="allow",
convert_tz=False,
drop_tzinfo=False,
**kwargs,
):
"""Create a datetime.datetime field."""
if tzd not in ("require", "allow", "utc", "reject"):
raise ValueError(
"DateTimeType.__init__() got an invalid value for parameter 'tzd'"
)
self.formats = listify(formats)
self.serialized_format = serialized_format or self.SERIALIZED_FORMAT
self.parser = parser
self.tzd = tzd
self.convert_tz = convert_tz
self.drop_tzinfo = drop_tzinfo
super().__init__(**kwargs)
def _mock(self, context=None):
dt = datetime.datetime(
year=random.randrange(600) + 1900,
month=random.randrange(12) + 1,
day=random.randrange(28) + 1,
hour=random.randrange(24),
minute=random.randrange(60),
second=random.randrange(60),
microsecond=random.randrange(1000000),
)
if (
self.tzd == "reject"
or self.drop_tzinfo
or self.tzd == "allow"
and random.randrange(2)
):
return dt
if self.convert_tz:
return dt.replace(tzinfo=self.UTC)
return dt.replace(
tzinfo=self.offset_timezone(
hours=random.randrange(-12, 15), minutes=random.choice([0, 30, 45])
)
)
def to_native(self, value, context=None):
if isinstance(value, datetime.datetime):
if value.tzinfo is None:
if not self.drop_tzinfo:
if self.tzd == "require":
raise ConversionError(
self.messages["tzd_require"].format(value)
)
if self.tzd == "utc":
value = value.replace(tzinfo=self.UTC)
else:
if self.tzd == "reject":
raise ConversionError(self.messages["tzd_reject"].format(value))
if self.convert_tz:
value = value.astimezone(self.UTC)
if self.drop_tzinfo:
value = value.replace(tzinfo=None)
return value
if self.formats:
# Delegate to datetime.datetime.strptime() using provided format strings.
for fmt in self.formats:
try:
dt = datetime.datetime.strptime(value, fmt)
break
except (ValueError, TypeError):
continue
else:
raise ConversionError(
self.messages["parse_formats"].format(
value, ", ".join(self.formats)
)
)
elif self.parser:
# Delegate to external parser.
try:
dt = self.parser(value)
except Exception as exc:
raise ConversionError(
self.messages["parse_external"].format(value)
) from exc
else:
# Use built-in parser.
try:
value = float(value)
except ValueError:
dt = self.from_string(value)
except TypeError as exc:
raise ConversionError(self.messages["parse"].format(value)) from exc
else:
dt = self.from_timestamp(value)
if not dt:
raise ConversionError(self.messages["parse"].format(value))
if dt.tzinfo is None:
if self.tzd == "require":
raise ConversionError(self.messages["parse_tzd_require"].format(value))
if self.tzd == "utc" and not self.drop_tzinfo:
dt = dt.replace(tzinfo=self.UTC)
else:
if self.tzd == "reject":
raise ConversionError(self.messages["parse_tzd_reject"].format(value))
if self.convert_tz:
dt = dt.astimezone(self.UTC)
if self.drop_tzinfo:
dt = dt.replace(tzinfo=None)
return dt
def from_string(self, value):
match = self.REGEX.match(value)
if not match:
return None
parts = dict(((k, v) for k, v in match.groupdict().items() if v is not None))
def p(name):
return int(parts.get(name, 0))
microsecond = p("sec_frac") and p("sec_frac") * 10 ** (
6 - len(parts["sec_frac"])
)
if "tzd_utc" in parts:
tz = self.UTC
elif "tzd_offset" in parts:
tz_sign = 1 if parts["tzd_sign"] == "+" else -1
tz_offset = (p("tzd_hour") * 60 + p("tzd_minute")) * tz_sign
if tz_offset == 0:
tz = self.UTC
else:
tz = self.offset_timezone(minutes=tz_offset)
else:
tz = None
try:
return datetime.datetime(
p("year"),
p("month"),
p("day"),
p("hour"),
p("minute"),
p("second"),
microsecond,
tz,
)
except (ValueError, TypeError):
return None
def from_timestamp(self, value):
try:
return datetime.datetime(1970, 1, 1, tzinfo=self.UTC) + datetime.timedelta(
seconds=value
)
except (ValueError, TypeError):
return None
def to_primitive(self, value, context=None):
if callable(self.serialized_format):
return self.serialized_format(value)
return value.strftime(self.serialized_format)
def validate_tz(self, value, context=None):
if value.tzinfo is None:
if not self.drop_tzinfo:
if self.tzd == "require":
raise ValidationError(self.messages["validate_tzd_require"])
if self.tzd == "utc":
raise ValidationError(self.messages["validate_utc_none"])
else:
if self.drop_tzinfo:
raise ValidationError(self.messages["validate_tzd_reject"])
if self.tzd == "reject":
raise ValidationError(self.messages["validate_tzd_reject"])
if self.convert_tz and value.tzinfo.utcoffset(value) != self.TIMEDELTA_ZERO:
raise ValidationError(self.messages["validate_utc_wrong"])
class UTCDateTimeType(DateTimeType):
"""A variant of ``DateTimeType`` that normalizes everything to UTC and stores values
as naive ``datetime`` instances. By default sets ``tzd='utc'``, ``convert_tz=True``,
and ``drop_tzinfo=True``. The standard export format always includes the UTC time
zone designator ``"Z"``.
"""
SERIALIZED_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
def __init__(
self,
formats=None,
parser=None,
tzd="utc",
convert_tz=True,
drop_tzinfo=True,
**kwargs,
):
"""Create a datetime.datetime in UTC field."""
super().__init__(
formats=formats,
parser=parser,
tzd=tzd,
convert_tz=convert_tz,
drop_tzinfo=drop_tzinfo,
**kwargs,
)
class TimestampType(DateTimeType):
"""A variant of ``DateTimeType`` that exports itself as a Unix timestamp
instead of an ISO 8601 string. Always sets ``tzd='require'`` and
``convert_tz=True``.
"""
primitive_type = float
def __init__(self, formats=None, parser=None, drop_tzinfo=False, **kwargs):
"""Create a datetime.datetime as a float field."""
super().__init__(
formats=formats,
parser=parser,
tzd="require",
convert_tz=True,
drop_tzinfo=drop_tzinfo,
**kwargs,
)
def to_primitive(self, value, context=None):
if value.tzinfo is None:
value = value.replace(tzinfo=self.UTC)
else:
value = value.astimezone(self.UTC)
delta = value - self.EPOCH
return delta.total_seconds()
class TimedeltaType(BaseType):
"""Converts Python Timedelta objects into the corresponding value in seconds."""
primitive_type = float
native_type = datetime.timedelta
MESSAGES = {
"convert": _("Couldn't interpret '{0}' value as Timedelta."),
}
DAYS = "days"
SECONDS = "seconds"
MICROSECONDS = "microseconds"
MILLISECONDS = "milliseconds"
MINUTES = "minutes"
HOURS = "hours"
WEEKS = "weeks"
def __init__(self, precision="seconds", **kwargs):
"""Create a datetime.timedelta field."""
precision = precision.lower()
units = (
self.DAYS,
self.SECONDS,
self.MICROSECONDS,
self.MILLISECONDS,
self.MINUTES,
self.HOURS,
self.WEEKS,
)
if precision not in units:
raise ValueError(
"TimedeltaType.__init__() got an invalid value for parameter 'precision'"
)
self.precision = precision
super().__init__(**kwargs)
def _mock(self, context=None):
return datetime.timedelta(seconds=random.random() * 1000)
def to_native(self, value, context=None):
if isinstance(value, datetime.timedelta):
return value
try:
return datetime.timedelta(**{self.precision: float(value)})
except (ValueError, TypeError) as exc:
raise ConversionError(self.messages["convert"].format(value)) from exc
def to_primitive(self, value, context=None):
base_unit = datetime.timedelta(**{self.precision: 1})
return int(value.total_seconds() / base_unit.total_seconds())
class GeoPointType(BaseType):
"""A list storing a latitude and longitude."""
primitive_type = list
native_type = list
MESSAGES = {
"point_min": _("{0} value {1} should be greater than or equal to {2}."),
"point_max": _("{0} value {1} should be less than or equal to {2}."),
}
def _mock(self, context=None):
return (random.randrange(-90, 90), random.randrange(-180, 180))
@classmethod
def _normalize(cls, value):
if isinstance(value, dict):
return list(value.values())
return list(value)
def to_native(self, value, context=None):
"""Make sure that a geo-value is of type (x, y)"""
if not isinstance(value, (tuple, list, dict)):
raise ConversionError(
_("GeoPointType can only accept tuples, lists, or dicts")
)
elements = self._normalize(value)
if not len(elements) == 2:
raise ConversionError(_("Value must be a two-dimensional point"))
if not all(isinstance(v, (float, int)) for v in elements):
raise ConversionError(_("Both values in point must be float or int"))
return value
def validate_range(self, value, context=None):
latitude, longitude = self._normalize(value)
if latitude < -90:
raise ValidationError(
self.messages["point_min"].format("Latitude", latitude, "-90")
)
if latitude > 90:
raise ValidationError(
self.messages["point_max"].format("Latitude", latitude, "90")
)
if longitude < -180:
raise ValidationError(
self.messages["point_min"].format("Longitude", longitude, -180)
)
if longitude > 180:
raise ValidationError(
self.messages["point_max"].format("Longitude", longitude, 180)
)
class MultilingualStringType(BaseType):
"""
A multilanguage string field, stored as a dict with {'locale': 'localized_value'}.
Minimum and maximum lengths apply to each of the localized values.
At least one of ``default_locale`` or ``context.app_data['locale']`` must be defined
when calling ``.to_primitive``.
"""
primitive_type = str
native_type = str
allow_casts = (int, bytes)
MESSAGES = {
"convert": _("Couldn't interpret value as string."),
"max_length": _("String value in locale {0} is too long."),
"min_length": _("String value in locale {0} is too short."),
"locale_not_found": _("No requested locale was available."),
"no_locale": _("No default or explicit locales were given."),
"regex_locale": _("Name of locale {0} did not match validation regex."),
"regex_localized": _(
"String value in locale {0} did not match validation regex."
),
}
LOCALE_REGEX = r"^[a-z]{2}(:?_[A-Z]{2})?$"
def __init__(
self,
regex=None,
max_length=None,
min_length=None,
default_locale=None,
locale_regex=LOCALE_REGEX,
**kwargs,
):
self.regex = re.compile(regex) if regex else None
self.max_length = max_length
self.min_length = min_length
self.default_locale = default_locale
self.locale_regex = re.compile(locale_regex) if locale_regex else None
super().__init__(**kwargs)
def _mock(self, context=None):
return random_string(get_value_in(self.min_length, self.max_length))
def to_native(self, value, context=None):
"""Make sure a MultilingualStringType value is a dict or None."""
if not (value is None or isinstance(value, dict)):
raise ConversionError(_("Value must be a dict or None"))
return value
def to_primitive(self, value, context=None):
"""
Use a combination of ``default_locale`` and ``context.app_data['locale']`` to return
the best localized string.
"""
if value is None:
return None
context_locale = None
if context and "locale" in context.app_data:
context_locale = context.app_data["locale"]
# Build a list of all possible locales to try
possible_locales = []
for locale in (context_locale, self.default_locale):
if not locale:
continue
if isinstance(locale, str):
possible_locales.append(locale)
else:
possible_locales.extend(locale)
if not possible_locales:
raise ConversionError(self.messages["no_locale"])
for locale in possible_locales:
if locale in value:
localized = value[locale]
break
else:
raise ConversionError(self.messages["locale_not_found"])
if not isinstance(localized, str):
if isinstance(localized, self.allow_casts):
if isinstance(localized, bytes):
localized = str(localized, "utf-8")
else:
localized = str(localized)
else:
raise ConversionError(self.messages["convert"])
return localized
def validate_length(self, value, context=None):
for locale, localized in value.items():
len_of_value = len(localized) if localized else 0
if self.max_length is not None and len_of_value > self.max_length:
raise ValidationError(self.messages["max_length"].format(locale))
if self.min_length is not None and len_of_value < self.min_length:
raise ValidationError(self.messages["min_length"].format(locale))
def validate_regex(self, value, context=None):
if self.regex is None and self.locale_regex is None:
return
for locale, localized in value.items():
if self.regex is not None and self.regex.match(localized) is None:
raise ValidationError(self.messages["regex_localized"].format(locale))
if (
self.locale_regex is not None
and self.locale_regex.match(locale) is None
):
raise ValidationError(self.messages["regex_locale"].format(locale))
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/types/base.py
|
base.py
|
import copy
import datetime
import decimal
import itertools
import numbers
import random
import re
import string
import uuid
from collections import OrderedDict
from collections.abc import Iterable
from typing import Any, Optional, Type
from ..common import DEFAULT, NATIVE, NONEMPTY, PRIMITIVE
from ..exceptions import (
ConversionError,
MockCreationError,
StopValidationError,
ValidationError,
)
from ..translator import _
from ..undefined import Undefined
from ..util import listify
from ..validate import get_validation_context, prepare_validator
__all__ = [
"BaseType",
"UUIDType",
"StringType",
"MultilingualStringType",
"NumberType",
"IntType",
"LongType",
"FloatType",
"DecimalType",
"HashType",
"MD5Type",
"SHA1Type",
"BooleanType",
"GeoPointType",
"DateType",
"DateTimeType",
"UTCDateTimeType",
"TimestampType",
"TimedeltaType",
]
def fill_template(template, min_length, max_length):
return template % random_string(
get_value_in(
min_length, max_length, padding=len(template) - 2, required_length=1
)
)
def get_range_endpoints(min_length, max_length, padding=0, required_length=0):
if min_length is None:
min_length = 0
if max_length is None:
max_length = max(min_length * 2, 16)
if padding:
max_length = max_length - padding
min_length = max(min_length - padding, 0)
if max_length < required_length:
raise MockCreationError("This field is too short to hold the mock data")
min_length = max(min_length, required_length)
if max_length < min_length:
raise MockCreationError("Minimum is greater than maximum")
return min_length, max_length
def get_value_in(min_length, max_length, padding=0, required_length=0):
return random.randint(
*get_range_endpoints(min_length, max_length, padding, required_length)
)
_alphanumeric = string.ascii_letters + string.digits
def random_string(length, chars=_alphanumeric):
return "".join(random.choice(chars) for _ in range(length))
_last_position_hint = -1
_next_position_hint = itertools.count()
class TypeMeta(type):
"""
Meta class for BaseType. Merges `MESSAGES` dict and accumulates
validator methods.
"""
def __new__(mcs, name, bases, attrs):
messages = {}
validators = OrderedDict()
for base in reversed(bases):
try:
messages.update(base.MESSAGES)
except AttributeError:
pass
try:
validators.update(base._validators)
except AttributeError:
pass
try:
messages.update(attrs["MESSAGES"])
except KeyError:
pass
attrs["MESSAGES"] = messages
for attr_name, attr in attrs.items():
if attr_name.startswith("validate_"):
validators[attr_name] = 1
attrs[attr_name] = prepare_validator(attr, 3)
attrs["_validators"] = validators
return type.__new__(mcs, name, bases, attrs)
class BaseType(metaclass=TypeMeta):
"""A base class for Types in a Schematics model. Instances of this
class may be added to subclasses of ``Model`` to define a model schema.
Validators that need to access variables on the instance
can be defined be implementing methods whose names start with ``validate_``
and accept one parameter (in addition to ``self``)
:param required:
Invalidate field when value is None or is not supplied. Default:
False.
:param default:
When no data is provided default to this value. May be a callable.
Default: None.
:param serialized_name:
The name of this field defaults to the class attribute used in the
model. However if the field has another name in foreign data set this
argument. Serialized data will use this value for the key name too.
:param deserialize_from:
A name or list of named fields for which foreign data sets are
searched to provide a value for the given field. This only effects
inbound data.
:param choices:
A list of valid choices. This is the last step of the validator
chain.
:param validators:
A list of callables. Each callable receives the value after it has been
converted into a rich python type. Default: []
:param serialize_when_none:
Dictates if the field should appear in the serialized data even if the
value is None. Default: None.
:param messages:
Override the error messages with a dict. You can also do this by
subclassing the Type and defining a `MESSAGES` dict attribute on the
class. A metaclass will merge all the `MESSAGES` and override the
resulting dict with instance level `messages` and assign to
`self.messages`.
:param metadata:
Dictionary for storing custom metadata associated with the field.
To encourage compatibility with external tools, we suggest these keys
for common metadata:
- *label* : Brief human-readable label
- *description* : Explanation of the purpose of the field. Used for
help, tooltips, documentation, etc.
"""
primitive_type: Optional[Type] = None
native_type: Optional[Type] = None
MESSAGES = {
"required": _("This field is required."),
"choices": _("Value must be one of {0}."),
}
EXPORT_METHODS = {
NATIVE: "to_native",
PRIMITIVE: "to_primitive",
}
def __init__(
self,
required=False,
default=Undefined,
serialized_name=None,
choices=None,
validators=None,
deserialize_from=None,
export_level=None,
serialize_when_none=None,
messages=None,
metadata=None,
):
super().__init__()
self.required = required
self._default = default
self.serialized_name = serialized_name
if choices and (isinstance(choices, str) or not isinstance(choices, Iterable)):
raise TypeError('"choices" must be a non-string Iterable')
self.choices = choices
self.deserialize_from = listify(deserialize_from)
self.validators = [
getattr(self, validator_name) for validator_name in self._validators
]
if validators:
self.validators += (prepare_validator(func, 2) for func in validators)
self._set_export_level(export_level, serialize_when_none)
self.messages = dict(self.MESSAGES, **(messages or {}))
self.metadata = metadata or {}
self._position_hint = next(_next_position_hint) # For ordering of fields
self.name = None
self.owner_model = None
self.parent_field = None
self.typeclass = self.__class__
self.is_compound = False
self.export_mapping = dict(
(format, getattr(self, fname))
for format, fname in self.EXPORT_METHODS.items()
)
def __repr__(self):
type_ = f"{self.__class__.__name__}({self._repr_info() or ''}) instance"
model = f" on {self.owner_model.__name__}" if self.owner_model else ""
field = f" as '{self.name}'" if self.name else ""
return f"<{type_}{model}{field}>"
def _repr_info(self):
return None
def __call__(self, value, context=None):
return self.convert(value, context)
def __deepcopy__(self, memo):
return copy.copy(self)
def _mock(self, context=None):
return None
def _setup(self, field_name, owner_model):
"""Perform late-stage setup tasks that are run after the containing model
has been created.
"""
self.name = field_name
self.owner_model = owner_model
self._input_keys = self._get_input_keys()
def _set_export_level(self, export_level, serialize_when_none):
if export_level is not None:
self.export_level = export_level
elif serialize_when_none is True:
self.export_level = DEFAULT
elif serialize_when_none is False:
self.export_level = NONEMPTY
else:
self.export_level = None
def get_export_level(self, context):
if self.owner_model:
level = self.owner_model._schema.options.export_level
else:
level = DEFAULT
if self.export_level is not None:
level = self.export_level
if context.export_level is not None:
level = context.export_level
return level
def get_input_keys(self, mapping=None):
if mapping:
return self._get_input_keys(mapping)
return self._input_keys
def _get_input_keys(self, mapping=None):
input_keys = [self.name]
if self.serialized_name:
input_keys.append(self.serialized_name)
if mapping and self.name in mapping:
input_keys.extend(listify(mapping[self.name]))
if self.deserialize_from:
input_keys.extend(self.deserialize_from)
return input_keys
@property
def default(self):
default = self._default
if callable(default):
default = default()
return default
def pre_setattr(self, value):
return value
def convert(self, value, context=None):
return self.to_native(value, context)
def export(self, value, format, context=None):
return self.export_mapping[format](value, context)
def to_primitive(self, value, context=None):
"""Convert internal data to a value safe to serialize."""
return value
def to_native(self, value, context=None):
"""
Convert untrusted data to a richer Python construct.
"""
return value
def validate(self, value, context=None):
"""
Validate the field and return a converted value or raise a
``ValidationError`` with a list of errors raised by the validation
chain. Stop the validation process from continuing through the
validators by raising ``StopValidationError`` instead of ``ValidationError``.
"""
context = context or get_validation_context()
if context.convert:
value = self.convert(value, context)
elif self.is_compound:
self.convert(value, context)
errors = []
for validator in self.validators:
try:
validator(value, context)
except ValidationError as exc:
errors.append(exc)
if isinstance(exc, StopValidationError):
break
if errors:
raise ValidationError(errors)
return value
def check_required(self, value, context):
if self.required and (value is None or value is Undefined):
if self.name is None or context and not context.partial:
raise ConversionError(self.messages["required"])
def validate_choices(self, value, context):
if self.choices is not None:
if value not in self.choices:
raise ValidationError(
self.messages["choices"].format(str(self.choices))
)
def mock(self, context=None):
if not self.required and not random.choice([True, False]):
return self.default
if self.choices is not None:
return random.choice(self.choices)
return self._mock(context)
class UUIDType(BaseType):
"""A field that stores a valid UUID value."""
primitive_type = str
native_type = uuid.UUID
MESSAGES = {
"convert": _("Couldn't interpret '{0}' value as UUID."),
}
def __init__(self, **kwargs):
"""Create a UUID field."""
super().__init__(**kwargs)
def _mock(self, context=None):
return uuid.uuid4()
def to_native(self, value, context=None):
if not isinstance(value, uuid.UUID):
try:
value = uuid.UUID(value)
except (TypeError, ValueError) as exc:
raise ConversionError(self.messages["convert"].format(value)) from exc
return value
def to_primitive(self, value, context=None):
return str(value)
class StringType(BaseType):
"""A Unicode string field."""
primitive_type = str
native_type = str
allow_casts = (int, bytes)
MESSAGES = {
"convert": _("Couldn't interpret '{0}' as string."),
"decode": _("Invalid UTF-8 data."),
"max_length": _("String value is too long."),
"min_length": _("String value is too short."),
"regex": _("String value did not match validation regex."),
}
def __init__(self, regex=None, max_length=None, min_length=None, **kwargs):
"""Create a typing.Text field."""
self.regex = re.compile(regex) if regex else None
self.max_length = max_length
self.min_length = min_length
super().__init__(**kwargs)
def _mock(self, context=None):
return random_string(get_value_in(self.min_length, self.max_length))
def to_native(self, value, context=None):
if isinstance(value, str):
return value
if isinstance(value, self.allow_casts):
if isinstance(value, bytes):
try:
return str(value, "utf-8")
except UnicodeError as exc:
raise ConversionError(
self.messages["decode"].format(value)
) from exc
elif isinstance(value, bool):
pass
else:
return str(value)
raise ConversionError(self.messages["convert"].format(value))
def validate_length(self, value, context=None):
length = len(value)
if self.max_length is not None and length > self.max_length:
raise ValidationError(self.messages["max_length"])
if self.min_length is not None and length < self.min_length:
raise ValidationError(self.messages["min_length"])
def validate_regex(self, value, context=None):
if self.regex is not None and self.regex.match(value) is None:
raise ValidationError(self.messages["regex"])
class NumberType(BaseType):
"""A generic number field.
Converts to and validates against `number_type` parameter.
"""
primitive_type: Optional[Type] = None
native_type: Optional[Type] = None
number_type: Optional[str] = None
MESSAGES = {
"number_coerce": _("Value '{0}' is not {1}."),
"number_min": _("{0} value should be greater than or equal to {1}."),
"number_max": _("{0} value should be less than or equal to {1}."),
}
def __init__(self, min_value=None, max_value=None, strict=False, **kwargs):
"""Create an int|float field."""
self.min_value = min_value
self.max_value = max_value
self.strict = strict
super().__init__(**kwargs)
def _mock(self, context=None):
number = random.uniform(*get_range_endpoints(self.min_value, self.max_value))
return self.native_type(number) if self.native_type else number
def to_native(self, value, context=None):
if isinstance(value, bool):
value = int(value)
if isinstance(value, self.native_type):
return value
try:
native_value = self.native_type(value)
except (TypeError, ValueError):
pass
else:
if self.native_type is float: # Float conversion is strict enough.
return native_value
if not self.strict and native_value == value: # Match numeric types.
return native_value
if isinstance(value, (str, numbers.Integral)):
return native_value
raise ConversionError(
self.messages["number_coerce"].format(value, self.number_type.lower())
)
def validate_range(self, value, context=None):
if self.min_value is not None and value < self.min_value:
raise ValidationError(
self.messages["number_min"].format(self.number_type, self.min_value)
)
if self.max_value is not None and value > self.max_value:
raise ValidationError(
self.messages["number_max"].format(self.number_type, self.max_value)
)
return value
class IntType(NumberType):
"""A field that validates input as an Integer"""
primitive_type = int
native_type = int
number_type = "Int"
def __init__(self, **kwargs):
"""Create an int field."""
super().__init__(**kwargs)
LongType = IntType
class FloatType(NumberType):
"""A field that validates input as a Float"""
primitive_type = float
native_type = float
number_type = "Float"
def __init__(self, **kwargs):
"""Create a float field."""
super().__init__(**kwargs)
class DecimalType(NumberType):
"""A fixed-point decimal number field."""
primitive_type = str
native_type = decimal.Decimal
number_type = "Decimal"
def to_primitive(self, value, context=None):
return str(value)
def to_native(self, value, context=None):
if isinstance(value, decimal.Decimal):
return value
if not isinstance(value, (str, bool)):
value = str(value)
try:
value = decimal.Decimal(value)
except (TypeError, decimal.InvalidOperation) as exc:
raise ConversionError(
self.messages["number_coerce"].format(value, self.number_type.lower())
) from exc
return value
class HashType(StringType):
MESSAGES = {
"hash_length": _("Hash value is wrong length."),
"hash_hex": _("Hash value is not hexadecimal."),
}
LENGTH = -1
def _mock(self, context=None):
return random_string(self.LENGTH, string.hexdigits)
def to_native(self, value, context=None):
value = super().to_native(value, context)
if len(value) != self.LENGTH:
raise ValidationError(self.messages["hash_length"])
try:
int(value, 16)
except ValueError as exc:
raise ConversionError(self.messages["hash_hex"]) from exc
return value
class MD5Type(HashType):
"""A field that validates input as resembling an MD5 hash."""
LENGTH = 32
class SHA1Type(HashType):
"""A field that validates input as resembling an SHA1 hash."""
LENGTH = 40
class BooleanType(BaseType):
"""A boolean field type. In addition to ``True`` and ``False``, coerces these
values:
+ For ``True``: "True", "true", "1"
+ For ``False``: "False", "false", "0"
"""
primitive_type = bool
native_type = bool
TRUE_VALUES = ("True", "true", "1")
FALSE_VALUES = ("False", "false", "0")
def __init__(self, **kwargs):
"""Create a bool field."""
super().__init__(**kwargs)
def _mock(self, context=None):
return random.choice([True, False])
def to_native(self, value, context=None):
if isinstance(value, str):
if value in self.TRUE_VALUES:
value = True
elif value in self.FALSE_VALUES:
value = False
elif isinstance(value, int) and value in [0, 1]:
value = bool(value)
if not isinstance(value, bool):
raise ConversionError(_("Must be either true or false."))
return value
class DateType(BaseType):
"""Defaults to converting to and from ISO8601 date values."""
primitive_type = str
native_type = datetime.date
SERIALIZED_FORMAT = "%Y-%m-%d"
MESSAGES = {
"parse": _("Could not parse {0}. Should be ISO 8601 (YYYY-MM-DD)."),
"parse_formats": _("Could not parse {0}. Valid formats: {1}"),
}
def __init__(self, formats=None, **kwargs):
"""Create a datetime.date field."""
if formats:
self.formats = listify(formats)
self.conversion_errmsg = self.MESSAGES["parse_formats"]
else:
self.formats = ["%Y-%m-%d"]
self.conversion_errmsg = self.MESSAGES["parse"]
self.serialized_format = self.SERIALIZED_FORMAT
super().__init__(**kwargs)
def _mock(self, context=None):
return datetime.date(
year=random.randrange(600) + 1900,
month=random.randrange(12) + 1,
day=random.randrange(28) + 1,
)
def to_native(self, value, context=None):
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
for fmt in self.formats:
try:
return datetime.datetime.strptime(value, fmt).date()
except (ValueError, TypeError):
continue
raise ConversionError(
self.conversion_errmsg.format(value, ", ".join(self.formats))
)
def to_primitive(self, value, context=None):
return value.strftime(self.serialized_format)
class DateTimeType(BaseType):
"""A field that holds a combined date and time value.
The built-in parser accepts input values conforming to the ISO 8601 format
``<YYYY>-<MM>-<DD>T<hh>:<mm>[:<ss.ssssss>][<z>]``. A space may be substituted
for the delimiter ``T``. The time zone designator ``<z>`` may be either ``Z``
or ``±<hh>[:][<mm>]``.
Values are stored as standard ``datetime.datetime`` instances with the time zone
offset in the ``tzinfo`` component if available. Raw values that do not specify a time
zone will be converted to naive ``datetime`` objects unless ``tzd='utc'`` is in effect.
Unix timestamps are also valid input values and will be converted to UTC datetimes.
:param formats:
(Optional) A value or iterable of values suitable as ``datetime.datetime.strptime`` format
strings, for example ``('%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f')``. If the parameter is
present, ``strptime()`` will be used for parsing instead of the built-in parser.
:param serialized_format:
The output format suitable for Python ``strftime``. Default: ``'%Y-%m-%dT%H:%M:%S.%f%z'``
:param parser:
(Optional) An external function to use for parsing instead of the built-in parser. It should
return a ``datetime.datetime`` instance.
:param tzd:
Sets the time zone policy.
Default: ``'allow'``
============== ======================================================================
``'require'`` Values must specify a time zone.
``'allow'`` Values both with and without a time zone designator are allowed.
``'utc'`` Like ``allow``, but values with no time zone information are assumed
to be in UTC.
``'reject'`` Values must not specify a time zone. This also prohibits timestamps.
============== ======================================================================
:param convert_tz:
Indicates whether values with a time zone designator should be automatically converted to UTC.
Default: ``False``
* ``True``: Convert the datetime to UTC based on its time zone offset.
* ``False``: Don't convert. Keep the original time and offset intact.
:param drop_tzinfo:
Can be set to automatically remove the ``tzinfo`` objects. This option should generally
be used in conjunction with the ``convert_tz`` option unless you only care about local
wall clock times. Default: ``False``
* ``True``: Discard the ``tzinfo`` components and make naive ``datetime`` objects instead.
* ``False``: Preserve the ``tzinfo`` components if present.
"""
primitive_type: Type[Any] = str
native_type = datetime.datetime
SERIALIZED_FORMAT = "%Y-%m-%dT%H:%M:%S.%f%z"
MESSAGES = {
"parse": _("Could not parse {0}. Should be ISO 8601 or timestamp."),
"parse_formats": _("Could not parse {0}. Valid formats: {1}"),
"parse_external": _("Could not parse {0}."),
"parse_tzd_require": _("Could not parse {0}. Time zone offset required."),
"parse_tzd_reject": _("Could not parse {0}. Time zone offset not allowed."),
"tzd_require": _("Could not convert {0}. Time zone required but not found."),
"tzd_reject": _("Could not convert {0}. Time zone offsets not allowed."),
"validate_tzd_require": _("Time zone information required but not found."),
"validate_tzd_reject": _("Time zone information not allowed."),
"validate_utc_none": _("Time zone must be UTC but was None."),
"validate_utc_wrong": _("Time zone must be UTC."),
}
REGEX = re.compile(
r"""
(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)(?:T|\ )
(?P<hour>\d\d):(?P<minute>\d\d)
(?::(?P<second>\d\d)(?:(?:\.|,)(?P<sec_frac>\d{1,6}))?)?
(?:(?P<tzd_offset>(?P<tzd_sign>[+−-])(?P<tzd_hour>\d\d):?(?P<tzd_minute>\d\d)?)
|(?P<tzd_utc>Z))?$""",
re.X,
)
TIMEDELTA_ZERO = datetime.timedelta(0)
class fixed_timezone(datetime.tzinfo):
def utcoffset(self, dt):
return self.offset
def fromutc(self, dt):
return dt + self.offset
def dst(self, dt):
return None
def tzname(self, dt):
return self.str
def __str__(self):
return self.str
def __repr__(self, info=""):
return f"{type(self).__name__}({info})"
class utc_timezone(fixed_timezone):
offset = datetime.timedelta(0)
name = str = "UTC"
class offset_timezone(fixed_timezone):
def __init__(self, hours=0, minutes=0):
self.offset = datetime.timedelta(hours=hours, minutes=minutes)
total_seconds = self.offset.days * 86400 + self.offset.seconds
self.str = "{0:s}{1:02d}:{2:02d}".format(
"+" if total_seconds >= 0 else "-",
int(abs(total_seconds) / 3600),
int(abs(total_seconds) % 3600 / 60),
)
def __repr__(self):
return DateTimeType.fixed_timezone.__repr__(self, self.str)
UTC = utc_timezone()
EPOCH = datetime.datetime(1970, 1, 1, tzinfo=UTC)
def __init__(
self,
formats=None,
serialized_format=None,
parser=None,
tzd="allow",
convert_tz=False,
drop_tzinfo=False,
**kwargs,
):
"""Create a datetime.datetime field."""
if tzd not in ("require", "allow", "utc", "reject"):
raise ValueError(
"DateTimeType.__init__() got an invalid value for parameter 'tzd'"
)
self.formats = listify(formats)
self.serialized_format = serialized_format or self.SERIALIZED_FORMAT
self.parser = parser
self.tzd = tzd
self.convert_tz = convert_tz
self.drop_tzinfo = drop_tzinfo
super().__init__(**kwargs)
def _mock(self, context=None):
dt = datetime.datetime(
year=random.randrange(600) + 1900,
month=random.randrange(12) + 1,
day=random.randrange(28) + 1,
hour=random.randrange(24),
minute=random.randrange(60),
second=random.randrange(60),
microsecond=random.randrange(1000000),
)
if (
self.tzd == "reject"
or self.drop_tzinfo
or self.tzd == "allow"
and random.randrange(2)
):
return dt
if self.convert_tz:
return dt.replace(tzinfo=self.UTC)
return dt.replace(
tzinfo=self.offset_timezone(
hours=random.randrange(-12, 15), minutes=random.choice([0, 30, 45])
)
)
def to_native(self, value, context=None):
if isinstance(value, datetime.datetime):
if value.tzinfo is None:
if not self.drop_tzinfo:
if self.tzd == "require":
raise ConversionError(
self.messages["tzd_require"].format(value)
)
if self.tzd == "utc":
value = value.replace(tzinfo=self.UTC)
else:
if self.tzd == "reject":
raise ConversionError(self.messages["tzd_reject"].format(value))
if self.convert_tz:
value = value.astimezone(self.UTC)
if self.drop_tzinfo:
value = value.replace(tzinfo=None)
return value
if self.formats:
# Delegate to datetime.datetime.strptime() using provided format strings.
for fmt in self.formats:
try:
dt = datetime.datetime.strptime(value, fmt)
break
except (ValueError, TypeError):
continue
else:
raise ConversionError(
self.messages["parse_formats"].format(
value, ", ".join(self.formats)
)
)
elif self.parser:
# Delegate to external parser.
try:
dt = self.parser(value)
except Exception as exc:
raise ConversionError(
self.messages["parse_external"].format(value)
) from exc
else:
# Use built-in parser.
try:
value = float(value)
except ValueError:
dt = self.from_string(value)
except TypeError as exc:
raise ConversionError(self.messages["parse"].format(value)) from exc
else:
dt = self.from_timestamp(value)
if not dt:
raise ConversionError(self.messages["parse"].format(value))
if dt.tzinfo is None:
if self.tzd == "require":
raise ConversionError(self.messages["parse_tzd_require"].format(value))
if self.tzd == "utc" and not self.drop_tzinfo:
dt = dt.replace(tzinfo=self.UTC)
else:
if self.tzd == "reject":
raise ConversionError(self.messages["parse_tzd_reject"].format(value))
if self.convert_tz:
dt = dt.astimezone(self.UTC)
if self.drop_tzinfo:
dt = dt.replace(tzinfo=None)
return dt
def from_string(self, value):
match = self.REGEX.match(value)
if not match:
return None
parts = dict(((k, v) for k, v in match.groupdict().items() if v is not None))
def p(name):
return int(parts.get(name, 0))
microsecond = p("sec_frac") and p("sec_frac") * 10 ** (
6 - len(parts["sec_frac"])
)
if "tzd_utc" in parts:
tz = self.UTC
elif "tzd_offset" in parts:
tz_sign = 1 if parts["tzd_sign"] == "+" else -1
tz_offset = (p("tzd_hour") * 60 + p("tzd_minute")) * tz_sign
if tz_offset == 0:
tz = self.UTC
else:
tz = self.offset_timezone(minutes=tz_offset)
else:
tz = None
try:
return datetime.datetime(
p("year"),
p("month"),
p("day"),
p("hour"),
p("minute"),
p("second"),
microsecond,
tz,
)
except (ValueError, TypeError):
return None
def from_timestamp(self, value):
try:
return datetime.datetime(1970, 1, 1, tzinfo=self.UTC) + datetime.timedelta(
seconds=value
)
except (ValueError, TypeError):
return None
def to_primitive(self, value, context=None):
if callable(self.serialized_format):
return self.serialized_format(value)
return value.strftime(self.serialized_format)
def validate_tz(self, value, context=None):
if value.tzinfo is None:
if not self.drop_tzinfo:
if self.tzd == "require":
raise ValidationError(self.messages["validate_tzd_require"])
if self.tzd == "utc":
raise ValidationError(self.messages["validate_utc_none"])
else:
if self.drop_tzinfo:
raise ValidationError(self.messages["validate_tzd_reject"])
if self.tzd == "reject":
raise ValidationError(self.messages["validate_tzd_reject"])
if self.convert_tz and value.tzinfo.utcoffset(value) != self.TIMEDELTA_ZERO:
raise ValidationError(self.messages["validate_utc_wrong"])
class UTCDateTimeType(DateTimeType):
"""A variant of ``DateTimeType`` that normalizes everything to UTC and stores values
as naive ``datetime`` instances. By default sets ``tzd='utc'``, ``convert_tz=True``,
and ``drop_tzinfo=True``. The standard export format always includes the UTC time
zone designator ``"Z"``.
"""
SERIALIZED_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
def __init__(
self,
formats=None,
parser=None,
tzd="utc",
convert_tz=True,
drop_tzinfo=True,
**kwargs,
):
"""Create a datetime.datetime in UTC field."""
super().__init__(
formats=formats,
parser=parser,
tzd=tzd,
convert_tz=convert_tz,
drop_tzinfo=drop_tzinfo,
**kwargs,
)
class TimestampType(DateTimeType):
"""A variant of ``DateTimeType`` that exports itself as a Unix timestamp
instead of an ISO 8601 string. Always sets ``tzd='require'`` and
``convert_tz=True``.
"""
primitive_type = float
def __init__(self, formats=None, parser=None, drop_tzinfo=False, **kwargs):
"""Create a datetime.datetime as a float field."""
super().__init__(
formats=formats,
parser=parser,
tzd="require",
convert_tz=True,
drop_tzinfo=drop_tzinfo,
**kwargs,
)
def to_primitive(self, value, context=None):
if value.tzinfo is None:
value = value.replace(tzinfo=self.UTC)
else:
value = value.astimezone(self.UTC)
delta = value - self.EPOCH
return delta.total_seconds()
class TimedeltaType(BaseType):
"""Converts Python Timedelta objects into the corresponding value in seconds."""
primitive_type = float
native_type = datetime.timedelta
MESSAGES = {
"convert": _("Couldn't interpret '{0}' value as Timedelta."),
}
DAYS = "days"
SECONDS = "seconds"
MICROSECONDS = "microseconds"
MILLISECONDS = "milliseconds"
MINUTES = "minutes"
HOURS = "hours"
WEEKS = "weeks"
def __init__(self, precision="seconds", **kwargs):
"""Create a datetime.timedelta field."""
precision = precision.lower()
units = (
self.DAYS,
self.SECONDS,
self.MICROSECONDS,
self.MILLISECONDS,
self.MINUTES,
self.HOURS,
self.WEEKS,
)
if precision not in units:
raise ValueError(
"TimedeltaType.__init__() got an invalid value for parameter 'precision'"
)
self.precision = precision
super().__init__(**kwargs)
def _mock(self, context=None):
return datetime.timedelta(seconds=random.random() * 1000)
def to_native(self, value, context=None):
if isinstance(value, datetime.timedelta):
return value
try:
return datetime.timedelta(**{self.precision: float(value)})
except (ValueError, TypeError) as exc:
raise ConversionError(self.messages["convert"].format(value)) from exc
def to_primitive(self, value, context=None):
base_unit = datetime.timedelta(**{self.precision: 1})
return int(value.total_seconds() / base_unit.total_seconds())
class GeoPointType(BaseType):
"""A list storing a latitude and longitude."""
primitive_type = list
native_type = list
MESSAGES = {
"point_min": _("{0} value {1} should be greater than or equal to {2}."),
"point_max": _("{0} value {1} should be less than or equal to {2}."),
}
def _mock(self, context=None):
return (random.randrange(-90, 90), random.randrange(-180, 180))
@classmethod
def _normalize(cls, value):
if isinstance(value, dict):
return list(value.values())
return list(value)
def to_native(self, value, context=None):
"""Make sure that a geo-value is of type (x, y)"""
if not isinstance(value, (tuple, list, dict)):
raise ConversionError(
_("GeoPointType can only accept tuples, lists, or dicts")
)
elements = self._normalize(value)
if not len(elements) == 2:
raise ConversionError(_("Value must be a two-dimensional point"))
if not all(isinstance(v, (float, int)) for v in elements):
raise ConversionError(_("Both values in point must be float or int"))
return value
def validate_range(self, value, context=None):
latitude, longitude = self._normalize(value)
if latitude < -90:
raise ValidationError(
self.messages["point_min"].format("Latitude", latitude, "-90")
)
if latitude > 90:
raise ValidationError(
self.messages["point_max"].format("Latitude", latitude, "90")
)
if longitude < -180:
raise ValidationError(
self.messages["point_min"].format("Longitude", longitude, -180)
)
if longitude > 180:
raise ValidationError(
self.messages["point_max"].format("Longitude", longitude, 180)
)
class MultilingualStringType(BaseType):
"""
A multilanguage string field, stored as a dict with {'locale': 'localized_value'}.
Minimum and maximum lengths apply to each of the localized values.
At least one of ``default_locale`` or ``context.app_data['locale']`` must be defined
when calling ``.to_primitive``.
"""
primitive_type = str
native_type = str
allow_casts = (int, bytes)
MESSAGES = {
"convert": _("Couldn't interpret value as string."),
"max_length": _("String value in locale {0} is too long."),
"min_length": _("String value in locale {0} is too short."),
"locale_not_found": _("No requested locale was available."),
"no_locale": _("No default or explicit locales were given."),
"regex_locale": _("Name of locale {0} did not match validation regex."),
"regex_localized": _(
"String value in locale {0} did not match validation regex."
),
}
LOCALE_REGEX = r"^[a-z]{2}(:?_[A-Z]{2})?$"
def __init__(
self,
regex=None,
max_length=None,
min_length=None,
default_locale=None,
locale_regex=LOCALE_REGEX,
**kwargs,
):
self.regex = re.compile(regex) if regex else None
self.max_length = max_length
self.min_length = min_length
self.default_locale = default_locale
self.locale_regex = re.compile(locale_regex) if locale_regex else None
super().__init__(**kwargs)
def _mock(self, context=None):
return random_string(get_value_in(self.min_length, self.max_length))
def to_native(self, value, context=None):
"""Make sure a MultilingualStringType value is a dict or None."""
if not (value is None or isinstance(value, dict)):
raise ConversionError(_("Value must be a dict or None"))
return value
def to_primitive(self, value, context=None):
"""
Use a combination of ``default_locale`` and ``context.app_data['locale']`` to return
the best localized string.
"""
if value is None:
return None
context_locale = None
if context and "locale" in context.app_data:
context_locale = context.app_data["locale"]
# Build a list of all possible locales to try
possible_locales = []
for locale in (context_locale, self.default_locale):
if not locale:
continue
if isinstance(locale, str):
possible_locales.append(locale)
else:
possible_locales.extend(locale)
if not possible_locales:
raise ConversionError(self.messages["no_locale"])
for locale in possible_locales:
if locale in value:
localized = value[locale]
break
else:
raise ConversionError(self.messages["locale_not_found"])
if not isinstance(localized, str):
if isinstance(localized, self.allow_casts):
if isinstance(localized, bytes):
localized = str(localized, "utf-8")
else:
localized = str(localized)
else:
raise ConversionError(self.messages["convert"])
return localized
def validate_length(self, value, context=None):
for locale, localized in value.items():
len_of_value = len(localized) if localized else 0
if self.max_length is not None and len_of_value > self.max_length:
raise ValidationError(self.messages["max_length"].format(locale))
if self.min_length is not None and len_of_value < self.min_length:
raise ValidationError(self.messages["min_length"].format(locale))
def validate_regex(self, value, context=None):
if self.regex is None and self.locale_regex is None:
return
for locale, localized in value.items():
if self.regex is not None and self.regex.match(localized) is None:
raise ValidationError(self.messages["regex_localized"].format(locale))
if (
self.locale_regex is not None
and self.locale_regex.match(locale) is None
):
raise ValidationError(self.messages["regex_locale"].format(locale))
| 0.771715 | 0.195479 |
import copy
from functools import partial
from types import FunctionType
from ..exceptions import UndefinedValueError
from ..undefined import Undefined
__all__ = ["calculated", "serializable", "Serializable"]
def serializable(arg=None, **kwargs):
"""A serializable is a way to define dynamic serializable fields that are
derived from other fields.
>>> from schematics.models import serializable
>>> class Location(Model):
... country_code = StringType()
... @serializable
... def country_name(self):
... return {'us': 'United States'}[self.country_code]
...
>>> location = Location({'country_code': 'us'})
>>> location.serialize()
{'country_name': 'United States', 'country_code': 'us'}
>>>
:param type:
A custom subclass of `BaseType` for enforcing a certain type
on serialization.
:param serialized_name:
The name of this field in the serialized output.
"""
from .base import BaseType, TypeMeta
if isinstance(arg, FunctionType):
decorator = True
func = arg
serialized_type = BaseType
elif arg is None or isinstance(arg, (BaseType, TypeMeta)):
decorator = False
serialized_type = arg or kwargs.pop("type", BaseType)
else:
raise TypeError("The argument to 'serializable' must be a function or a type.")
if isinstance(serialized_type, BaseType):
# `serialized_type` is already a type instance,
# so update it with the options found in `kwargs`.
serialized_type._set_export_level(
kwargs.pop("export_level", None), kwargs.pop("serialize_when_none", None)
)
for name, value in kwargs.items():
setattr(serialized_type, name, value)
else:
serialized_type = serialized_type(**kwargs)
if decorator:
return Serializable(type=serialized_type, fget=func)
return partial(Serializable, type=serialized_type)
def calculated(type, fget, fset=None):
return Serializable(type=type, fget=fget, fset=fset)
class Serializable:
def __init__(self, fget, type, fset=None):
self.type = type
self.fget = fget
self.fset = fset
def __getattr__(self, name):
return getattr(self.type, name)
def __get__(self, instance, cls):
if instance is None:
return self
value = self.fget(instance)
if value is Undefined:
raise UndefinedValueError(instance, self.name)
return value
def __set__(self, instance, value):
if self.fset is None:
raise AttributeError(f"can't set attribute {self.name}")
value = self.type.pre_setattr(value)
self.fset(instance, value)
def setter(self, fset):
self.fset = fset
return self
def _repr_info(self):
return self.type.__class__.__name__
def __deepcopy__(self, memo):
return self.__class__(self.fget, type=copy.deepcopy(self.type), fset=self.fset)
def __repr__(self):
type_ = f"{self.__class__.__name__}({self._repr_info() or ''}) instance"
model = f" on {self.owner_model.__name__}" if self.owner_model else ""
field = f" as '{self.name}'" if self.name else ""
return f"<{type_}{model}{field}>"
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/types/serializable.py
|
serializable.py
|
import copy
from functools import partial
from types import FunctionType
from ..exceptions import UndefinedValueError
from ..undefined import Undefined
__all__ = ["calculated", "serializable", "Serializable"]
def serializable(arg=None, **kwargs):
"""A serializable is a way to define dynamic serializable fields that are
derived from other fields.
>>> from schematics.models import serializable
>>> class Location(Model):
... country_code = StringType()
... @serializable
... def country_name(self):
... return {'us': 'United States'}[self.country_code]
...
>>> location = Location({'country_code': 'us'})
>>> location.serialize()
{'country_name': 'United States', 'country_code': 'us'}
>>>
:param type:
A custom subclass of `BaseType` for enforcing a certain type
on serialization.
:param serialized_name:
The name of this field in the serialized output.
"""
from .base import BaseType, TypeMeta
if isinstance(arg, FunctionType):
decorator = True
func = arg
serialized_type = BaseType
elif arg is None or isinstance(arg, (BaseType, TypeMeta)):
decorator = False
serialized_type = arg or kwargs.pop("type", BaseType)
else:
raise TypeError("The argument to 'serializable' must be a function or a type.")
if isinstance(serialized_type, BaseType):
# `serialized_type` is already a type instance,
# so update it with the options found in `kwargs`.
serialized_type._set_export_level(
kwargs.pop("export_level", None), kwargs.pop("serialize_when_none", None)
)
for name, value in kwargs.items():
setattr(serialized_type, name, value)
else:
serialized_type = serialized_type(**kwargs)
if decorator:
return Serializable(type=serialized_type, fget=func)
return partial(Serializable, type=serialized_type)
def calculated(type, fget, fset=None):
return Serializable(type=type, fget=fget, fset=fset)
class Serializable:
def __init__(self, fget, type, fset=None):
self.type = type
self.fget = fget
self.fset = fset
def __getattr__(self, name):
return getattr(self.type, name)
def __get__(self, instance, cls):
if instance is None:
return self
value = self.fget(instance)
if value is Undefined:
raise UndefinedValueError(instance, self.name)
return value
def __set__(self, instance, value):
if self.fset is None:
raise AttributeError(f"can't set attribute {self.name}")
value = self.type.pre_setattr(value)
self.fset(instance, value)
def setter(self, fset):
self.fset = fset
return self
def _repr_info(self):
return self.type.__class__.__name__
def __deepcopy__(self, memo):
return self.__class__(self.fget, type=copy.deepcopy(self.type), fset=self.fset)
def __repr__(self):
type_ = f"{self.__class__.__name__}({self._repr_info() or ''}) instance"
model = f" on {self.owner_model.__name__}" if self.owner_model else ""
field = f" as '{self.name}'" if self.name else ""
return f"<{type_}{model}{field}>"
| 0.747063 | 0.128225 |
import inspect
from collections import OrderedDict
from ..exceptions import ConversionError
from ..transforms import get_import_context
from ..translator import _
from .base import BaseType
__all__ = ["UnionType"]
def _valid_init_args(type_):
args = set()
for cls in type_.__mro__:
init_args = inspect.getfullargspec(cls.__init__).args[1:]
args.update(init_args)
if cls is BaseType:
break
return args
def _filter_kwargs(valid_args, kwargs):
return dict((k, v) for k, v in kwargs.items() if k in valid_args)
class UnionType(BaseType):
types = None
MESSAGES = {
"convert": _("Couldn't interpret value '{0}' as any of {1}."),
}
_baseclass_args = _valid_init_args(BaseType)
def __init__(self, types=None, resolver=None, **kwargs):
self._types = OrderedDict()
types = types or self.types
if resolver:
self.resolve = resolver
for type_ in types:
if isinstance(type_, type) and issubclass(type_, BaseType):
type_ = type_(**_filter_kwargs(_valid_init_args(type_), kwargs))
elif not isinstance(type_, BaseType):
raise TypeError(
f"Got '{type_.__class__.__name__}' instance instead of a Schematics type"
)
self._types[type_.__class__] = type_
self.typenames = tuple((cls.__name__ for cls in self._types))
super().__init__(**_filter_kwargs(self._baseclass_args, kwargs))
def resolve(self, value, context):
for field in self._types.values():
try:
value = field.convert(value, context)
except ConversionError:
pass
else:
return field, value
return None
def _resolve(self, value, context):
response = self.resolve(value, context)
if isinstance(response, type):
field = self._types[response]
try:
response = field, field.convert(value, context)
except ConversionError:
pass
if isinstance(response, tuple):
return response
raise ConversionError(self.messages["convert"].format(value, self.typenames))
def convert(self, value, context=None):
context = context or get_import_context()
field, native_value = self._resolve(value, context)
return native_value
def validate(self, value, context=None):
field, _ = self._resolve(value, context)
return field.validate(value, context)
def _export(self, value, format, context=None):
field, _ = self._resolve(value, context)
return field._export(value, format, context)
def to_native(self, value, context=None):
field, _ = self._resolve(value, context)
return field.to_native(value, context)
def to_primitive(self, value, context=None):
field, _ = self._resolve(value, context)
return field.to_primitive(value, context)
|
schematics-py310-plus
|
/schematics-py310-plus-0.0.4.tar.gz/schematics-py310-plus-0.0.4/schematics/types/union.py
|
union.py
|
import inspect
from collections import OrderedDict
from ..exceptions import ConversionError
from ..transforms import get_import_context
from ..translator import _
from .base import BaseType
__all__ = ["UnionType"]
def _valid_init_args(type_):
args = set()
for cls in type_.__mro__:
init_args = inspect.getfullargspec(cls.__init__).args[1:]
args.update(init_args)
if cls is BaseType:
break
return args
def _filter_kwargs(valid_args, kwargs):
return dict((k, v) for k, v in kwargs.items() if k in valid_args)
class UnionType(BaseType):
types = None
MESSAGES = {
"convert": _("Couldn't interpret value '{0}' as any of {1}."),
}
_baseclass_args = _valid_init_args(BaseType)
def __init__(self, types=None, resolver=None, **kwargs):
self._types = OrderedDict()
types = types or self.types
if resolver:
self.resolve = resolver
for type_ in types:
if isinstance(type_, type) and issubclass(type_, BaseType):
type_ = type_(**_filter_kwargs(_valid_init_args(type_), kwargs))
elif not isinstance(type_, BaseType):
raise TypeError(
f"Got '{type_.__class__.__name__}' instance instead of a Schematics type"
)
self._types[type_.__class__] = type_
self.typenames = tuple((cls.__name__ for cls in self._types))
super().__init__(**_filter_kwargs(self._baseclass_args, kwargs))
def resolve(self, value, context):
for field in self._types.values():
try:
value = field.convert(value, context)
except ConversionError:
pass
else:
return field, value
return None
def _resolve(self, value, context):
response = self.resolve(value, context)
if isinstance(response, type):
field = self._types[response]
try:
response = field, field.convert(value, context)
except ConversionError:
pass
if isinstance(response, tuple):
return response
raise ConversionError(self.messages["convert"].format(value, self.typenames))
def convert(self, value, context=None):
context = context or get_import_context()
field, native_value = self._resolve(value, context)
return native_value
def validate(self, value, context=None):
field, _ = self._resolve(value, context)
return field.validate(value, context)
def _export(self, value, format, context=None):
field, _ = self._resolve(value, context)
return field._export(value, format, context)
def to_native(self, value, context=None):
field, _ = self._resolve(value, context)
return field.to_native(value, context)
def to_primitive(self, value, context=None):
field, _ = self._resolve(value, context)
return field.to_primitive(value, context)
| 0.562777 | 0.132571 |
import inspect
from collections import namedtuple
from schematics import models
from schematics import types
name = 'schematics_to_swagger'
DEFAULT_SWAGGER_VERSION = 2
SwaggerProp = namedtuple('SwaggerProp', ['name', 'func'], defaults=(None, lambda x: x))
_KNOWN_PROPS = {
'max_length': SwaggerProp('maxLength'),
'min_length': SwaggerProp('minLength'),
'min_value': SwaggerProp('minimum'),
'max_value': SwaggerProp('maximum'),
'regex': SwaggerProp('pattern', lambda x: x.pattern),
'choices': SwaggerProp('enum'),
}
def _map_type_properties(t):
props = {}
for k, v in _KNOWN_PROPS.items():
prop_value = getattr(t, k, None)
if prop_value:
props[v.name] = v.func(prop_value)
# passthrough metadata items
for k, v in t.metadata.items():
props[k] = v
return props
_DATATYPES = {
# Base types
types.BooleanType: lambda t: dict(type='boolean', **_map_type_properties(t)),
types.IntType: lambda t: dict(type='integer', format='int32', **_map_type_properties(t)),
types.LongType: lambda t: dict(type='integer', format='int64', **_map_type_properties(t)),
types.FloatType: lambda t: dict(type='number', format='float', **_map_type_properties(t)),
types.DecimalType: lambda t: dict(type='number', format='double', **_map_type_properties(t)),
types.StringType: lambda t: dict(type='string', **_map_type_properties(t)),
types.UUIDType: lambda t: dict(type='string', format='uuid', **_map_type_properties(t)),
types.MD5Type: lambda t: dict(type='string', format='md5', **_map_type_properties(t)),
types.SHA1Type: lambda t: dict(type='string', format='sha1', **_map_type_properties(t)),
types.DateType: lambda t: dict(type='string', format='date', **_map_type_properties(t)),
types.DateTimeType: lambda t: dict(type='string', format='date-time', **_map_type_properties(t)),
# Net types
types.EmailType: lambda t: dict(type='string', format='email', **_map_type_properties(t)),
types.URLType: lambda t: dict(type='string', format='uri', **_map_type_properties(t)),
# Compound types
types.ModelType: lambda t: dict({'$ref': '#/definitions/%s' % t.model_name}, **_map_type_properties(t)),
types.ListType: lambda t: dict(type='array', items=_map_schematics_type(t.field), **_map_type_properties(t))
}
def _map_schematics_type(t):
if t.__class__ in _DATATYPES:
return _DATATYPES[t.__class__](t)
def model_to_definition(model):
properties = {}
required = []
for field_name, field in model.fields.items():
if field_name.startswith(f'_{model.__name__}'):
continue # Exclude private fields
properties[field_name] = _map_schematics_type(field)
if getattr(field, 'required'):
required.append(field_name)
result_info = {
'type': 'object',
'title': model.__name__,
'description': model.__doc__,
'properties': properties
}
if required:
result_info['required'] = required
return result_info
def _build_model_type_v3(t):
ref = {'$ref': f'#/components/schemas/{t.model_name}'}
if t.metadata and not getattr(t, 'required', False):
field = {'allOf': [ref], **_map_type_properties(t)}
else:
field = {**ref, **_map_type_properties(t)}
return field
def version_dependencies(version):
if version == 3:
global _DATATYPES
_DATATYPES.update({
types.ModelType: _build_model_type_v3
})
def read_models_from_module(module, version=DEFAULT_SWAGGER_VERSION):
version_dependencies(version)
results = {}
for item in dir(module):
if item.startswith('_'):
continue # Skip private stuff
obj = getattr(module, item)
if inspect.isclass(obj) and issubclass(obj, models.Model) and obj.__module__ == module.__name__:
results[item] = model_to_definition(obj)
return results
|
schematics-to-swagger
|
/schematics_to_swagger-1.4.7-py3-none-any.whl/schematics_to_swagger/__init__.py
|
__init__.py
|
import inspect
from collections import namedtuple
from schematics import models
from schematics import types
name = 'schematics_to_swagger'
DEFAULT_SWAGGER_VERSION = 2
SwaggerProp = namedtuple('SwaggerProp', ['name', 'func'], defaults=(None, lambda x: x))
_KNOWN_PROPS = {
'max_length': SwaggerProp('maxLength'),
'min_length': SwaggerProp('minLength'),
'min_value': SwaggerProp('minimum'),
'max_value': SwaggerProp('maximum'),
'regex': SwaggerProp('pattern', lambda x: x.pattern),
'choices': SwaggerProp('enum'),
}
def _map_type_properties(t):
props = {}
for k, v in _KNOWN_PROPS.items():
prop_value = getattr(t, k, None)
if prop_value:
props[v.name] = v.func(prop_value)
# passthrough metadata items
for k, v in t.metadata.items():
props[k] = v
return props
_DATATYPES = {
# Base types
types.BooleanType: lambda t: dict(type='boolean', **_map_type_properties(t)),
types.IntType: lambda t: dict(type='integer', format='int32', **_map_type_properties(t)),
types.LongType: lambda t: dict(type='integer', format='int64', **_map_type_properties(t)),
types.FloatType: lambda t: dict(type='number', format='float', **_map_type_properties(t)),
types.DecimalType: lambda t: dict(type='number', format='double', **_map_type_properties(t)),
types.StringType: lambda t: dict(type='string', **_map_type_properties(t)),
types.UUIDType: lambda t: dict(type='string', format='uuid', **_map_type_properties(t)),
types.MD5Type: lambda t: dict(type='string', format='md5', **_map_type_properties(t)),
types.SHA1Type: lambda t: dict(type='string', format='sha1', **_map_type_properties(t)),
types.DateType: lambda t: dict(type='string', format='date', **_map_type_properties(t)),
types.DateTimeType: lambda t: dict(type='string', format='date-time', **_map_type_properties(t)),
# Net types
types.EmailType: lambda t: dict(type='string', format='email', **_map_type_properties(t)),
types.URLType: lambda t: dict(type='string', format='uri', **_map_type_properties(t)),
# Compound types
types.ModelType: lambda t: dict({'$ref': '#/definitions/%s' % t.model_name}, **_map_type_properties(t)),
types.ListType: lambda t: dict(type='array', items=_map_schematics_type(t.field), **_map_type_properties(t))
}
def _map_schematics_type(t):
if t.__class__ in _DATATYPES:
return _DATATYPES[t.__class__](t)
def model_to_definition(model):
properties = {}
required = []
for field_name, field in model.fields.items():
if field_name.startswith(f'_{model.__name__}'):
continue # Exclude private fields
properties[field_name] = _map_schematics_type(field)
if getattr(field, 'required'):
required.append(field_name)
result_info = {
'type': 'object',
'title': model.__name__,
'description': model.__doc__,
'properties': properties
}
if required:
result_info['required'] = required
return result_info
def _build_model_type_v3(t):
ref = {'$ref': f'#/components/schemas/{t.model_name}'}
if t.metadata and not getattr(t, 'required', False):
field = {'allOf': [ref], **_map_type_properties(t)}
else:
field = {**ref, **_map_type_properties(t)}
return field
def version_dependencies(version):
if version == 3:
global _DATATYPES
_DATATYPES.update({
types.ModelType: _build_model_type_v3
})
def read_models_from_module(module, version=DEFAULT_SWAGGER_VERSION):
version_dependencies(version)
results = {}
for item in dir(module):
if item.startswith('_'):
continue # Skip private stuff
obj = getattr(module, item)
if inspect.isclass(obj) and issubclass(obj, models.Model) and obj.__module__ == module.__name__:
results[item] = model_to_definition(obj)
return results
| 0.530236 | 0.332608 |
==============
schematics-xml
==============
Python schematics_ models for converting to and from XML.
.. image:: https://travis-ci.org/alexhayes/schematics-xml.png?branch=master
:target: https://travis-ci.org/alexhayes/schematics-xml
:alt: Build Status
.. image:: https://landscape.io/github/alexhayes/schematics-xml/master/landscape.png
:target: https://landscape.io/github/alexhayes/schematics-xml/
:alt: Code Health
.. image:: https://codecov.io/github/alexhayes/schematics-xml/coverage.svg?branch=master
:target: https://codecov.io/github/alexhayes/schematics-xml?branch=master
:alt: Code Coverage
.. image:: https://readthedocs.org/projects/schematics-xml/badge/
:target: http://schematics-xml.readthedocs.org/en/latest/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Supported Python versions
Install
-------
.. code-block:: bash
pip install schematics-xml
Example Usage
-------------
Simply inherit XMLModel.
.. code-block:: python
from schematics_xml import XMLModel
class Person(XMLModel):
name = StringType()
john = Person(dict(name='John'))
xml = john.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<person>
<name>John</name>
</person>
And back the other way;
.. code-block:: python
john = Person.from_xml(xml)
Author
------
Alex Hayes <[email protected]>
.. _schematics: https://schematics.readthedocs.io
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/README.rst
|
README.rst
|
==============
schematics-xml
==============
Python schematics_ models for converting to and from XML.
.. image:: https://travis-ci.org/alexhayes/schematics-xml.png?branch=master
:target: https://travis-ci.org/alexhayes/schematics-xml
:alt: Build Status
.. image:: https://landscape.io/github/alexhayes/schematics-xml/master/landscape.png
:target: https://landscape.io/github/alexhayes/schematics-xml/
:alt: Code Health
.. image:: https://codecov.io/github/alexhayes/schematics-xml/coverage.svg?branch=master
:target: https://codecov.io/github/alexhayes/schematics-xml?branch=master
:alt: Code Coverage
.. image:: https://readthedocs.org/projects/schematics-xml/badge/
:target: http://schematics-xml.readthedocs.org/en/latest/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Supported Python versions
Install
-------
.. code-block:: bash
pip install schematics-xml
Example Usage
-------------
Simply inherit XMLModel.
.. code-block:: python
from schematics_xml import XMLModel
class Person(XMLModel):
name = StringType()
john = Person(dict(name='John'))
xml = john.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<person>
<name>John</name>
</person>
And back the other way;
.. code-block:: python
john = Person.from_xml(xml)
Author
------
Alex Hayes <[email protected]>
.. _schematics: https://schematics.readthedocs.io
| 0.89128 | 0.513546 |
# Release 0.2.1 - Friday 11 November 15:54:21 AEDT 2016
- Ensure that lists with `None` value aren't turned into `[None]` (#7)
# Release 0.2.0 - Thursday 3 November 23:49:32 AEDT 2016
- Allow user to set XML encoding (#6)
- Added encoding parameter to to_xml
- Changed default encoding to UTF-8.
- Added XMLModel attribute xml_encoding with default 'UTF-8'.
- Added docs detailing how to set the encoding.
- Ensure deeply nested lists are traversed even if the parent is OK. (#5)
- Test schematics serialized_name BaseType feature.
# Release 0.1.2 - Wednesday 2 November 23:13:48 AEDT 2016
- Support lists with a single item in XML being converted to raw_data with a list not dict. (#2)
- Set reports no in pylintrc (#1)
- Removed keyword only args from to_xml function for py 3.3/3.4 support. (#3)
# Release 0.1.1 - Wednesday 2 November 08:02:07 AEDT 2016
- Fixed travis YAML file parse error
- Allow travis failures for pypy and pypy3
- Added pytest-cov
- Fixed pylint issue with __init__ import
- Cleaned up test requirements
# Release 0.1.0 - Wed Nov 2 07:55:01 EST 2016
- Initial release
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/CHANGELOG.md
|
CHANGELOG.md
|
# Release 0.2.1 - Friday 11 November 15:54:21 AEDT 2016
- Ensure that lists with `None` value aren't turned into `[None]` (#7)
# Release 0.2.0 - Thursday 3 November 23:49:32 AEDT 2016
- Allow user to set XML encoding (#6)
- Added encoding parameter to to_xml
- Changed default encoding to UTF-8.
- Added XMLModel attribute xml_encoding with default 'UTF-8'.
- Added docs detailing how to set the encoding.
- Ensure deeply nested lists are traversed even if the parent is OK. (#5)
- Test schematics serialized_name BaseType feature.
# Release 0.1.2 - Wednesday 2 November 23:13:48 AEDT 2016
- Support lists with a single item in XML being converted to raw_data with a list not dict. (#2)
- Set reports no in pylintrc (#1)
- Removed keyword only args from to_xml function for py 3.3/3.4 support. (#3)
# Release 0.1.1 - Wednesday 2 November 08:02:07 AEDT 2016
- Fixed travis YAML file parse error
- Allow travis failures for pypy and pypy3
- Added pytest-cov
- Fixed pylint issue with __init__ import
- Cleaned up test requirements
# Release 0.1.0 - Wed Nov 2 07:55:01 EST 2016
- Initial release
| 0.511229 | 0.238816 |
=====
Usage
=====
Simply inherit ``XMLModel``.
.. code-block:: python
from schematics_xml import XMLModel
class Person(XMLModel):
name = StringType()
john = Person(dict(name='John'))
xml = john.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<person>
<name>John</name>
</person>
And back the other way;
.. code-block:: python
john = Person.from_xml(xml)
Root Node
---------
To set the root node simply define class property ``xml_root``, as follows;
.. code-block:: python
from schematics_xml import XMLModel
class Animal(XMLModel):
kind = StringType()
@property
def xml_root(self):
return self.kind
garfield = Animal(dict(kind='cat'))
xml = garfield.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<cat>
<kind>cat</kind>
</cat>
Encoding
--------
By default the encoding returned :py:meth:`.XMLModel.to_xml` is `UTF-8` however
this can be changed either by setting the `xml_encoding` attribute on the model
or by setting the `encoding` kwarg when calling :py:meth:`.XMLModel.to_xml`.
.. code-block:: python
from schematics_xml import XMLModel
class Animal(XMLModel):
xml_encoding = 'UTF-8'
kind = StringType()
garfield = Animal(dict(kind='cat'))
xml = garfield.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<cat>
<animal>cat</animal>
</cat>
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/usage.rst
|
usage.rst
|
=====
Usage
=====
Simply inherit ``XMLModel``.
.. code-block:: python
from schematics_xml import XMLModel
class Person(XMLModel):
name = StringType()
john = Person(dict(name='John'))
xml = john.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<person>
<name>John</name>
</person>
And back the other way;
.. code-block:: python
john = Person.from_xml(xml)
Root Node
---------
To set the root node simply define class property ``xml_root``, as follows;
.. code-block:: python
from schematics_xml import XMLModel
class Animal(XMLModel):
kind = StringType()
@property
def xml_root(self):
return self.kind
garfield = Animal(dict(kind='cat'))
xml = garfield.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<cat>
<kind>cat</kind>
</cat>
Encoding
--------
By default the encoding returned :py:meth:`.XMLModel.to_xml` is `UTF-8` however
this can be changed either by setting the `xml_encoding` attribute on the model
or by setting the `encoding` kwarg when calling :py:meth:`.XMLModel.to_xml`.
.. code-block:: python
from schematics_xml import XMLModel
class Animal(XMLModel):
xml_encoding = 'UTF-8'
kind = StringType()
garfield = Animal(dict(kind='cat'))
xml = garfield.to_xml()
XML now contains;
.. code-block:: xml
<?xml version='1.0' encoding='UTF-8'?>
<cat>
<animal>cat</animal>
</cat>
| 0.706292 | 0.138928 |
==============
schematics-xml
==============
Python schematics_ models for converting to and from XML.
.. image:: https://travis-ci.org/alexhayes/schematics-xml.png?branch=master
:target: https://travis-ci.org/alexhayes/schematics-xml
:alt: Build Status
.. image:: https://landscape.io/github/alexhayes/schematics-xml/master/landscape.png
:target: https://landscape.io/github/alexhayes/schematics-xml/
:alt: Code Health
.. image:: https://codecov.io/github/alexhayes/schematics-xml/coverage.svg?branch=master
:target: https://codecov.io/github/alexhayes/schematics-xml?branch=master
:alt: Code Coverage
.. image:: https://readthedocs.org/projects/schematics-xml/badge/
:target: http://schematics-xml.readthedocs.org/en/latest/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Supported Python versions
.. image:: https://img.shields.io/pypi/dd/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Downloads
Contents
--------
.. toctree::
:maxdepth: 1
installation
usage
developer
internals/reference/index
License
-------
This software is licensed under the `MIT License`. See the `LICENSE`_.
Author
------
Alex Hayes <[email protected]>
.. _schematics: schematics.readthedocs.org
.. _LICENSE: https://github.com/alexhayes/schematics-xml/blob/master/LICENSE
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/index.rst
|
index.rst
|
==============
schematics-xml
==============
Python schematics_ models for converting to and from XML.
.. image:: https://travis-ci.org/alexhayes/schematics-xml.png?branch=master
:target: https://travis-ci.org/alexhayes/schematics-xml
:alt: Build Status
.. image:: https://landscape.io/github/alexhayes/schematics-xml/master/landscape.png
:target: https://landscape.io/github/alexhayes/schematics-xml/
:alt: Code Health
.. image:: https://codecov.io/github/alexhayes/schematics-xml/coverage.svg?branch=master
:target: https://codecov.io/github/alexhayes/schematics-xml?branch=master
:alt: Code Coverage
.. image:: https://readthedocs.org/projects/schematics-xml/badge/
:target: http://schematics-xml.readthedocs.org/en/latest/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Supported Python versions
.. image:: https://img.shields.io/pypi/dd/schematics-xml.svg
:target: https://pypi.python.org/pypi/schematics-xml/
:alt: Downloads
Contents
--------
.. toctree::
:maxdepth: 1
installation
usage
developer
internals/reference/index
License
-------
This software is licensed under the `MIT License`. See the `LICENSE`_.
Author
------
Alex Hayes <[email protected]>
.. _schematics: schematics.readthedocs.org
.. _LICENSE: https://github.com/alexhayes/schematics-xml/blob/master/LICENSE
| 0.912678 | 0.516656 |
============
Installation
============
You can install schematics-xml either via the Python Package Index (PyPI)
or from github.
To install using pip;
.. code-block:: bash
$ pip install schematics-xml
From github;
.. code-block:: bash
$ pip install git+https://github.com/alexhayes/schematics-xml.git
Currently `schematics-xml` only supports Python 3 - if you'd like feel free to
submit a PR adding support for Python 2, however note that I love type
annotations and any Python 2 PR will need to include a stub file.
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/installation.rst
|
installation.rst
|
============
Installation
============
You can install schematics-xml either via the Python Package Index (PyPI)
or from github.
To install using pip;
.. code-block:: bash
$ pip install schematics-xml
From github;
.. code-block:: bash
$ pip install git+https://github.com/alexhayes/schematics-xml.git
Currently `schematics-xml` only supports Python 3 - if you'd like feel free to
submit a PR adding support for Python 2, however note that I love type
annotations and any Python 2 PR will need to include a stub file.
| 0.73029 | 0.243946 |
Developer Documentation
=======================
Contributions
-------------
Contributions are more than welcome!
To get setup do the following;
.. code-block:: bash
mkvirtualenv --python=/usr/bin/python3.5 schematics-xml
git clone https://github.com/alexhayes/schematics-xml.git
cd schematics-xml
pip install -r requirements/dev.txt
pip install Django>=1.9,<1.10
Running Tests
-------------
Once you've checked out you should be able to run the tests;
.. code-block:: bash
tox
Or run all environments at once using detox;
.. code-block:: bash
detox
Creating Documentation
----------------------
.. code-block:: bash
cd docs
make clean html
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/developer.rst
|
developer.rst
|
Developer Documentation
=======================
Contributions
-------------
Contributions are more than welcome!
To get setup do the following;
.. code-block:: bash
mkvirtualenv --python=/usr/bin/python3.5 schematics-xml
git clone https://github.com/alexhayes/schematics-xml.git
cd schematics-xml
pip install -r requirements/dev.txt
pip install Django>=1.9,<1.10
Running Tests
-------------
Once you've checked out you should be able to run the tests;
.. code-block:: bash
tox
Or run all environments at once using detox;
.. code-block:: bash
detox
Creating Documentation
----------------------
.. code-block:: bash
cd docs
make clean html
| 0.516352 | 0.243564 |
Search.setIndex({envversion:50,filenames:["developer","index","installation","internals/reference/index","internals/reference/modules","internals/reference/schematics_xml","internals/reference/schematics_xml.tests","usage"],objects:{"":{schematics_xml:[5,0,0,"-"]},"schematics_xml.VersionInfo":{major:[5,2,1,""],micro:[5,2,1,""],minor:[5,2,1,""],releaselevel:[5,2,1,""],serial:[5,2,1,""]},"schematics_xml.models":{XMLModel:[5,1,1,""],field_has_type:[5,5,1,""],model_has_field_type:[5,5,1,""]},"schematics_xml.models.XMLModel":{from_xml:[5,3,1,""],primitive_to_xml:[5,4,1,""],primitive_value_to_xml:[5,4,1,""],to_xml:[5,4,1,""],xml_root:[5,2,1,""]},"schematics_xml.tests":{test_models:[6,0,0,"-"]},"schematics_xml.tests.test_models":{TestBooleanType:[6,1,1,""],TestDateTimeType:[6,1,1,""],TestDateType:[6,1,1,""],TestDecimalType:[6,1,1,""],TestDictType:[6,1,1,""],TestEmailType:[6,1,1,""],TestFloatType:[6,1,1,""],TestGeoPointType:[6,1,1,""],TestHasFieldType:[6,1,1,""],TestIPv4Type:[6,1,1,""],TestIPv6Type:[6,1,1,""],TestIntType:[6,1,1,""],TestListTypeOfIntType:[6,1,1,""],TestListTypeOfModelType:[6,1,1,""],TestLongType:[6,1,1,""],TestMD5Type:[6,1,1,""],TestModelType:[6,1,1,""],TestMultilingualStringType:[6,1,1,""],TestPolyModelType:[6,1,1,""],TestSHA1Type:[6,1,1,""],TestStringType:[6,1,1,""],TestTimestampType:[6,1,1,""],TestURLType:[6,1,1,""],TestUTCDateTimeType:[6,1,1,""],TestUUIDType:[6,1,1,""],TestUnionType:[6,1,1,""]},"schematics_xml.tests.test_models.TestBooleanType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestBooleanType.User":{active:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateTimeType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateTimeType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateType.User":{birthdate:[6,2,1,""]},"schematics_xml.tests.test_models.TestDecimalType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDecimalType.Person":{height:[6,2,1,""]},"schematics_xml.tests.test_models.TestDictType":{Request:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDictType.Request":{payload:[6,2,1,""]},"schematics_xml.tests.test_models.TestEmailType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestEmailType.User":{email:[6,2,1,""]},"schematics_xml.tests.test_models.TestFloatType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestFloatType.Person":{height:[6,2,1,""]},"schematics_xml.tests.test_models.TestGeoPointType":{Place:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestGeoPointType.Place":{point:[6,2,1,""]},"schematics_xml.tests.test_models.TestHasFieldType":{TestModel:[6,1,1,""],test_dicttype:[6,4,1,""],test_listtype:[6,4,1,""],test_listtype_withlisttype:[6,4,1,""],test_modeltype:[6,4,1,""],test_polymodel_fieldtype:[6,4,1,""],test_shallow:[6,4,1,""]},"schematics_xml.tests.test_models.TestHasFieldType.TestModel":{a:[6,2,1,""],b:[6,2,1,""],c:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv4Type":{Proxy:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv4Type.Proxy":{ip_address:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv6Type":{Proxy:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv6Type.Proxy":{ip_address:[6,2,1,""]},"schematics_xml.tests.test_models.TestIntType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIntType.Person":{age:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfIntType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfIntType.Person":{favorite_numbers:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfModelType":{Color:[6,1,1,""],Person:[6,2,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfModelType.Color":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestLongType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestLongType.Person":{pk:[6,2,1,""]},"schematics_xml.tests.test_models.TestMD5Type":{File:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestMD5Type.File":{md5:[6,2,1,""]},"schematics_xml.tests.test_models.TestModelType":{Person:[6,2,1,""],Pet:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestModelType.Pet":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestMultilingualStringType":{Animal:[6,1,1,""],test_from_xml:[6,4,1,""],test_from_xml_nested_raises:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestMultilingualStringType.Animal":{text:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType":{Eggs:[6,1,1,""],RecipeItem:[6,2,1,""],Sausage:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType.Eggs":{yolks:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType.Sausage":{meat:[6,2,1,""]},"schematics_xml.tests.test_models.TestSHA1Type":{File:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestSHA1Type.File":{sha1:[6,2,1,""]},"schematics_xml.tests.test_models.TestStringType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestStringType.Person":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestTimestampType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestTimestampType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestURLType":{Site:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestURLType.Site":{url:[6,2,1,""]},"schematics_xml.tests.test_models.TestUTCDateTimeType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUTCDateTimeType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestUUIDType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUUIDType.Person":{pk:[6,2,1,""]},"schematics_xml.tests.test_models.TestUnionType":{Foo:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUnionType.Foo":{union:[6,2,1,""]},schematics_xml:{VersionInfo:[5,1,1,""],models:[5,0,0,"-"],tests:[6,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","attribute","Python attribute"],"3":["py","classmethod","Python class method"],"4":["py","method","Python method"],"5":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:attribute","3":"py:classmethod","4":"py:method","5":"py:function"},terms:{"000000z":6,"01t08":6,"2ee84ef6301ccec5926c4adbf3e9b51c6c42ade3":6,"32c5548e":6,"4b23":6,"85a3":6,"8a2e":6,"class":[5,6,7],"import":7,"return":[5,7],"true":[5,6],_element:5,a06:6,abl:0,activ:6,alex:1,alexhay:[0,2,6],alia:5,all:[0,5],alut:1,ani:2,anim:6,animal:[6,7],annot:2,app_data:[5,6],appropri:5,argument:5,back:7,bar:6,base:[5,6],basetyp:5,bin:0,birthdat:6,blue:6,bool:5,booleantyp:6,can:[2,5],cat:7,check:0,classmethod:5,clean:0,clone:0,color:6,com:[0,1,2,6],contain:[5,7],convert:[1,5],current:[2,5],date:3,datetimetyp:6,datetyp:6,db8:6,ddee:6,decimaltyp:6,def:7,defin:7,deserialize_map:[5,6],detox:0,dev:0,dict:[5,7],dicttyp:6,django:0,doc:0,efe2d5fd46824508b8a0082c8279bba:6,egg:6,either:2,email:6,emailtyp:6,encod:[6,7],environ:0,etre:5,exampl:6,f387a15bcac9:6,fals:[5,6],favorite_color:6,favorite_numb:6,feel:2,field:5,field_has_typ:5,file:[2,6],floattyp:6,follow:[0,7],foo:6,free:2,from:[1,2,5,7],from_xml:[5,6,7],garfield:[6,7],geopointtyp:6,get:0,git:[0,2],github:[0,2,6],green:6,hay:1,haystack:5,height:6,howev:2,html:0,http:[0,2,6],includ:2,index:2,inherit:7,init:[5,6],instal:[0,2],installat:1,instanc:[5,6],internal:1,inttype:6,ip_address:6,ipv4type:6,ipv6type:6,iso:[6,7],item:6,iterat:5,john:[6,7],kei:5,kind:7,kwarg:[5,6],license:1,like:2,listtyp:6,love:2,lxml:5,major:5,make:0,md5:6,md5type:6,meat:6,method:5,micro:5,minor:5,mit:1,mkvirtualenv:0,model:[1,4],model_has_field_typ:5,modul:1,more:0,multilingualstringtyp:6,name:[6,7],need:2,needl:5,nest:6,none:[5,6],nonetyp:5,note:2,notimplementederror:6,now:7,number:5,object:6,oct:3,onc:0,once:0,onli:2,other:7,out:0,over:5,packag:[2,3,4],paramet:5,parent:5,partial:[5,6],pass:5,payload:6,person:[6,7],pet:6,pip:[0,2],place:6,point:6,primit:5,primitive_to_xml:5,primitive_value_to_xml:5,properti:7,provid:5,proxi:6,pypi:2,python3:0,python:[0,1,2,5],rais:6,raw_data:[5,6],recipeitem:6,red:6,refer:1,releas:3,releaselevel:5,repres:5,request:6,requir:0,role:5,sausag:6,schemat:0,schematics_xml:3,search:5,see:1,self:7,serial:5,serpent:6,set:7,setup:0,sha1:6,sha1type:6,should:0,simpli:7,site:6,softwar:1,sourc:[5,6],str:5,strict:[5,6],string:5,stringtyp:[6,7],stub:2,submit:2,submodul:4,subpackag:4,support:2,test_dicttyp:6,test_from_xml:6,test_from_xml_nested_rais:6,test_listtyp:6,test_listtype_withlisttyp:6,test_model:[4,5],test_modeltyp:6,test_polymodel_fieldtyp:6,test_shallow:6,test_to_xml:6,testbooleantyp:6,testdatetimetyp:6,testdatetyp:6,testdecimaltyp:6,testdicttyp:6,testemailtyp:6,testfloattyp:6,testgeopointtyp:6,testhasfieldtyp:6,testinttyp:6,testipv4typ:6,testipv6typ:6,testlisttypeofinttyp:6,testlisttypeofmodeltyp:6,testlongtyp:6,testmd5typ:6,testmodel:6,testmodeltyp:6,testmultilingualstringtyp:6,testpolymodeltyp:6,testsha1typ:6,teststringtyp:6,testtimestamptyp:6,testuniontyp:6,testurltyp:6,testutcdatetimetyp:6,testuuidtyp:6,text:6,than:0,thi:[1,5],through:5,timestamptyp:6,to_primit:5,to_xml:[5,7],tox:0,trusted_data:[5,6],tupl:5,txt:0,type:[2,5],under:1,union:[5,6],uniontyp:6,url:6,urltype:6,usage:1,user:6,usr:0,utcdatetimetyp:6,uuidtype:6,valid:[5,6],valu:5,version:[6,7],versioninfo:5,via:2,wai:7,welcom:0,within:5,xml:0,xml_root:[5,7],xmlmodel:[5,6,7],yolk:6,you:[0,2]},titles:["Developer Documentation","schematics-xml","Installation","Internal Module Reference","schematics_xml","schematics_xml package","schematics_xml.tests package","Usage"],titleterms:{author:1,content:[1,5,6],contribut:0,creat:0,develop:0,document:0,installat:2,internal:3,licens:1,model:5,modul:[3,5,6],node:7,packag:[5,6],refer:3,root:7,run:0,schemat:1,schematics_xml:[4,5,6],submodul:[5,6],subpackag:5,test:[0,6],test_model:6,usage:7,xml:1}})
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/_build/html/searchindex.js
|
searchindex.js
|
Search.setIndex({envversion:50,filenames:["developer","index","installation","internals/reference/index","internals/reference/modules","internals/reference/schematics_xml","internals/reference/schematics_xml.tests","usage"],objects:{"":{schematics_xml:[5,0,0,"-"]},"schematics_xml.VersionInfo":{major:[5,2,1,""],micro:[5,2,1,""],minor:[5,2,1,""],releaselevel:[5,2,1,""],serial:[5,2,1,""]},"schematics_xml.models":{XMLModel:[5,1,1,""],field_has_type:[5,5,1,""],model_has_field_type:[5,5,1,""]},"schematics_xml.models.XMLModel":{from_xml:[5,3,1,""],primitive_to_xml:[5,4,1,""],primitive_value_to_xml:[5,4,1,""],to_xml:[5,4,1,""],xml_root:[5,2,1,""]},"schematics_xml.tests":{test_models:[6,0,0,"-"]},"schematics_xml.tests.test_models":{TestBooleanType:[6,1,1,""],TestDateTimeType:[6,1,1,""],TestDateType:[6,1,1,""],TestDecimalType:[6,1,1,""],TestDictType:[6,1,1,""],TestEmailType:[6,1,1,""],TestFloatType:[6,1,1,""],TestGeoPointType:[6,1,1,""],TestHasFieldType:[6,1,1,""],TestIPv4Type:[6,1,1,""],TestIPv6Type:[6,1,1,""],TestIntType:[6,1,1,""],TestListTypeOfIntType:[6,1,1,""],TestListTypeOfModelType:[6,1,1,""],TestLongType:[6,1,1,""],TestMD5Type:[6,1,1,""],TestModelType:[6,1,1,""],TestMultilingualStringType:[6,1,1,""],TestPolyModelType:[6,1,1,""],TestSHA1Type:[6,1,1,""],TestStringType:[6,1,1,""],TestTimestampType:[6,1,1,""],TestURLType:[6,1,1,""],TestUTCDateTimeType:[6,1,1,""],TestUUIDType:[6,1,1,""],TestUnionType:[6,1,1,""]},"schematics_xml.tests.test_models.TestBooleanType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestBooleanType.User":{active:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateTimeType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateTimeType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDateType.User":{birthdate:[6,2,1,""]},"schematics_xml.tests.test_models.TestDecimalType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDecimalType.Person":{height:[6,2,1,""]},"schematics_xml.tests.test_models.TestDictType":{Request:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestDictType.Request":{payload:[6,2,1,""]},"schematics_xml.tests.test_models.TestEmailType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestEmailType.User":{email:[6,2,1,""]},"schematics_xml.tests.test_models.TestFloatType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestFloatType.Person":{height:[6,2,1,""]},"schematics_xml.tests.test_models.TestGeoPointType":{Place:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestGeoPointType.Place":{point:[6,2,1,""]},"schematics_xml.tests.test_models.TestHasFieldType":{TestModel:[6,1,1,""],test_dicttype:[6,4,1,""],test_listtype:[6,4,1,""],test_listtype_withlisttype:[6,4,1,""],test_modeltype:[6,4,1,""],test_polymodel_fieldtype:[6,4,1,""],test_shallow:[6,4,1,""]},"schematics_xml.tests.test_models.TestHasFieldType.TestModel":{a:[6,2,1,""],b:[6,2,1,""],c:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv4Type":{Proxy:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv4Type.Proxy":{ip_address:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv6Type":{Proxy:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIPv6Type.Proxy":{ip_address:[6,2,1,""]},"schematics_xml.tests.test_models.TestIntType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestIntType.Person":{age:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfIntType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfIntType.Person":{favorite_numbers:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfModelType":{Color:[6,1,1,""],Person:[6,2,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestListTypeOfModelType.Color":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestLongType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestLongType.Person":{pk:[6,2,1,""]},"schematics_xml.tests.test_models.TestMD5Type":{File:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestMD5Type.File":{md5:[6,2,1,""]},"schematics_xml.tests.test_models.TestModelType":{Person:[6,2,1,""],Pet:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestModelType.Pet":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestMultilingualStringType":{Animal:[6,1,1,""],test_from_xml:[6,4,1,""],test_from_xml_nested_raises:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestMultilingualStringType.Animal":{text:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType":{Eggs:[6,1,1,""],RecipeItem:[6,2,1,""],Sausage:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType.Eggs":{yolks:[6,2,1,""]},"schematics_xml.tests.test_models.TestPolyModelType.Sausage":{meat:[6,2,1,""]},"schematics_xml.tests.test_models.TestSHA1Type":{File:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestSHA1Type.File":{sha1:[6,2,1,""]},"schematics_xml.tests.test_models.TestStringType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestStringType.Person":{name:[6,2,1,""]},"schematics_xml.tests.test_models.TestTimestampType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestTimestampType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestURLType":{Site:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestURLType.Site":{url:[6,2,1,""]},"schematics_xml.tests.test_models.TestUTCDateTimeType":{User:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUTCDateTimeType.User":{created:[6,2,1,""]},"schematics_xml.tests.test_models.TestUUIDType":{Person:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUUIDType.Person":{pk:[6,2,1,""]},"schematics_xml.tests.test_models.TestUnionType":{Foo:[6,1,1,""],test_from_xml:[6,4,1,""],test_to_xml:[6,4,1,""],xml:[6,2,1,""]},"schematics_xml.tests.test_models.TestUnionType.Foo":{union:[6,2,1,""]},schematics_xml:{VersionInfo:[5,1,1,""],models:[5,0,0,"-"],tests:[6,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","attribute","Python attribute"],"3":["py","classmethod","Python class method"],"4":["py","method","Python method"],"5":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:class","2":"py:attribute","3":"py:classmethod","4":"py:method","5":"py:function"},terms:{"000000z":6,"01t08":6,"2ee84ef6301ccec5926c4adbf3e9b51c6c42ade3":6,"32c5548e":6,"4b23":6,"85a3":6,"8a2e":6,"class":[5,6,7],"import":7,"return":[5,7],"true":[5,6],_element:5,a06:6,abl:0,activ:6,alex:1,alexhay:[0,2,6],alia:5,all:[0,5],alut:1,ani:2,anim:6,animal:[6,7],annot:2,app_data:[5,6],appropri:5,argument:5,back:7,bar:6,base:[5,6],basetyp:5,bin:0,birthdat:6,blue:6,bool:5,booleantyp:6,can:[2,5],cat:7,check:0,classmethod:5,clean:0,clone:0,color:6,com:[0,1,2,6],contain:[5,7],convert:[1,5],current:[2,5],date:3,datetimetyp:6,datetyp:6,db8:6,ddee:6,decimaltyp:6,def:7,defin:7,deserialize_map:[5,6],detox:0,dev:0,dict:[5,7],dicttyp:6,django:0,doc:0,efe2d5fd46824508b8a0082c8279bba:6,egg:6,either:2,email:6,emailtyp:6,encod:[6,7],environ:0,etre:5,exampl:6,f387a15bcac9:6,fals:[5,6],favorite_color:6,favorite_numb:6,feel:2,field:5,field_has_typ:5,file:[2,6],floattyp:6,follow:[0,7],foo:6,free:2,from:[1,2,5,7],from_xml:[5,6,7],garfield:[6,7],geopointtyp:6,get:0,git:[0,2],github:[0,2,6],green:6,hay:1,haystack:5,height:6,howev:2,html:0,http:[0,2,6],includ:2,index:2,inherit:7,init:[5,6],instal:[0,2],installat:1,instanc:[5,6],internal:1,inttype:6,ip_address:6,ipv4type:6,ipv6type:6,iso:[6,7],item:6,iterat:5,john:[6,7],kei:5,kind:7,kwarg:[5,6],license:1,like:2,listtyp:6,love:2,lxml:5,major:5,make:0,md5:6,md5type:6,meat:6,method:5,micro:5,minor:5,mit:1,mkvirtualenv:0,model:[1,4],model_has_field_typ:5,modul:1,more:0,multilingualstringtyp:6,name:[6,7],need:2,needl:5,nest:6,none:[5,6],nonetyp:5,note:2,notimplementederror:6,now:7,number:5,object:6,oct:3,onc:0,once:0,onli:2,other:7,out:0,over:5,packag:[2,3,4],paramet:5,parent:5,partial:[5,6],pass:5,payload:6,person:[6,7],pet:6,pip:[0,2],place:6,point:6,primit:5,primitive_to_xml:5,primitive_value_to_xml:5,properti:7,provid:5,proxi:6,pypi:2,python3:0,python:[0,1,2,5],rais:6,raw_data:[5,6],recipeitem:6,red:6,refer:1,releas:3,releaselevel:5,repres:5,request:6,requir:0,role:5,sausag:6,schemat:0,schematics_xml:3,search:5,see:1,self:7,serial:5,serpent:6,set:7,setup:0,sha1:6,sha1type:6,should:0,simpli:7,site:6,softwar:1,sourc:[5,6],str:5,strict:[5,6],string:5,stringtyp:[6,7],stub:2,submit:2,submodul:4,subpackag:4,support:2,test_dicttyp:6,test_from_xml:6,test_from_xml_nested_rais:6,test_listtyp:6,test_listtype_withlisttyp:6,test_model:[4,5],test_modeltyp:6,test_polymodel_fieldtyp:6,test_shallow:6,test_to_xml:6,testbooleantyp:6,testdatetimetyp:6,testdatetyp:6,testdecimaltyp:6,testdicttyp:6,testemailtyp:6,testfloattyp:6,testgeopointtyp:6,testhasfieldtyp:6,testinttyp:6,testipv4typ:6,testipv6typ:6,testlisttypeofinttyp:6,testlisttypeofmodeltyp:6,testlongtyp:6,testmd5typ:6,testmodel:6,testmodeltyp:6,testmultilingualstringtyp:6,testpolymodeltyp:6,testsha1typ:6,teststringtyp:6,testtimestamptyp:6,testuniontyp:6,testurltyp:6,testutcdatetimetyp:6,testuuidtyp:6,text:6,than:0,thi:[1,5],through:5,timestamptyp:6,to_primit:5,to_xml:[5,7],tox:0,trusted_data:[5,6],tupl:5,txt:0,type:[2,5],under:1,union:[5,6],uniontyp:6,url:6,urltype:6,usage:1,user:6,usr:0,utcdatetimetyp:6,uuidtype:6,valid:[5,6],valu:5,version:[6,7],versioninfo:5,via:2,wai:7,welcom:0,within:5,xml:0,xml_root:[5,7],xmlmodel:[5,6,7],yolk:6,you:[0,2]},titles:["Developer Documentation","schematics-xml","Installation","Internal Module Reference","schematics_xml","schematics_xml package","schematics_xml.tests package","Usage"],titleterms:{author:1,content:[1,5,6],contribut:0,creat:0,develop:0,document:0,installat:2,internal:3,licens:1,model:5,modul:[3,5,6],node:7,packag:[5,6],refer:3,root:7,run:0,schemat:1,schematics_xml:[4,5,6],submodul:[5,6],subpackag:5,test:[0,6],test_model:6,usage:7,xml:1}})
| 0.198802 | 0.28825 |
* select a different prefix for underscore
*/
$u = _.noConflict();
/**
* make the code below compatible with browsers without
* an installed firebug like debugger
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
"profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {};
}
*/
/**
* small helper function to urldecode strings
*/
jQuery.urldecode = function(x) {
return decodeURIComponent(x).replace(/\+/g, ' ');
};
/**
* small helper function to urlencode strings
*/
jQuery.urlencode = encodeURIComponent;
/**
* This function returns the parsed url parameters of the
* current request. Multiple values per key are supported,
* it will always return arrays of strings for the value parts.
*/
jQuery.getQueryParameters = function(s) {
if (typeof s == 'undefined')
s = document.location.search;
var parts = s.substr(s.indexOf('?') + 1).split('&');
var result = {};
for (var i = 0; i < parts.length; i++) {
var tmp = parts[i].split('=', 2);
var key = jQuery.urldecode(tmp[0]);
var value = jQuery.urldecode(tmp[1]);
if (key in result)
result[key].push(value);
else
result[key] = [value];
}
return result;
};
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this);
});
}
}
return this.each(function() {
highlight(this);
});
};
/*
* backward compatibility for jQuery.browser
* This will be supported until firefox bug is fixed.
*/
if (!jQuery.browser) {
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
jQuery.browser = {};
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}
/**
* Small JavaScript module for the documentation.
*/
var Documentation = {
init : function() {
this.fixFirefoxAnchorBug();
this.highlightSearchWords();
this.initIndexTable();
},
/**
* i18n support
*/
TRANSLATIONS : {},
PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; },
LOCALE : 'unknown',
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext : function(string) {
var translated = Documentation.TRANSLATIONS[string];
if (typeof translated == 'undefined')
return string;
return (typeof translated == 'string') ? translated : translated[0];
},
ngettext : function(singular, plural, n) {
var translated = Documentation.TRANSLATIONS[singular];
if (typeof translated == 'undefined')
return (n == 1) ? singular : plural;
return translated[Documentation.PLURALEXPR(n)];
},
addTranslations : function(catalog) {
for (var key in catalog.messages)
this.TRANSLATIONS[key] = catalog.messages[key];
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
this.LOCALE = catalog.locale;
},
/**
* add context elements like header anchor links
*/
addContextElements : function() {
$('div[id] > :header:first').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this headline')).
appendTo(this);
});
$('dt[id]').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this definition')).
appendTo(this);
});
},
/**
* workaround a firefox stupidity
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
*/
fixFirefoxAnchorBug : function() {
if (document.location.hash)
window.setTimeout(function() {
document.location.href += '';
}, 10);
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
.appendTo($('#searchbox'));
}
},
/**
* init the domain index toggle buttons
*/
initIndexTable : function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) == 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
},
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
},
/**
* make the url absolute
*/
makeURL : function(relativeURL) {
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
},
/**
* get the current relative url
*/
getCurrentURL : function() {
var path = document.location.pathname;
var parts = path.split(/\//);
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
if (this == '..')
parts.pop();
});
var url = parts.join('/');
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
},
initOnKeyListeners: function() {
$(document).keyup(function(event) {
var activeElementType = document.activeElement.tagName;
// don't navigate when in search box or textarea
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
switch (event.keyCode) {
case 37: // left
var prevHref = $('link[rel="prev"]').prop('href');
if (prevHref) {
window.location.href = prevHref;
return false;
}
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
}
}
});
}
};
// quick alias for translations
_ = Documentation.gettext;
$(document).ready(function() {
Documentation.init();
});
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/_build/html/_static/doctools.js
|
doctools.js
|
* select a different prefix for underscore
*/
$u = _.noConflict();
/**
* make the code below compatible with browsers without
* an installed firebug like debugger
if (!window.console || !console.firebug) {
var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
"dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
"profile", "profileEnd"];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {};
}
*/
/**
* small helper function to urldecode strings
*/
jQuery.urldecode = function(x) {
return decodeURIComponent(x).replace(/\+/g, ' ');
};
/**
* small helper function to urlencode strings
*/
jQuery.urlencode = encodeURIComponent;
/**
* This function returns the parsed url parameters of the
* current request. Multiple values per key are supported,
* it will always return arrays of strings for the value parts.
*/
jQuery.getQueryParameters = function(s) {
if (typeof s == 'undefined')
s = document.location.search;
var parts = s.substr(s.indexOf('?') + 1).split('&');
var result = {};
for (var i = 0; i < parts.length; i++) {
var tmp = parts[i].split('=', 2);
var key = jQuery.urldecode(tmp[0]);
var value = jQuery.urldecode(tmp[1]);
if (key in result)
result[key].push(value);
else
result[key] = [value];
}
return result;
};
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this);
});
}
}
return this.each(function() {
highlight(this);
});
};
/*
* backward compatibility for jQuery.browser
* This will be supported until firefox bug is fixed.
*/
if (!jQuery.browser) {
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
/(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
jQuery.browser = {};
jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}
/**
* Small JavaScript module for the documentation.
*/
var Documentation = {
init : function() {
this.fixFirefoxAnchorBug();
this.highlightSearchWords();
this.initIndexTable();
},
/**
* i18n support
*/
TRANSLATIONS : {},
PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; },
LOCALE : 'unknown',
// gettext and ngettext don't access this so that the functions
// can safely bound to a different name (_ = Documentation.gettext)
gettext : function(string) {
var translated = Documentation.TRANSLATIONS[string];
if (typeof translated == 'undefined')
return string;
return (typeof translated == 'string') ? translated : translated[0];
},
ngettext : function(singular, plural, n) {
var translated = Documentation.TRANSLATIONS[singular];
if (typeof translated == 'undefined')
return (n == 1) ? singular : plural;
return translated[Documentation.PLURALEXPR(n)];
},
addTranslations : function(catalog) {
for (var key in catalog.messages)
this.TRANSLATIONS[key] = catalog.messages[key];
this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
this.LOCALE = catalog.locale;
},
/**
* add context elements like header anchor links
*/
addContextElements : function() {
$('div[id] > :header:first').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this headline')).
appendTo(this);
});
$('dt[id]').each(function() {
$('<a class="headerlink">\u00B6</a>').
attr('href', '#' + this.id).
attr('title', _('Permalink to this definition')).
appendTo(this);
});
},
/**
* workaround a firefox stupidity
* see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
*/
fixFirefoxAnchorBug : function() {
if (document.location.hash)
window.setTimeout(function() {
document.location.href += '';
}, 10);
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
if (!body.length) {
body = $('body');
}
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlighted');
});
}, 10);
$('<p class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
.appendTo($('#searchbox'));
}
},
/**
* init the domain index toggle buttons
*/
initIndexTable : function() {
var togglers = $('img.toggler').click(function() {
var src = $(this).attr('src');
var idnum = $(this).attr('id').substr(7);
$('tr.cg-' + idnum).toggle();
if (src.substr(-9) == 'minus.png')
$(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
else
$(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
}).css('display', '');
if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
togglers.click();
}
},
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('#searchbox .highlight-link').fadeOut(300);
$('span.highlighted').removeClass('highlighted');
},
/**
* make the url absolute
*/
makeURL : function(relativeURL) {
return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
},
/**
* get the current relative url
*/
getCurrentURL : function() {
var path = document.location.pathname;
var parts = path.split(/\//);
$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
if (this == '..')
parts.pop();
});
var url = parts.join('/');
return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
},
initOnKeyListeners: function() {
$(document).keyup(function(event) {
var activeElementType = document.activeElement.tagName;
// don't navigate when in search box or textarea
if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
switch (event.keyCode) {
case 37: // left
var prevHref = $('link[rel="prev"]').prop('href');
if (prevHref) {
window.location.href = prevHref;
return false;
}
case 39: // right
var nextHref = $('link[rel="next"]').prop('href');
if (nextHref) {
window.location.href = nextHref;
return false;
}
}
}
});
}
};
// quick alias for translations
_ = Documentation.gettext;
$(document).ready(function() {
Documentation.init();
});
| 0.382603 | 0.193223 |
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,
h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each=
b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a==
null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=
function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=
e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=
function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});
return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,
c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=
b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);
return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,
d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};
var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,
c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:
a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};
b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments,
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};
b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};
b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),
function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+
u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]=
function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=
true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/_build/html/_static/underscore.js
|
underscore.js
|
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,
h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each=
b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a==
null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=
function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=
e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=
function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});
return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,
c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=
b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);
return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,
d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};
var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,
c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:
a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};
b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments,
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};
b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};
b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),
function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+
u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]=
function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=
true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
| 0.067803 | 0.252406 |
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"sphinx-rtd-theme":[function(require,module,exports){
var jQuery = (typeof(window) != 'undefined') ? window.jQuery : require('jquery');
// Sphinx theme nav state
function ThemeNav () {
var nav = {
navBar: null,
win: null,
winScroll: false,
winResize: false,
linkScroll: false,
winPosition: 0,
winHeight: null,
docHeight: null,
isRunning: null
};
nav.enable = function () {
var self = this;
jQuery(function ($) {
self.init($);
self.reset();
self.win.on('hashchange', self.reset);
// Set scroll monitor
self.win.on('scroll', function () {
if (!self.linkScroll) {
self.winScroll = true;
}
});
setInterval(function () { if (self.winScroll) self.onScroll(); }, 25);
// Set resize monitor
self.win.on('resize', function () {
self.winResize = true;
});
setInterval(function () { if (self.winResize) self.onResize(); }, 25);
self.onResize();
});
};
nav.init = function ($) {
var doc = $(document),
self = this;
this.navBar = $('div.wy-side-scroll:first');
this.win = $(window);
// Set up javascript UX bits
$(document)
// Shift nav in mobile when clicking the menu.
.on('click', "[data-toggle='wy-nav-top']", function() {
$("[data-toggle='wy-nav-shift']").toggleClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
})
// Nav menu link click operations
.on('click', ".wy-menu-vertical .current ul li a", function() {
var target = $(this);
// Close menu when you click a link.
$("[data-toggle='wy-nav-shift']").removeClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
// Handle dynamic display of l3 and l4 nav lists
self.toggleCurrent(target);
self.hashChange();
})
.on('click', "[data-toggle='rst-current-version']", function() {
$("[data-toggle='rst-versions']").toggleClass("shift-up");
})
// Make tables responsive
$("table.docutils:not(.field-list)")
.wrap("<div class='wy-table-responsive'></div>");
// Add expand links to all parents of nested ul
$('.wy-menu-vertical ul').not('.simple').siblings('a').each(function () {
var link = $(this);
expand = $('<span class="toctree-expand"></span>');
expand.on('click', function (ev) {
self.toggleCurrent(link);
ev.stopPropagation();
return false;
});
link.prepend(expand);
});
};
nav.reset = function () {
// Get anchor from URL and open up nested nav
var anchor = encodeURI(window.location.hash);
if (anchor) {
try {
var link = $('.wy-menu-vertical')
.find('[href="' + anchor + '"]');
$('.wy-menu-vertical li.toctree-l1 li.current')
.removeClass('current');
link.closest('li.toctree-l2').addClass('current');
link.closest('li.toctree-l3').addClass('current');
link.closest('li.toctree-l4').addClass('current');
}
catch (err) {
console.log("Error expanding nav for anchor", err);
}
}
};
nav.onScroll = function () {
this.winScroll = false;
var newWinPosition = this.win.scrollTop(),
winBottom = newWinPosition + this.winHeight,
navPosition = this.navBar.scrollTop(),
newNavPosition = navPosition + (newWinPosition - this.winPosition);
if (newWinPosition < 0 || winBottom > this.docHeight) {
return;
}
this.navBar.scrollTop(newNavPosition);
this.winPosition = newWinPosition;
};
nav.onResize = function () {
this.winResize = false;
this.winHeight = this.win.height();
this.docHeight = $(document).height();
};
nav.hashChange = function () {
this.linkScroll = true;
this.win.one('hashchange', function () {
this.linkScroll = false;
});
};
nav.toggleCurrent = function (elem) {
var parent_li = elem.closest('li');
parent_li.siblings('li.current').removeClass('current');
parent_li.siblings().find('li.current').removeClass('current');
parent_li.find('> ul li.current').removeClass('current');
parent_li.toggleClass('current');
}
return nav;
};
module.exports.ThemeNav = ThemeNav();
if (typeof(window) != 'undefined') {
window.SphinxRtdTheme = { StickyNav: module.exports.ThemeNav };
}
},{"jquery":"jquery"}]},{},["sphinx-rtd-theme"]);
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/_build/html/_static/js/theme.js
|
theme.js
|
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"sphinx-rtd-theme":[function(require,module,exports){
var jQuery = (typeof(window) != 'undefined') ? window.jQuery : require('jquery');
// Sphinx theme nav state
function ThemeNav () {
var nav = {
navBar: null,
win: null,
winScroll: false,
winResize: false,
linkScroll: false,
winPosition: 0,
winHeight: null,
docHeight: null,
isRunning: null
};
nav.enable = function () {
var self = this;
jQuery(function ($) {
self.init($);
self.reset();
self.win.on('hashchange', self.reset);
// Set scroll monitor
self.win.on('scroll', function () {
if (!self.linkScroll) {
self.winScroll = true;
}
});
setInterval(function () { if (self.winScroll) self.onScroll(); }, 25);
// Set resize monitor
self.win.on('resize', function () {
self.winResize = true;
});
setInterval(function () { if (self.winResize) self.onResize(); }, 25);
self.onResize();
});
};
nav.init = function ($) {
var doc = $(document),
self = this;
this.navBar = $('div.wy-side-scroll:first');
this.win = $(window);
// Set up javascript UX bits
$(document)
// Shift nav in mobile when clicking the menu.
.on('click', "[data-toggle='wy-nav-top']", function() {
$("[data-toggle='wy-nav-shift']").toggleClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
})
// Nav menu link click operations
.on('click', ".wy-menu-vertical .current ul li a", function() {
var target = $(this);
// Close menu when you click a link.
$("[data-toggle='wy-nav-shift']").removeClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
// Handle dynamic display of l3 and l4 nav lists
self.toggleCurrent(target);
self.hashChange();
})
.on('click', "[data-toggle='rst-current-version']", function() {
$("[data-toggle='rst-versions']").toggleClass("shift-up");
})
// Make tables responsive
$("table.docutils:not(.field-list)")
.wrap("<div class='wy-table-responsive'></div>");
// Add expand links to all parents of nested ul
$('.wy-menu-vertical ul').not('.simple').siblings('a').each(function () {
var link = $(this);
expand = $('<span class="toctree-expand"></span>');
expand.on('click', function (ev) {
self.toggleCurrent(link);
ev.stopPropagation();
return false;
});
link.prepend(expand);
});
};
nav.reset = function () {
// Get anchor from URL and open up nested nav
var anchor = encodeURI(window.location.hash);
if (anchor) {
try {
var link = $('.wy-menu-vertical')
.find('[href="' + anchor + '"]');
$('.wy-menu-vertical li.toctree-l1 li.current')
.removeClass('current');
link.closest('li.toctree-l2').addClass('current');
link.closest('li.toctree-l3').addClass('current');
link.closest('li.toctree-l4').addClass('current');
}
catch (err) {
console.log("Error expanding nav for anchor", err);
}
}
};
nav.onScroll = function () {
this.winScroll = false;
var newWinPosition = this.win.scrollTop(),
winBottom = newWinPosition + this.winHeight,
navPosition = this.navBar.scrollTop(),
newNavPosition = navPosition + (newWinPosition - this.winPosition);
if (newWinPosition < 0 || winBottom > this.docHeight) {
return;
}
this.navBar.scrollTop(newNavPosition);
this.winPosition = newWinPosition;
};
nav.onResize = function () {
this.winResize = false;
this.winHeight = this.win.height();
this.docHeight = $(document).height();
};
nav.hashChange = function () {
this.linkScroll = true;
this.win.one('hashchange', function () {
this.linkScroll = false;
});
};
nav.toggleCurrent = function (elem) {
var parent_li = elem.closest('li');
parent_li.siblings('li.current').removeClass('current');
parent_li.siblings().find('li.current').removeClass('current');
parent_li.find('> ul li.current').removeClass('current');
parent_li.toggleClass('current');
}
return nav;
};
module.exports.ThemeNav = ThemeNav();
if (typeof(window) != 'undefined') {
window.SphinxRtdTheme = { StickyNav: module.exports.ThemeNav };
}
},{"jquery":"jquery"}]},{},["sphinx-rtd-theme"]);
| 0.257018 | 0.065875 |
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/docs/_build/html/_static/js/modernizr.min.js
|
modernizr.min.js
|
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
| 0.039021 | 0.25243 |
import collections
import numbers
import lxml.builder
import lxml.etree
from schematics import Model
from schematics.types import BaseType, ModelType, CompoundType, ListType, DictType
from schematics.types.base import MultilingualStringType
from schematics.types.compound import PolyModelType
from xmltodict import parse
class XMLModel(Model):
"""
A model that can convert it's fields to and from XML.
"""
@property
def xml_root(self) -> str:
"""
Override this attribute to set the XML root returned by :py:meth:`.XMLModel.to_xml`.
"""
return type(self).__name__.lower()
#: Override this attribute to set the encoding specified in the XML returned by :py:meth:`.XMLModel.to_xml`.
xml_encoding = 'UTF-8'
def to_xml(self, role: str=None, app_data: dict=None, encoding: str=None, **kwargs) -> str:
"""
Return a string of XML that represents this model.
Currently all arguments are passed through to schematics.Model.to_primitive.
:param role: schematics Model to_primitive role parameter.
:param app_data: schematics Model to_primitive app_data parameter.
:param encoding: xml encoding attribute string.
:param kwargs: schematics Model to_primitive kwargs parameter.
"""
primitive = self.to_primitive(role=role, app_data=app_data, **kwargs)
root = self.primitive_to_xml(primitive)
return lxml.etree.tostring( # pylint: disable=no-member
root,
pretty_print=True,
xml_declaration=True,
encoding=encoding or self.xml_encoding
)
def primitive_to_xml(self, primitive: dict, parent: 'lxml.etree._Element'=None):
element_maker = lxml.builder.ElementMaker()
if parent is None:
parent = getattr(element_maker, self.xml_root)()
for key, value in primitive.items():
self.primitive_value_to_xml(key, parent, value)
return parent
def primitive_value_to_xml(self, key, parent, value):
element_maker = lxml.builder.ElementMaker()
if isinstance(value, bool):
parent.append(getattr(element_maker, key)('1' if value else '0'))
elif isinstance(value, numbers.Number) or isinstance(value, str):
parent.append(getattr(element_maker, key)(str(value)))
elif value is None:
parent.append(getattr(element_maker, key)(''))
elif isinstance(value, dict):
_parent = getattr(element_maker, key)()
parent.append(self.primitive_to_xml(value, _parent))
elif isinstance(value, collections.abc.Iterable):
for _value in value:
self.primitive_value_to_xml(key, parent, _value)
else:
raise TypeError('Unsupported data type: %s (%s)' % (value, type(value).__name__))
@classmethod
def from_xml(cls, xml: str) -> Model:
"""
Convert XML into a model.
:param xml: A string of XML that represents this Model.
"""
if model_has_field_type(MultilingualStringType, cls):
raise NotImplementedError("Field type 'MultilingualStringType' is not supported.")
primitive = parse(xml)
if len(primitive) != 1:
raise NotImplementedError
for _, raw_data in primitive.items():
if model_has_field_type(ListType, cls):
# We need to ensure that single item lists are actually lists and not dicts
raw_data = ensure_lists_in_model(raw_data, cls)
return cls(raw_data=raw_data)
def model_has_field_type(needle: BaseType, haystack: Model) -> bool:
"""
Return True if haystack contains a field of type needle.
Iterates over all fields (and into field if appropriate) and searches for field type *needle* in model
*haystack*.
:param needle: A schematics field class to search for.
:param haystack: A schematics model to search within.
"""
for _, field in haystack._field_list: # pylint: disable=protected-access
if field_has_type(needle, field):
return True
return False
def field_has_type(needle: BaseType, field: BaseType) -> bool: # pylint: disable=too-many-return-statements, too-many-branches
"""
Return True if field haystack contains a field of type needle.
:param needle: A schematics field class to search for.
:param haystack: An instance of a schematics field within a model.
"""
if isinstance(field, needle):
return True
elif isinstance(field, ModelType):
if model_has_field_type(needle, field.model_class):
return True
elif isinstance(field, PolyModelType):
if needle in [type(obj) for obj in field.model_classes]:
return True
for obj in [obj for obj in field.model_classes if isinstance(obj, ModelType)]:
if model_has_field_type(needle, obj.model_class):
return True
elif isinstance(field, CompoundType):
if needle == type(field.field):
return True
try:
if needle == field.model_class:
return True
except AttributeError:
pass
else:
if model_has_field_type(needle, field.model_class):
return True
if field_has_type(needle, field.field):
return True
return False
def ensure_lists_in_model(raw_data: dict, model_cls: XMLModel):
"""
Ensure that single item lists are represented as lists and not dicts.
In XML single item lists are converted to dicts by xmltodict - there is essentially no
way for xmltodict to know that it *should* be a list not a dict.
:param raw_data:
:param model_cls:
"""
if not model_has_field_type(ListType, model_cls):
return raw_data
for _, field in model_cls._field_list: # pylint: disable=protected-access
key = field.serialized_name or field.name
try:
value = raw_data[key]
except KeyError:
continue
raw_data[key] = ensure_lists_in_value(value, field)
return raw_data
def ensure_lists_in_value(value: 'typing.Any', field: BaseType):
if value is None:
# Don't turn None items into a list of None items
return None
if isinstance(field, ListType):
if not isinstance(value, list):
value = [
ensure_lists_in_value(value, field.field)
]
elif field_has_type(ListType, field.field):
value = [
ensure_lists_in_value(_value, field.field)
for _value in value
]
elif field_has_type(ListType, field):
if isinstance(field, DictType):
for _key, _value in value.items():
value[_key] = ensure_lists_in_value(_value, field.field)
elif isinstance(field, ModelType):
value = ensure_lists_in_model(value, field.model_class)
return value
|
schematics-xml
|
/schematics-xml-0.2.1.tar.gz/schematics-xml-0.2.1/schematics_xml/models.py
|
models.py
|
import collections
import numbers
import lxml.builder
import lxml.etree
from schematics import Model
from schematics.types import BaseType, ModelType, CompoundType, ListType, DictType
from schematics.types.base import MultilingualStringType
from schematics.types.compound import PolyModelType
from xmltodict import parse
class XMLModel(Model):
"""
A model that can convert it's fields to and from XML.
"""
@property
def xml_root(self) -> str:
"""
Override this attribute to set the XML root returned by :py:meth:`.XMLModel.to_xml`.
"""
return type(self).__name__.lower()
#: Override this attribute to set the encoding specified in the XML returned by :py:meth:`.XMLModel.to_xml`.
xml_encoding = 'UTF-8'
def to_xml(self, role: str=None, app_data: dict=None, encoding: str=None, **kwargs) -> str:
"""
Return a string of XML that represents this model.
Currently all arguments are passed through to schematics.Model.to_primitive.
:param role: schematics Model to_primitive role parameter.
:param app_data: schematics Model to_primitive app_data parameter.
:param encoding: xml encoding attribute string.
:param kwargs: schematics Model to_primitive kwargs parameter.
"""
primitive = self.to_primitive(role=role, app_data=app_data, **kwargs)
root = self.primitive_to_xml(primitive)
return lxml.etree.tostring( # pylint: disable=no-member
root,
pretty_print=True,
xml_declaration=True,
encoding=encoding or self.xml_encoding
)
def primitive_to_xml(self, primitive: dict, parent: 'lxml.etree._Element'=None):
element_maker = lxml.builder.ElementMaker()
if parent is None:
parent = getattr(element_maker, self.xml_root)()
for key, value in primitive.items():
self.primitive_value_to_xml(key, parent, value)
return parent
def primitive_value_to_xml(self, key, parent, value):
element_maker = lxml.builder.ElementMaker()
if isinstance(value, bool):
parent.append(getattr(element_maker, key)('1' if value else '0'))
elif isinstance(value, numbers.Number) or isinstance(value, str):
parent.append(getattr(element_maker, key)(str(value)))
elif value is None:
parent.append(getattr(element_maker, key)(''))
elif isinstance(value, dict):
_parent = getattr(element_maker, key)()
parent.append(self.primitive_to_xml(value, _parent))
elif isinstance(value, collections.abc.Iterable):
for _value in value:
self.primitive_value_to_xml(key, parent, _value)
else:
raise TypeError('Unsupported data type: %s (%s)' % (value, type(value).__name__))
@classmethod
def from_xml(cls, xml: str) -> Model:
"""
Convert XML into a model.
:param xml: A string of XML that represents this Model.
"""
if model_has_field_type(MultilingualStringType, cls):
raise NotImplementedError("Field type 'MultilingualStringType' is not supported.")
primitive = parse(xml)
if len(primitive) != 1:
raise NotImplementedError
for _, raw_data in primitive.items():
if model_has_field_type(ListType, cls):
# We need to ensure that single item lists are actually lists and not dicts
raw_data = ensure_lists_in_model(raw_data, cls)
return cls(raw_data=raw_data)
def model_has_field_type(needle: BaseType, haystack: Model) -> bool:
"""
Return True if haystack contains a field of type needle.
Iterates over all fields (and into field if appropriate) and searches for field type *needle* in model
*haystack*.
:param needle: A schematics field class to search for.
:param haystack: A schematics model to search within.
"""
for _, field in haystack._field_list: # pylint: disable=protected-access
if field_has_type(needle, field):
return True
return False
def field_has_type(needle: BaseType, field: BaseType) -> bool: # pylint: disable=too-many-return-statements, too-many-branches
"""
Return True if field haystack contains a field of type needle.
:param needle: A schematics field class to search for.
:param haystack: An instance of a schematics field within a model.
"""
if isinstance(field, needle):
return True
elif isinstance(field, ModelType):
if model_has_field_type(needle, field.model_class):
return True
elif isinstance(field, PolyModelType):
if needle in [type(obj) for obj in field.model_classes]:
return True
for obj in [obj for obj in field.model_classes if isinstance(obj, ModelType)]:
if model_has_field_type(needle, obj.model_class):
return True
elif isinstance(field, CompoundType):
if needle == type(field.field):
return True
try:
if needle == field.model_class:
return True
except AttributeError:
pass
else:
if model_has_field_type(needle, field.model_class):
return True
if field_has_type(needle, field.field):
return True
return False
def ensure_lists_in_model(raw_data: dict, model_cls: XMLModel):
"""
Ensure that single item lists are represented as lists and not dicts.
In XML single item lists are converted to dicts by xmltodict - there is essentially no
way for xmltodict to know that it *should* be a list not a dict.
:param raw_data:
:param model_cls:
"""
if not model_has_field_type(ListType, model_cls):
return raw_data
for _, field in model_cls._field_list: # pylint: disable=protected-access
key = field.serialized_name or field.name
try:
value = raw_data[key]
except KeyError:
continue
raw_data[key] = ensure_lists_in_value(value, field)
return raw_data
def ensure_lists_in_value(value: 'typing.Any', field: BaseType):
if value is None:
# Don't turn None items into a list of None items
return None
if isinstance(field, ListType):
if not isinstance(value, list):
value = [
ensure_lists_in_value(value, field.field)
]
elif field_has_type(ListType, field.field):
value = [
ensure_lists_in_value(_value, field.field)
for _value in value
]
elif field_has_type(ListType, field):
if isinstance(field, DictType):
for _key, _value in value.items():
value[_key] = ensure_lists_in_value(_value, field.field)
elif isinstance(field, ModelType):
value = ensure_lists_in_model(value, field.model_class)
return value
| 0.727685 | 0.298798 |
2.1.1 / 2021-08-17
==================
- Update error message for incorrect choices field
`#572 <https://github.com/schematics/schematics/pull/572>`__
(`begor <https://github.com/begor>`__)
- Avoid some deprecation warnings when using Python 3
`#576 <https://github.com/schematics/schematics/pull/576>`__
(`jesuslosada <https://github.com/jesuslosada>`__)
- Fix EnumType enums with value=0 not working with use_values=True
`#594 <https://github.com/schematics/schematics/pull/594>`__
(`nikhilgupta345 <https://github.com/nikhilgupta345>`__)
- Fix syntax warning over comparison of literals using is.
`#611 <https://github.com/schematics/schematics/pull/611>`__
(`tirkarthi <https://github.com/tirkarthi>`__)
- Add help text generation capability to Models
`#543 <https://github.com/schematics/schematics/pull/543>`__
(`MartinHowarth <https://github.com/MartinHowarth>`__)
- Update documentation
`#578 <https://github.com/schematics/schematics/pull/578>`__
(`BobDu <https://github.com/BobDu>`__)
`#604 <https://github.com/schematics/schematics/pull/604>`__
(`BryanChan777 <https://github.com/BryanChan777>`__)
`#605 <https://github.com/schematics/schematics/pull/605>`__
(`timgates42 <https://github.com/timgates42>`__)
`#608 <https://github.com/schematics/schematics/pull/608>`__
(`dasubermanmind <https://github.com/dasubermanmind>`__)
- Add test coverage for model validation inside Dict/List
`#588 <https://github.com/schematics/schematics/pull/588>`__
(`borgstrom <https://github.com/borgstrom>`__)
- Added German translation
`#614 <https://github.com/schematics/schematics/pull/614>`__
(`hkage <https://github.com/hkage>`__)
2.1.0 / 2018-06-25
==================
**[BREAKING CHANGE]**
- Drop Python 2.6 support
`#517 <https://github.com/schematics/schematics/pull/517>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
Other changes:
- Add TimedeltaType
`#540 <https://github.com/schematics/schematics/pull/540>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Allow to create Model fields dynamically
`#512 <https://github.com/schematics/schematics/pull/512>`__
(`lkraider <https://github.com/lkraider>`__)
- Allow ModelOptions to have extra parameters
`#449 <https://github.com/schematics/schematics/pull/449>`__
(`rmb938 <https://github.com/rmb938>`__)
`#506 <https://github.com/schematics/schematics/pull/506>`__
(`ekampf <https://github.com/ekampf>`__)
- Accept callables as serialize roles
`#508 <https://github.com/schematics/schematics/pull/508>`__
(`lkraider <https://github.com/lkraider>`__)
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Simplify PolyModelType.find_model for readability
`#537 <https://github.com/schematics/schematics/pull/537>`__
(`kstrauser <https://github.com/kstrauser>`__)
- Enable PolyModelType recursive validation
`#535 <https://github.com/schematics/schematics/pull/535>`__
(`javiertejero <https://github.com/javiertejero>`__)
- Documentation fixes
`#509 <https://github.com/schematics/schematics/pull/509>`__
(`Tuoris <https://github.com/Tuoris>`__)
`#514 <https://github.com/schematics/schematics/pull/514>`__
(`tommyzli <https://github.com/tommyzli>`__)
`#518 <https://github.com/schematics/schematics/pull/518>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#546 <https://github.com/schematics/schematics/pull/546>`__
(`harveyslash <https://github.com/harveyslash>`__)
- Fix Model.init validation when partial is True
`#531 <https://github.com/schematics/schematics/issues/531>`__
(`lkraider <https://github.com/lkraider>`__)
- Minor number types refactor and mocking fixes
`#519 <https://github.com/schematics/schematics/pull/519>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#520 <https://github.com/schematics/schematics/pull/520>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
- Add ability to import models as strings
`#496 <https://github.com/schematics/schematics/pull/496>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Add EnumType
`#504 <https://github.com/schematics/schematics/pull/504>`__
(`ekamil <https://github.com/ekamil>`__)
- Dynamic models: Possible memory issues because of _subclasses
`#502 <https://github.com/schematics/schematics/pull/502>`__
(`mjrk <https://github.com/mjrk>`__)
- Add type hints to constructors of field type classes
`#488 <https://github.com/schematics/schematics/pull/488>`__
(`KonishchevDmitry <https://github.com/KonishchevDmitry>`__)
- Regression: Do not call field validator if field has not been set
`#499 <https://github.com/schematics/schematics/pull/499>`__
(`cmonfort <https://github.com/cmonfort>`__)
- Add possibility to translate strings and add initial pt_BR translations
`#495 <https://github.com/schematics/schematics/pull/495>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.1 / 2017-05-30
==================
- Support for raising DataError inside custom validate_fieldname methods.
`#441 <https://github.com/schematics/schematics/pull/441>`__
(`alexhayes <https://github.com/alexhayes>`__)
- Add specialized SchematicsDeprecationWarning.
(`lkraider <https://github.com/lkraider>`__)
- DateTimeType to_native method should handle type errors gracefully.
`#491 <https://github.com/schematics/schematics/pull/491>`__
(`e271828- <https://github.com/e271828->`__)
- Allow fields names to override the mapping-interface methods.
`#489 <https://github.com/schematics/schematics/pull/489>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.0 / 2017-05-22
==================
**[BREAKING CHANGE]**
Version 2.0 introduces many API changes, and it is not fully backwards-compatible with 1.x code.
`Full Changelog <https://github.com/schematics/schematics/compare/v1.1.2...v2.0.0>`_
- Add syntax highlighting to README examples
`#486 <https://github.com/schematics/schematics/pull/486>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Encode Unsafe data state in Model
`#484 <https://github.com/schematics/schematics/pull/484>`__
(`lkraider <https://github.com/lkraider>`__)
- Add MACAddressType
`#482 <https://github.com/schematics/schematics/pull/482>`__
(`aleksej-paschenko <https://github.com/aleksej-paschenko>`__)
2.0.0.b1 / 2017-04-06
=====================
- Enhancing and addressing some issues around exceptions:
`#477 <https://github.com/schematics/schematics/pull/477>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
- Allow primitive and native types to be inspected
`#431 <https://github.com/schematics/schematics/pull/431>`__
(`chadrik <https://github.com/chadrik>`__)
- Atoms iterator performance improvement
`#476 <https://github.com/schematics/schematics/pull/476>`__
(`vovanbo <https://github.com/vovanbo>`__)
- Fixes 453: Recursive import\_loop with ListType
`#475 <https://github.com/schematics/schematics/pull/475>`__
(`lkraider <https://github.com/lkraider>`__)
- Schema API
`#466 <https://github.com/schematics/schematics/pull/466>`__
(`lkraider <https://github.com/lkraider>`__)
- Tweak code example to avoid sql injection
`#462 <https://github.com/schematics/schematics/pull/462>`__
(`Ian-Foote <https://github.com/Ian-Foote>`__)
- Convert readthedocs links for their .org -> .io migration for hosted
projects `#454 <https://github.com/schematics/schematics/pull/454>`__
(`adamchainz <https://github.com/adamchainz>`__)
- Support all non-string Iterables as choices (dev branch)
`#436 <https://github.com/schematics/schematics/pull/436>`__
(`di <https://github.com/di>`__)
- When testing if a values is None or Undefined, use 'is'.
`#425 <https://github.com/schematics/schematics/pull/425>`__
(`chadrik <https://github.com/chadrik>`__)
2.0.0a1 / 2016-05-03
====================
- Restore v1 to\_native behavior; simplify converter code
`#412 <https://github.com/schematics/schematics/pull/412>`__
(`bintoro <https://github.com/bintoro>`__)
- Change conversion rules for booleans
`#407 <https://github.com/schematics/schematics/pull/407>`__
(`bintoro <https://github.com/bintoro>`__)
- Test for Model.\_\_init\_\_ context passing to types
`#399 <https://github.com/schematics/schematics/pull/399>`__
(`sheilatron <https://github.com/sheilatron>`__)
- Code normalization for Python 3 + general cleanup
`#391 <https://github.com/schematics/schematics/pull/391>`__
(`bintoro <https://github.com/bintoro>`__)
- Add support for arbitrary field metadata.
`#390 <https://github.com/schematics/schematics/pull/390>`__
(`chadrik <https://github.com/chadrik>`__)
- Introduce MixedType
`#380 <https://github.com/schematics/schematics/pull/380>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev2 / 2016-02-06
=======================
- Type maintenance
`#383 <https://github.com/schematics/schematics/pull/383>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev1 / 2016-02-01
=======================
- Performance optimizations
`#378 <https://github.com/schematics/schematics/pull/378>`__
(`bintoro <https://github.com/bintoro>`__)
- Validation refactoring + exception redesign
`#374 <https://github.com/schematics/schematics/pull/374>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix typo: serilaizataion --> serialization
`#373 <https://github.com/schematics/schematics/pull/373>`__
(`jeffwidman <https://github.com/jeffwidman>`__)
- Add support for undefined values
`#372 <https://github.com/schematics/schematics/pull/372>`__
(`bintoro <https://github.com/bintoro>`__)
- Serializable improvements
`#371 <https://github.com/schematics/schematics/pull/371>`__
(`bintoro <https://github.com/bintoro>`__)
- Unify import/export interface across all types
`#368 <https://github.com/schematics/schematics/pull/368>`__
(`bintoro <https://github.com/bintoro>`__)
- Correctly decode bytestrings in Python 3
`#365 <https://github.com/schematics/schematics/pull/365>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix NumberType.to\_native()
`#364 <https://github.com/schematics/schematics/pull/364>`__
(`bintoro <https://github.com/bintoro>`__)
- Make sure field.validate() uses a native type
`#363 <https://github.com/schematics/schematics/pull/363>`__
(`bintoro <https://github.com/bintoro>`__)
- Don't validate ListType items twice
`#362 <https://github.com/schematics/schematics/pull/362>`__
(`bintoro <https://github.com/bintoro>`__)
- Collect field validators as bound methods
`#361 <https://github.com/schematics/schematics/pull/361>`__
(`bintoro <https://github.com/bintoro>`__)
- Propagate environment during recursive import/export/validation
`#359 <https://github.com/schematics/schematics/pull/359>`__
(`bintoro <https://github.com/bintoro>`__)
- DateTimeType & TimestampType major rewrite
`#358 <https://github.com/schematics/schematics/pull/358>`__
(`bintoro <https://github.com/bintoro>`__)
- Always export empty compound objects as {} / []
`#351 <https://github.com/schematics/schematics/pull/351>`__
(`bintoro <https://github.com/bintoro>`__)
- export\_loop cleanup
`#350 <https://github.com/schematics/schematics/pull/350>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix FieldDescriptor.\_\_delete\_\_ to not touch model
`#349 <https://github.com/schematics/schematics/pull/349>`__
(`bintoro <https://github.com/bintoro>`__)
- Add validation method for latitude and longitude ranges in
GeoPointType
`#347 <https://github.com/schematics/schematics/pull/347>`__
(`wraziens <https://github.com/wraziens>`__)
- Fix longitude values for GeoPointType mock and add tests
`#344 <https://github.com/schematics/schematics/pull/344>`__
(`wraziens <https://github.com/wraziens>`__)
- Add support for self-referential ModelType fields
`#335 <https://github.com/schematics/schematics/pull/335>`__
(`bintoro <https://github.com/bintoro>`__)
- avoid unnecessary code path through try/except
`#327 <https://github.com/schematics/schematics/pull/327>`__
(`scavpy <https://github.com/scavpy>`__)
- Get mock object for ModelType and ListType
`#306 <https://github.com/schematics/schematics/pull/306>`__
(`kaiix <https://github.com/kaiix>`__)
1.1.3 / 2017-06-27
==================
* [Maintenance] (`#501 <https://github.com/schematics/schematics/issues/501>`_) Dynamic models: Possible memory issues because of _subclasses
1.1.2 / 2017-03-27
==================
* [Bug] (`#478 <https://github.com/schematics/schematics/pull/478>`_) Fix dangerous performance issue with ModelConversionError in nested models
1.1.1 / 2015-11-03
==================
* [Bug] (`befa202 <https://github.com/schematics/schematics/commit/befa202c3b3202aca89fb7ef985bdca06f9da37c>`_) Fix Unicode issue with DecimalType
* [Documentation] (`41157a1 <https://github.com/schematics/schematics/commit/41157a13896bd32a337c5503c04c5e9cc30ba4c7>`_) Documentation overhaul
* [Bug] (`860d717 <https://github.com/schematics/schematics/commit/860d71778421981f284c0612aec665ebf0cfcba2>`_) Fix import that was negatively affecting performance
* [Feature] (`93b554f <https://github.com/schematics/schematics/commit/93b554fd6a4e7b38133c4da5592b1843101792f0>`_) Add DataObject to datastructures.py
* [Bug] (`#236 <https://github.com/schematics/schematics/pull/236>`_) Set `None` on a field that's a compound type should honour that semantics
* [Maintenance] (`#348 <https://github.com/schematics/schematics/pull/348>`_) Update requirements
* [Maintenance] (`#346 <https://github.com/schematics/schematics/pull/346>`_) Combining Requirements
* [Maintenance] (`#342 <https://github.com/schematics/schematics/pull/342>`_) Remove to_primitive() method from compound types
* [Bug] (`#339 <https://github.com/schematics/schematics/pull/339>`_) Basic number validation
* [Bug] (`#336 <https://github.com/schematics/schematics/pull/336>`_) Don't evaluate serializable when accessed through class
* [Bug] (`#321 <https://github.com/schematics/schematics/pull/321>`_) Do not compile regex
* [Maintenance] (`#319 <https://github.com/schematics/schematics/pull/319>`_) Remove mock from install_requires
1.1.0 / 2015-07-12
==================
* [Feature] (`#303 <https://github.com/schematics/schematics/pull/303>`_) fix ListType, validate_items adds to errors list just field name without...
* [Feature] (`#304 <https://github.com/schematics/schematics/pull/304>`_) Include Partial Data when Raising ModelConversionError
* [Feature] (`#305 <https://github.com/schematics/schematics/pull/305>`_) Updated domain verifications to fit to RFC/working standards
* [Feature] (`#308 <https://github.com/schematics/schematics/pull/308>`_) Grennady ordered validation
* [Feature] (`#309 <https://github.com/schematics/schematics/pull/309>`_) improves date_time_type error message for custom formats
* [Feature] (`#310 <https://github.com/schematics/schematics/pull/310>`_) accept optional 'Z' suffix for UTC date_time_type format
* [Feature] (`#311 <https://github.com/schematics/schematics/pull/311>`_) Remove commented lines from models.py
* [Feature] (`#230 <https://github.com/schematics/schematics/pull/230>`_) Message normalization
1.0.4 / 2015-04-13
==================
* [Example] (`#286 <https://github.com/schematics/schematics/pull/286>`_) Add schematics usage with Django
* [Feature] (`#292 <https://github.com/schematics/schematics/pull/292>`_) increase domain length to 10 for .holiday, .vacations
* [Feature] (`#297 <https://github.com/schematics/schematics/pull/297>`_) Support for fields order in serialized format
* [Feature] (`#300 <https://github.com/schematics/schematics/pull/300>`_) increase domain length to 32
1.0.3 / 2015-03-07
==================
* [Feature] (`#284 <https://github.com/schematics/schematics/pull/284>`_) Add missing requirement for `six`
* [Feature] (`#283 <https://github.com/schematics/schematics/pull/283>`_) Update error msgs to print out invalid values in base.py
* [Feature] (`#281 <https://github.com/schematics/schematics/pull/281>`_) Update Model.__eq__
* [Feature] (`#267 <https://github.com/schematics/schematics/pull/267>`_) Type choices should be list or tuple
1.0.2 / 2015-02-12
==================
* [Bug] (`#280 <https://github.com/schematics/schematics/issues/280>`_) Fix the circular import issue.
1.0.1 / 2015-02-01
==================
* [Feature] (`#184 <https://github.com/schematics/schematics/issues/184>`_ / `03b2fd9 <https://github.com/schematics/schematics/commit/03b2fd97fb47c00e8d667cc8ea7254cc64d0f0a0>`_) Support for polymorphic model fields
* [Bug] (`#233 <https://github.com/schematics/schematics/pull/233>`_) Set field.owner_model recursively and honor ListType.field.serialize_when_none
* [Bug](`#252 <https://github.com/schematics/schematics/pull/252>`_) Fixed project URL
* [Feature] (`#259 <https://github.com/schematics/schematics/pull/259>`_) Give export loop to serializable when type has one
* [Feature] (`#262 <https://github.com/schematics/schematics/pull/262>`_) Make copies of inherited meta attributes when setting up a Model
* [Documentation] (`#276 <https://github.com/schematics/schematics/pull/276>`_) Improve the documentation of get_mock_object
1.0.0 / 2014-10-16
==================
* [Documentation] (`#239 <https://github.com/schematics/schematics/issues/239>`_) Fix typo with wording suggestion
* [Documentation] (`#244 <https://github.com/schematics/schematics/issues/244>`_) fix wrong reference in docs
* [Documentation] (`#246 <https://github.com/schematics/schematics/issues/246>`_) Using the correct function name in the docstring
* [Documentation] (`#245 <https://github.com/schematics/schematics/issues/245>`_) Making the docstring match actual parameter names
* [Feature] (`#241 <https://github.com/schematics/schematics/issues/241>`_) Py3k support
0.9.5 / 2014-07-19
==================
* [Feature] (`#191 <https://github.com/schematics/schematics/pull/191>`_) Updated import_data to avoid overwriting existing data. deserialize_mapping can now support partial and nested models.
* [Documentation] (`#192 <https://github.com/schematics/schematics/pull/192>`_) Document the creation of custom types
* [Feature] (`#193 <https://github.com/schematics/schematics/pull/193>`_) Add primitive types accepting values of any simple or compound primitive JSON type.
* [Bug] (`#194 <https://github.com/schematics/schematics/pull/194>`_) Change standard coerce_key function to unicode
* [Tests] (`#196 <https://github.com/schematics/schematics/pull/196>`_) Test fixes and cleanup
* [Feature] (`#197 <https://github.com/schematics/schematics/pull/197>`_) Giving context to serialization
* [Bug] (`#198 <https://github.com/schematics/schematics/pull/198>`_) Fixed typo in variable name in DateTimeType
* [Feature] (`#200 <https://github.com/schematics/schematics/pull/200>`_) Added the option to turn of strict conversion when creating a Model from a dict
* [Feature] (`#212 <https://github.com/schematics/schematics/pull/212>`_) Support exporting ModelType fields with subclassed model instances
* [Feature] (`#214 <https://github.com/schematics/schematics/pull/214>`_) Create mock objects using a class's fields as a template
* [Bug] (`#215 <https://github.com/schematics/schematics/pull/215>`_) PEP 8 FTW
* [Feature] (`#216 <https://github.com/schematics/schematics/pull/216>`_) Datastructures cleanup
* [Feature] (`#217 <https://github.com/schematics/schematics/pull/217>`_) Models cleanup pt 1
* [Feature] (`#218 <https://github.com/schematics/schematics/pull/218>`_) Models cleanup pt 2
* [Feature] (`#219 <https://github.com/schematics/schematics/pull/219>`_) Mongo cleanup
* [Feature] (`#220 <https://github.com/schematics/schematics/pull/220>`_) Temporal cleanup
* [Feature] (`#221 <https://github.com/schematics/schematics/pull/221>`_) Base cleanup
* [Feature] (`#224 <https://github.com/schematics/schematics/pull/224>`_) Exceptions cleanup
* [Feature] (`#225 <https://github.com/schematics/schematics/pull/225>`_) Validate cleanup
* [Feature] (`#226 <https://github.com/schematics/schematics/pull/226>`_) Serializable cleanup
* [Feature] (`#227 <https://github.com/schematics/schematics/pull/227>`_) Transforms cleanup
* [Feature] (`#228 <https://github.com/schematics/schematics/pull/228>`_) Compound cleanup
* [Feature] (`#229 <https://github.com/schematics/schematics/pull/229>`_) UUID cleanup
* [Feature] (`#231 <https://github.com/schematics/schematics/pull/231>`_) Booleans as numbers
0.9.4 / 2013-12-08
==================
* [Feature] (`#178 <https://github.com/schematics/schematics/pull/178>`_) Added deserialize_from flag to BaseType for alternate field names on import
* [Bug] (`#186 <https://github.com/schematics/schematics/pull/186>`_) Compoundtype support in ListTypes
* [Bug] (`#181 <https://github.com/schematics/schematics/pull/181>`_) Removed that stupid print statement!
* [Feature] (`#182 <https://github.com/schematics/schematics/pull/182>`_) Default roles system
* [Documentation] (`#190 <https://github.com/schematics/schematics/pull/190>`_) Typos
* [Bug] (`#177 <https://github.com/schematics/schematics/pull/177>`_) Removed `__iter__` from ModelMeta
* [Documentation] (`#188 <https://github.com/schematics/schematics/pull/188>`_) Typos
0.9.3 / 2013-10-20
==================
* [Documentation] More improvements
* [Feature] (`#147 <https://github.com/schematics/schematics/pull/147>`_) Complete conversion over to py.test
* [Bug] (`#176 <https://github.com/schematics/schematics/pull/176>`_) Fixed bug preventing clean override of options class
* [Bug] (`#174 <https://github.com/schematics/schematics/pull/174>`_) Python 2.6 support
0.9.2 / 2013-09-13
==================
* [Documentation] New History file!
* [Documentation] Major improvements to documentation
* [Feature] Renamed ``check_value`` to ``validate_range``
* [Feature] Changed ``serialize`` to ``to_native``
* [Bug] (`#155 <https://github.com/schematics/schematics/pull/155>`_) NumberType number range validation bugfix
|
schematics
|
/schematics-2.1.1.tar.gz/schematics-2.1.1/HISTORY.rst
|
HISTORY.rst
|
2.1.1 / 2021-08-17
==================
- Update error message for incorrect choices field
`#572 <https://github.com/schematics/schematics/pull/572>`__
(`begor <https://github.com/begor>`__)
- Avoid some deprecation warnings when using Python 3
`#576 <https://github.com/schematics/schematics/pull/576>`__
(`jesuslosada <https://github.com/jesuslosada>`__)
- Fix EnumType enums with value=0 not working with use_values=True
`#594 <https://github.com/schematics/schematics/pull/594>`__
(`nikhilgupta345 <https://github.com/nikhilgupta345>`__)
- Fix syntax warning over comparison of literals using is.
`#611 <https://github.com/schematics/schematics/pull/611>`__
(`tirkarthi <https://github.com/tirkarthi>`__)
- Add help text generation capability to Models
`#543 <https://github.com/schematics/schematics/pull/543>`__
(`MartinHowarth <https://github.com/MartinHowarth>`__)
- Update documentation
`#578 <https://github.com/schematics/schematics/pull/578>`__
(`BobDu <https://github.com/BobDu>`__)
`#604 <https://github.com/schematics/schematics/pull/604>`__
(`BryanChan777 <https://github.com/BryanChan777>`__)
`#605 <https://github.com/schematics/schematics/pull/605>`__
(`timgates42 <https://github.com/timgates42>`__)
`#608 <https://github.com/schematics/schematics/pull/608>`__
(`dasubermanmind <https://github.com/dasubermanmind>`__)
- Add test coverage for model validation inside Dict/List
`#588 <https://github.com/schematics/schematics/pull/588>`__
(`borgstrom <https://github.com/borgstrom>`__)
- Added German translation
`#614 <https://github.com/schematics/schematics/pull/614>`__
(`hkage <https://github.com/hkage>`__)
2.1.0 / 2018-06-25
==================
**[BREAKING CHANGE]**
- Drop Python 2.6 support
`#517 <https://github.com/schematics/schematics/pull/517>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
Other changes:
- Add TimedeltaType
`#540 <https://github.com/schematics/schematics/pull/540>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Allow to create Model fields dynamically
`#512 <https://github.com/schematics/schematics/pull/512>`__
(`lkraider <https://github.com/lkraider>`__)
- Allow ModelOptions to have extra parameters
`#449 <https://github.com/schematics/schematics/pull/449>`__
(`rmb938 <https://github.com/rmb938>`__)
`#506 <https://github.com/schematics/schematics/pull/506>`__
(`ekampf <https://github.com/ekampf>`__)
- Accept callables as serialize roles
`#508 <https://github.com/schematics/schematics/pull/508>`__
(`lkraider <https://github.com/lkraider>`__)
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Simplify PolyModelType.find_model for readability
`#537 <https://github.com/schematics/schematics/pull/537>`__
(`kstrauser <https://github.com/kstrauser>`__)
- Enable PolyModelType recursive validation
`#535 <https://github.com/schematics/schematics/pull/535>`__
(`javiertejero <https://github.com/javiertejero>`__)
- Documentation fixes
`#509 <https://github.com/schematics/schematics/pull/509>`__
(`Tuoris <https://github.com/Tuoris>`__)
`#514 <https://github.com/schematics/schematics/pull/514>`__
(`tommyzli <https://github.com/tommyzli>`__)
`#518 <https://github.com/schematics/schematics/pull/518>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#546 <https://github.com/schematics/schematics/pull/546>`__
(`harveyslash <https://github.com/harveyslash>`__)
- Fix Model.init validation when partial is True
`#531 <https://github.com/schematics/schematics/issues/531>`__
(`lkraider <https://github.com/lkraider>`__)
- Minor number types refactor and mocking fixes
`#519 <https://github.com/schematics/schematics/pull/519>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#520 <https://github.com/schematics/schematics/pull/520>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
- Add ability to import models as strings
`#496 <https://github.com/schematics/schematics/pull/496>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Add EnumType
`#504 <https://github.com/schematics/schematics/pull/504>`__
(`ekamil <https://github.com/ekamil>`__)
- Dynamic models: Possible memory issues because of _subclasses
`#502 <https://github.com/schematics/schematics/pull/502>`__
(`mjrk <https://github.com/mjrk>`__)
- Add type hints to constructors of field type classes
`#488 <https://github.com/schematics/schematics/pull/488>`__
(`KonishchevDmitry <https://github.com/KonishchevDmitry>`__)
- Regression: Do not call field validator if field has not been set
`#499 <https://github.com/schematics/schematics/pull/499>`__
(`cmonfort <https://github.com/cmonfort>`__)
- Add possibility to translate strings and add initial pt_BR translations
`#495 <https://github.com/schematics/schematics/pull/495>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.1 / 2017-05-30
==================
- Support for raising DataError inside custom validate_fieldname methods.
`#441 <https://github.com/schematics/schematics/pull/441>`__
(`alexhayes <https://github.com/alexhayes>`__)
- Add specialized SchematicsDeprecationWarning.
(`lkraider <https://github.com/lkraider>`__)
- DateTimeType to_native method should handle type errors gracefully.
`#491 <https://github.com/schematics/schematics/pull/491>`__
(`e271828- <https://github.com/e271828->`__)
- Allow fields names to override the mapping-interface methods.
`#489 <https://github.com/schematics/schematics/pull/489>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.0 / 2017-05-22
==================
**[BREAKING CHANGE]**
Version 2.0 introduces many API changes, and it is not fully backwards-compatible with 1.x code.
`Full Changelog <https://github.com/schematics/schematics/compare/v1.1.2...v2.0.0>`_
- Add syntax highlighting to README examples
`#486 <https://github.com/schematics/schematics/pull/486>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Encode Unsafe data state in Model
`#484 <https://github.com/schematics/schematics/pull/484>`__
(`lkraider <https://github.com/lkraider>`__)
- Add MACAddressType
`#482 <https://github.com/schematics/schematics/pull/482>`__
(`aleksej-paschenko <https://github.com/aleksej-paschenko>`__)
2.0.0.b1 / 2017-04-06
=====================
- Enhancing and addressing some issues around exceptions:
`#477 <https://github.com/schematics/schematics/pull/477>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
- Allow primitive and native types to be inspected
`#431 <https://github.com/schematics/schematics/pull/431>`__
(`chadrik <https://github.com/chadrik>`__)
- Atoms iterator performance improvement
`#476 <https://github.com/schematics/schematics/pull/476>`__
(`vovanbo <https://github.com/vovanbo>`__)
- Fixes 453: Recursive import\_loop with ListType
`#475 <https://github.com/schematics/schematics/pull/475>`__
(`lkraider <https://github.com/lkraider>`__)
- Schema API
`#466 <https://github.com/schematics/schematics/pull/466>`__
(`lkraider <https://github.com/lkraider>`__)
- Tweak code example to avoid sql injection
`#462 <https://github.com/schematics/schematics/pull/462>`__
(`Ian-Foote <https://github.com/Ian-Foote>`__)
- Convert readthedocs links for their .org -> .io migration for hosted
projects `#454 <https://github.com/schematics/schematics/pull/454>`__
(`adamchainz <https://github.com/adamchainz>`__)
- Support all non-string Iterables as choices (dev branch)
`#436 <https://github.com/schematics/schematics/pull/436>`__
(`di <https://github.com/di>`__)
- When testing if a values is None or Undefined, use 'is'.
`#425 <https://github.com/schematics/schematics/pull/425>`__
(`chadrik <https://github.com/chadrik>`__)
2.0.0a1 / 2016-05-03
====================
- Restore v1 to\_native behavior; simplify converter code
`#412 <https://github.com/schematics/schematics/pull/412>`__
(`bintoro <https://github.com/bintoro>`__)
- Change conversion rules for booleans
`#407 <https://github.com/schematics/schematics/pull/407>`__
(`bintoro <https://github.com/bintoro>`__)
- Test for Model.\_\_init\_\_ context passing to types
`#399 <https://github.com/schematics/schematics/pull/399>`__
(`sheilatron <https://github.com/sheilatron>`__)
- Code normalization for Python 3 + general cleanup
`#391 <https://github.com/schematics/schematics/pull/391>`__
(`bintoro <https://github.com/bintoro>`__)
- Add support for arbitrary field metadata.
`#390 <https://github.com/schematics/schematics/pull/390>`__
(`chadrik <https://github.com/chadrik>`__)
- Introduce MixedType
`#380 <https://github.com/schematics/schematics/pull/380>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev2 / 2016-02-06
=======================
- Type maintenance
`#383 <https://github.com/schematics/schematics/pull/383>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev1 / 2016-02-01
=======================
- Performance optimizations
`#378 <https://github.com/schematics/schematics/pull/378>`__
(`bintoro <https://github.com/bintoro>`__)
- Validation refactoring + exception redesign
`#374 <https://github.com/schematics/schematics/pull/374>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix typo: serilaizataion --> serialization
`#373 <https://github.com/schematics/schematics/pull/373>`__
(`jeffwidman <https://github.com/jeffwidman>`__)
- Add support for undefined values
`#372 <https://github.com/schematics/schematics/pull/372>`__
(`bintoro <https://github.com/bintoro>`__)
- Serializable improvements
`#371 <https://github.com/schematics/schematics/pull/371>`__
(`bintoro <https://github.com/bintoro>`__)
- Unify import/export interface across all types
`#368 <https://github.com/schematics/schematics/pull/368>`__
(`bintoro <https://github.com/bintoro>`__)
- Correctly decode bytestrings in Python 3
`#365 <https://github.com/schematics/schematics/pull/365>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix NumberType.to\_native()
`#364 <https://github.com/schematics/schematics/pull/364>`__
(`bintoro <https://github.com/bintoro>`__)
- Make sure field.validate() uses a native type
`#363 <https://github.com/schematics/schematics/pull/363>`__
(`bintoro <https://github.com/bintoro>`__)
- Don't validate ListType items twice
`#362 <https://github.com/schematics/schematics/pull/362>`__
(`bintoro <https://github.com/bintoro>`__)
- Collect field validators as bound methods
`#361 <https://github.com/schematics/schematics/pull/361>`__
(`bintoro <https://github.com/bintoro>`__)
- Propagate environment during recursive import/export/validation
`#359 <https://github.com/schematics/schematics/pull/359>`__
(`bintoro <https://github.com/bintoro>`__)
- DateTimeType & TimestampType major rewrite
`#358 <https://github.com/schematics/schematics/pull/358>`__
(`bintoro <https://github.com/bintoro>`__)
- Always export empty compound objects as {} / []
`#351 <https://github.com/schematics/schematics/pull/351>`__
(`bintoro <https://github.com/bintoro>`__)
- export\_loop cleanup
`#350 <https://github.com/schematics/schematics/pull/350>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix FieldDescriptor.\_\_delete\_\_ to not touch model
`#349 <https://github.com/schematics/schematics/pull/349>`__
(`bintoro <https://github.com/bintoro>`__)
- Add validation method for latitude and longitude ranges in
GeoPointType
`#347 <https://github.com/schematics/schematics/pull/347>`__
(`wraziens <https://github.com/wraziens>`__)
- Fix longitude values for GeoPointType mock and add tests
`#344 <https://github.com/schematics/schematics/pull/344>`__
(`wraziens <https://github.com/wraziens>`__)
- Add support for self-referential ModelType fields
`#335 <https://github.com/schematics/schematics/pull/335>`__
(`bintoro <https://github.com/bintoro>`__)
- avoid unnecessary code path through try/except
`#327 <https://github.com/schematics/schematics/pull/327>`__
(`scavpy <https://github.com/scavpy>`__)
- Get mock object for ModelType and ListType
`#306 <https://github.com/schematics/schematics/pull/306>`__
(`kaiix <https://github.com/kaiix>`__)
1.1.3 / 2017-06-27
==================
* [Maintenance] (`#501 <https://github.com/schematics/schematics/issues/501>`_) Dynamic models: Possible memory issues because of _subclasses
1.1.2 / 2017-03-27
==================
* [Bug] (`#478 <https://github.com/schematics/schematics/pull/478>`_) Fix dangerous performance issue with ModelConversionError in nested models
1.1.1 / 2015-11-03
==================
* [Bug] (`befa202 <https://github.com/schematics/schematics/commit/befa202c3b3202aca89fb7ef985bdca06f9da37c>`_) Fix Unicode issue with DecimalType
* [Documentation] (`41157a1 <https://github.com/schematics/schematics/commit/41157a13896bd32a337c5503c04c5e9cc30ba4c7>`_) Documentation overhaul
* [Bug] (`860d717 <https://github.com/schematics/schematics/commit/860d71778421981f284c0612aec665ebf0cfcba2>`_) Fix import that was negatively affecting performance
* [Feature] (`93b554f <https://github.com/schematics/schematics/commit/93b554fd6a4e7b38133c4da5592b1843101792f0>`_) Add DataObject to datastructures.py
* [Bug] (`#236 <https://github.com/schematics/schematics/pull/236>`_) Set `None` on a field that's a compound type should honour that semantics
* [Maintenance] (`#348 <https://github.com/schematics/schematics/pull/348>`_) Update requirements
* [Maintenance] (`#346 <https://github.com/schematics/schematics/pull/346>`_) Combining Requirements
* [Maintenance] (`#342 <https://github.com/schematics/schematics/pull/342>`_) Remove to_primitive() method from compound types
* [Bug] (`#339 <https://github.com/schematics/schematics/pull/339>`_) Basic number validation
* [Bug] (`#336 <https://github.com/schematics/schematics/pull/336>`_) Don't evaluate serializable when accessed through class
* [Bug] (`#321 <https://github.com/schematics/schematics/pull/321>`_) Do not compile regex
* [Maintenance] (`#319 <https://github.com/schematics/schematics/pull/319>`_) Remove mock from install_requires
1.1.0 / 2015-07-12
==================
* [Feature] (`#303 <https://github.com/schematics/schematics/pull/303>`_) fix ListType, validate_items adds to errors list just field name without...
* [Feature] (`#304 <https://github.com/schematics/schematics/pull/304>`_) Include Partial Data when Raising ModelConversionError
* [Feature] (`#305 <https://github.com/schematics/schematics/pull/305>`_) Updated domain verifications to fit to RFC/working standards
* [Feature] (`#308 <https://github.com/schematics/schematics/pull/308>`_) Grennady ordered validation
* [Feature] (`#309 <https://github.com/schematics/schematics/pull/309>`_) improves date_time_type error message for custom formats
* [Feature] (`#310 <https://github.com/schematics/schematics/pull/310>`_) accept optional 'Z' suffix for UTC date_time_type format
* [Feature] (`#311 <https://github.com/schematics/schematics/pull/311>`_) Remove commented lines from models.py
* [Feature] (`#230 <https://github.com/schematics/schematics/pull/230>`_) Message normalization
1.0.4 / 2015-04-13
==================
* [Example] (`#286 <https://github.com/schematics/schematics/pull/286>`_) Add schematics usage with Django
* [Feature] (`#292 <https://github.com/schematics/schematics/pull/292>`_) increase domain length to 10 for .holiday, .vacations
* [Feature] (`#297 <https://github.com/schematics/schematics/pull/297>`_) Support for fields order in serialized format
* [Feature] (`#300 <https://github.com/schematics/schematics/pull/300>`_) increase domain length to 32
1.0.3 / 2015-03-07
==================
* [Feature] (`#284 <https://github.com/schematics/schematics/pull/284>`_) Add missing requirement for `six`
* [Feature] (`#283 <https://github.com/schematics/schematics/pull/283>`_) Update error msgs to print out invalid values in base.py
* [Feature] (`#281 <https://github.com/schematics/schematics/pull/281>`_) Update Model.__eq__
* [Feature] (`#267 <https://github.com/schematics/schematics/pull/267>`_) Type choices should be list or tuple
1.0.2 / 2015-02-12
==================
* [Bug] (`#280 <https://github.com/schematics/schematics/issues/280>`_) Fix the circular import issue.
1.0.1 / 2015-02-01
==================
* [Feature] (`#184 <https://github.com/schematics/schematics/issues/184>`_ / `03b2fd9 <https://github.com/schematics/schematics/commit/03b2fd97fb47c00e8d667cc8ea7254cc64d0f0a0>`_) Support for polymorphic model fields
* [Bug] (`#233 <https://github.com/schematics/schematics/pull/233>`_) Set field.owner_model recursively and honor ListType.field.serialize_when_none
* [Bug](`#252 <https://github.com/schematics/schematics/pull/252>`_) Fixed project URL
* [Feature] (`#259 <https://github.com/schematics/schematics/pull/259>`_) Give export loop to serializable when type has one
* [Feature] (`#262 <https://github.com/schematics/schematics/pull/262>`_) Make copies of inherited meta attributes when setting up a Model
* [Documentation] (`#276 <https://github.com/schematics/schematics/pull/276>`_) Improve the documentation of get_mock_object
1.0.0 / 2014-10-16
==================
* [Documentation] (`#239 <https://github.com/schematics/schematics/issues/239>`_) Fix typo with wording suggestion
* [Documentation] (`#244 <https://github.com/schematics/schematics/issues/244>`_) fix wrong reference in docs
* [Documentation] (`#246 <https://github.com/schematics/schematics/issues/246>`_) Using the correct function name in the docstring
* [Documentation] (`#245 <https://github.com/schematics/schematics/issues/245>`_) Making the docstring match actual parameter names
* [Feature] (`#241 <https://github.com/schematics/schematics/issues/241>`_) Py3k support
0.9.5 / 2014-07-19
==================
* [Feature] (`#191 <https://github.com/schematics/schematics/pull/191>`_) Updated import_data to avoid overwriting existing data. deserialize_mapping can now support partial and nested models.
* [Documentation] (`#192 <https://github.com/schematics/schematics/pull/192>`_) Document the creation of custom types
* [Feature] (`#193 <https://github.com/schematics/schematics/pull/193>`_) Add primitive types accepting values of any simple or compound primitive JSON type.
* [Bug] (`#194 <https://github.com/schematics/schematics/pull/194>`_) Change standard coerce_key function to unicode
* [Tests] (`#196 <https://github.com/schematics/schematics/pull/196>`_) Test fixes and cleanup
* [Feature] (`#197 <https://github.com/schematics/schematics/pull/197>`_) Giving context to serialization
* [Bug] (`#198 <https://github.com/schematics/schematics/pull/198>`_) Fixed typo in variable name in DateTimeType
* [Feature] (`#200 <https://github.com/schematics/schematics/pull/200>`_) Added the option to turn of strict conversion when creating a Model from a dict
* [Feature] (`#212 <https://github.com/schematics/schematics/pull/212>`_) Support exporting ModelType fields with subclassed model instances
* [Feature] (`#214 <https://github.com/schematics/schematics/pull/214>`_) Create mock objects using a class's fields as a template
* [Bug] (`#215 <https://github.com/schematics/schematics/pull/215>`_) PEP 8 FTW
* [Feature] (`#216 <https://github.com/schematics/schematics/pull/216>`_) Datastructures cleanup
* [Feature] (`#217 <https://github.com/schematics/schematics/pull/217>`_) Models cleanup pt 1
* [Feature] (`#218 <https://github.com/schematics/schematics/pull/218>`_) Models cleanup pt 2
* [Feature] (`#219 <https://github.com/schematics/schematics/pull/219>`_) Mongo cleanup
* [Feature] (`#220 <https://github.com/schematics/schematics/pull/220>`_) Temporal cleanup
* [Feature] (`#221 <https://github.com/schematics/schematics/pull/221>`_) Base cleanup
* [Feature] (`#224 <https://github.com/schematics/schematics/pull/224>`_) Exceptions cleanup
* [Feature] (`#225 <https://github.com/schematics/schematics/pull/225>`_) Validate cleanup
* [Feature] (`#226 <https://github.com/schematics/schematics/pull/226>`_) Serializable cleanup
* [Feature] (`#227 <https://github.com/schematics/schematics/pull/227>`_) Transforms cleanup
* [Feature] (`#228 <https://github.com/schematics/schematics/pull/228>`_) Compound cleanup
* [Feature] (`#229 <https://github.com/schematics/schematics/pull/229>`_) UUID cleanup
* [Feature] (`#231 <https://github.com/schematics/schematics/pull/231>`_) Booleans as numbers
0.9.4 / 2013-12-08
==================
* [Feature] (`#178 <https://github.com/schematics/schematics/pull/178>`_) Added deserialize_from flag to BaseType for alternate field names on import
* [Bug] (`#186 <https://github.com/schematics/schematics/pull/186>`_) Compoundtype support in ListTypes
* [Bug] (`#181 <https://github.com/schematics/schematics/pull/181>`_) Removed that stupid print statement!
* [Feature] (`#182 <https://github.com/schematics/schematics/pull/182>`_) Default roles system
* [Documentation] (`#190 <https://github.com/schematics/schematics/pull/190>`_) Typos
* [Bug] (`#177 <https://github.com/schematics/schematics/pull/177>`_) Removed `__iter__` from ModelMeta
* [Documentation] (`#188 <https://github.com/schematics/schematics/pull/188>`_) Typos
0.9.3 / 2013-10-20
==================
* [Documentation] More improvements
* [Feature] (`#147 <https://github.com/schematics/schematics/pull/147>`_) Complete conversion over to py.test
* [Bug] (`#176 <https://github.com/schematics/schematics/pull/176>`_) Fixed bug preventing clean override of options class
* [Bug] (`#174 <https://github.com/schematics/schematics/pull/174>`_) Python 2.6 support
0.9.2 / 2013-09-13
==================
* [Documentation] New History file!
* [Documentation] Major improvements to documentation
* [Feature] Renamed ``check_value`` to ``validate_range``
* [Feature] Changed ``serialize`` to ``to_native``
* [Bug] (`#155 <https://github.com/schematics/schematics/pull/155>`_) NumberType number range validation bugfix
| 0.787278 | 0.657799 |
==========
Schematics
==========
.. rubric:: Python Data Structures for Humans™.
.. image:: https://travis-ci.org/schematics/schematics.svg?branch=master
:target: https://travis-ci.org/schematics/schematics
:alt: Build Status
.. image:: https://coveralls.io/repos/github/schematics/schematics/badge.svg?branch=master
:target: https://coveralls.io/github/schematics/schematics?branch=master
:alt: Coverage
About
=====
**Project documentation:** https://schematics.readthedocs.io/en/latest/
Schematics is a Python library to combine types into structures, validate them, and transform the shapes of your data based on simple descriptions.
The internals are similar to ORM type systems, but there is no database layer in Schematics. Instead, we believe that building a database layer is easily made when Schematics handles everything except for writing the query.
Schematics can be used for tasks where having a database involved is unusual.
Some common use cases:
+ Design and document specific `data structures <https://schematics.readthedocs.io/en/latest/usage/models.html>`_
+ `Convert structures <https://schematics.readthedocs.io/en/latest/usage/exporting.html#converting-data>`_ to and from different formats such as JSON or MsgPack
+ `Validate <https://schematics.readthedocs.io/en/latest/usage/validation.html>`_ API inputs
+ `Remove fields based on access rights <https://schematics.readthedocs.io/en/latest/usage/exporting.html>`_ of some data's recipient
+ Define message formats for communications protocols, like an RPC
+ Custom `persistence layers <https://schematics.readthedocs.io/en/latest/usage/models.html#model-configuration>`_
Example
=======
This is a simple Model.
.. code:: python
>>> from schematics.models import Model
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
.. code:: python
>>> import json
>>> json.dumps(person.to_primitive())
{"name": "Joe Strummer", "website": "http://soundcloud.com/joestrummer"}
Let's try validating without a name value, since it's required.
.. code:: python
>>> person = Person()
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "schematics/models.py", line 231, in validate
raise DataError(e.messages)
schematics.exceptions.DataError: {'name': ['This field is required.']}
Add the field and validation passes.
.. code:: python
>>> person = Person()
>>> person.name = 'Amon Tobin'
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
>>>
.. _coverage:
Testing & Coverage support
==========================
Run coverage and check the missing statements. ::
$ coverage run --source schematics -m py.test && coverage report
|
schematics
|
/schematics-2.1.1.tar.gz/schematics-2.1.1/README.rst
|
README.rst
|
==========
Schematics
==========
.. rubric:: Python Data Structures for Humans™.
.. image:: https://travis-ci.org/schematics/schematics.svg?branch=master
:target: https://travis-ci.org/schematics/schematics
:alt: Build Status
.. image:: https://coveralls.io/repos/github/schematics/schematics/badge.svg?branch=master
:target: https://coveralls.io/github/schematics/schematics?branch=master
:alt: Coverage
About
=====
**Project documentation:** https://schematics.readthedocs.io/en/latest/
Schematics is a Python library to combine types into structures, validate them, and transform the shapes of your data based on simple descriptions.
The internals are similar to ORM type systems, but there is no database layer in Schematics. Instead, we believe that building a database layer is easily made when Schematics handles everything except for writing the query.
Schematics can be used for tasks where having a database involved is unusual.
Some common use cases:
+ Design and document specific `data structures <https://schematics.readthedocs.io/en/latest/usage/models.html>`_
+ `Convert structures <https://schematics.readthedocs.io/en/latest/usage/exporting.html#converting-data>`_ to and from different formats such as JSON or MsgPack
+ `Validate <https://schematics.readthedocs.io/en/latest/usage/validation.html>`_ API inputs
+ `Remove fields based on access rights <https://schematics.readthedocs.io/en/latest/usage/exporting.html>`_ of some data's recipient
+ Define message formats for communications protocols, like an RPC
+ Custom `persistence layers <https://schematics.readthedocs.io/en/latest/usage/models.html#model-configuration>`_
Example
=======
This is a simple Model.
.. code:: python
>>> from schematics.models import Model
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
.. code:: python
>>> import json
>>> json.dumps(person.to_primitive())
{"name": "Joe Strummer", "website": "http://soundcloud.com/joestrummer"}
Let's try validating without a name value, since it's required.
.. code:: python
>>> person = Person()
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "schematics/models.py", line 231, in validate
raise DataError(e.messages)
schematics.exceptions.DataError: {'name': ['This field is required.']}
Add the field and validation passes.
.. code:: python
>>> person = Person()
>>> person.name = 'Amon Tobin'
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
>>>
.. _coverage:
Testing & Coverage support
==========================
Run coverage and check the missing statements. ::
$ coverage run --source schematics -m py.test && coverage report
| 0.927408 | 0.633878 |
Schematizer
===========
Schematizer is a lightweight library for data marshalling/unmarshalling in Python.
It helps you:
- **Validate** input and output data
- **Marshal** primitive data into a form you would like to interact with
- **Unmarshal** native data so that it can be rendered to JSON, YAML, MsgPack, etc.
Examples
--------
Simple.
.. code:: python
>>> from schematizer.exceptions import BaseValidationError
>>> from schematizer.schemas.compound import Dict, List
>>> from schematizer.schemas.simple import Date, Str
>>> from schematizer.validators import Length
>>>
>>> album_schema = Dict({
... 'title': Str(),
... 'released_at': Date(),
... })
>>>
>>> artist_schema = Dict({
... 'name': Str(),
... 'albums': List(album_schema),
... })
>>>
>>> artist_schema.to_native({
... 'name': 'Burzum',
... 'albums': [
... {
... 'title': 'Filosofem',
... 'released_at': '1996-01-01',
... },
... ],
... })
{'name': 'Burzum', 'albums': [{'title': 'Filosofem', 'released_at': datetime.date(1996, 1, 1)}]}
With invalid data.
.. code:: python
>>> try:
... artist_schema.to_native({
... 'albums': [
... {'released_at': '19960101'},
... ],
... })
... except BaseValidationError as exc:
... exc.flatten()
...
[
SimpleValidationError('MISSING', path=['name'], extra=None),
SimpleValidationError('MISSING', path=['albums', 0, 'title'], extra=None),
SimpleValidationError('INVALID', path=['albums', 0, 'released_at'], extra={'message': "time data '19960101' does not match format '%Y-%m-%d'"}),
]
Installation
------------
::
$ pip install schematizer
Documentation
-------------
Coming soon...
|
schematizer
|
/schematizer-0.9.4.tar.gz/schematizer-0.9.4/README.rst
|
README.rst
|
Schematizer
===========
Schematizer is a lightweight library for data marshalling/unmarshalling in Python.
It helps you:
- **Validate** input and output data
- **Marshal** primitive data into a form you would like to interact with
- **Unmarshal** native data so that it can be rendered to JSON, YAML, MsgPack, etc.
Examples
--------
Simple.
.. code:: python
>>> from schematizer.exceptions import BaseValidationError
>>> from schematizer.schemas.compound import Dict, List
>>> from schematizer.schemas.simple import Date, Str
>>> from schematizer.validators import Length
>>>
>>> album_schema = Dict({
... 'title': Str(),
... 'released_at': Date(),
... })
>>>
>>> artist_schema = Dict({
... 'name': Str(),
... 'albums': List(album_schema),
... })
>>>
>>> artist_schema.to_native({
... 'name': 'Burzum',
... 'albums': [
... {
... 'title': 'Filosofem',
... 'released_at': '1996-01-01',
... },
... ],
... })
{'name': 'Burzum', 'albums': [{'title': 'Filosofem', 'released_at': datetime.date(1996, 1, 1)}]}
With invalid data.
.. code:: python
>>> try:
... artist_schema.to_native({
... 'albums': [
... {'released_at': '19960101'},
... ],
... })
... except BaseValidationError as exc:
... exc.flatten()
...
[
SimpleValidationError('MISSING', path=['name'], extra=None),
SimpleValidationError('MISSING', path=['albums', 0, 'title'], extra=None),
SimpleValidationError('INVALID', path=['albums', 0, 'released_at'], extra={'message': "time data '19960101' does not match format '%Y-%m-%d'"}),
]
Installation
------------
::
$ pip install schematizer
Documentation
-------------
Coming soon...
| 0.806281 | 0.459501 |
https://www.postgresqltutorial.com/postgresql-string-functions/postgresql-to_char/
The format for the result string.
The following table illustrates the valid numeric format strings:
Format Description
9 Numeric value with the specified number of digits
0 Numeric value with leading zeros
. (period) decimal point
D decimal point that uses locale
, (comma) group (thousand) separator
FM Fill mode, which suppresses padding blanks and leading zeroes.
PR Negative value in angle brackets.
S Sign anchored to a number that uses locale
L Currency symbol that uses locale
G Group separator that uses locale
MI Minus sign in the specified position for numbers that are less than 0.
PL Plus sign in the specified position for numbers that are greater than 0.
SG Plus / minus sign in the specified position
RN Roman numeral that ranges from 1 to 3999
TH or th Upper case or lower case ordinal number suffix
The following table shows the valid timestamp format strings:
Pattern Description
Y,YYY year in 4 digits with comma
YYYY year in 4 digits
YYY last 3 digits of year
YY last 2 digits of year
Y The last digit of year
IYYY ISO 8601 week-numbering year (4 or more digits)
IYY Last 3 digits of ISO 8601 week-numbering year
IY Last 2 digits of ISO 8601 week-numbering year
I Last digit of ISO 8601 week-numbering year
BC, bc, AD or ad Era indicator without periods
B.C., b.c., A.D. ora.d. Era indicator with periods
MONTH English month name in uppercase
Month Full capitalized English month name
month Full lowercase English month name
MON Abbreviated uppercase month name e.g., JAN, FEB, etc.
Mon Abbreviated capitalized month name e.g, Jan, Feb, etc.
mon Abbreviated lowercase month name e.g., jan, feb, etc.
MM month number from 01 to 12
DAY Full uppercase day name
Day Full capitalized day name
day Full lowercase day name
DY Abbreviated uppercase day name
Dy Abbreviated capitalized day name
dy Abbreviated lowercase day name
DDD Day of year (001-366)
IDDD Day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)
DD Day of month (01-31)
D Day of the week, Sunday (1) to Saturday (7)
ID ISO 8601 day of the week, Monday (1) to Sunday (7)
W Week of month (1-5) (the first week starts on the first day of the month)
WW Week number of year (1-53) (the first week starts on the first day of the year)
IW Week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)
CC Century e.g, 21, 22, etc.
J Julian Day (integer days since November 24, 4714 BC at midnight UTC)
RM Month in upper case Roman numerals (I-XII; >
rm Month in lowercase Roman numerals (i-xii; >
HH Hour of day (0-12)
HH12 Hour of day (0-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)
MS Millisecond (000-999)
US Microsecond (000000-999999)
SSSS Seconds past midnight (0-86399)
AM, am, PM or pm Meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. Meridiem indicator (with periods)
Return value
|
schemawizard-package
|
/schemawizard_package-2.5.2.tar.gz/schemawizard_package-2.5.2/dateformat_readme.md
|
dateformat_readme.md
|
https://www.postgresqltutorial.com/postgresql-string-functions/postgresql-to_char/
The format for the result string.
The following table illustrates the valid numeric format strings:
Format Description
9 Numeric value with the specified number of digits
0 Numeric value with leading zeros
. (period) decimal point
D decimal point that uses locale
, (comma) group (thousand) separator
FM Fill mode, which suppresses padding blanks and leading zeroes.
PR Negative value in angle brackets.
S Sign anchored to a number that uses locale
L Currency symbol that uses locale
G Group separator that uses locale
MI Minus sign in the specified position for numbers that are less than 0.
PL Plus sign in the specified position for numbers that are greater than 0.
SG Plus / minus sign in the specified position
RN Roman numeral that ranges from 1 to 3999
TH or th Upper case or lower case ordinal number suffix
The following table shows the valid timestamp format strings:
Pattern Description
Y,YYY year in 4 digits with comma
YYYY year in 4 digits
YYY last 3 digits of year
YY last 2 digits of year
Y The last digit of year
IYYY ISO 8601 week-numbering year (4 or more digits)
IYY Last 3 digits of ISO 8601 week-numbering year
IY Last 2 digits of ISO 8601 week-numbering year
I Last digit of ISO 8601 week-numbering year
BC, bc, AD or ad Era indicator without periods
B.C., b.c., A.D. ora.d. Era indicator with periods
MONTH English month name in uppercase
Month Full capitalized English month name
month Full lowercase English month name
MON Abbreviated uppercase month name e.g., JAN, FEB, etc.
Mon Abbreviated capitalized month name e.g, Jan, Feb, etc.
mon Abbreviated lowercase month name e.g., jan, feb, etc.
MM month number from 01 to 12
DAY Full uppercase day name
Day Full capitalized day name
day Full lowercase day name
DY Abbreviated uppercase day name
Dy Abbreviated capitalized day name
dy Abbreviated lowercase day name
DDD Day of year (001-366)
IDDD Day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)
DD Day of month (01-31)
D Day of the week, Sunday (1) to Saturday (7)
ID ISO 8601 day of the week, Monday (1) to Sunday (7)
W Week of month (1-5) (the first week starts on the first day of the month)
WW Week number of year (1-53) (the first week starts on the first day of the year)
IW Week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)
CC Century e.g, 21, 22, etc.
J Julian Day (integer days since November 24, 4714 BC at midnight UTC)
RM Month in upper case Roman numerals (I-XII; >
rm Month in lowercase Roman numerals (i-xii; >
HH Hour of day (0-12)
HH12 Hour of day (0-12)
HH24 Hour of day (0-23)
MI Minute (0-59)
SS Second (0-59)
MS Millisecond (000-999)
US Microsecond (000000-999999)
SSSS Seconds past midnight (0-86399)
AM, am, PM or pm Meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. Meridiem indicator (with periods)
Return value
| 0.787727 | 0.88054 |
import datetime
import os
import sys
from sqlitedave_package.sqlitedave import sqlite_db
from postgresdave_package.postgresdave import postgres_db
from mysqldave_package.mysqldave import mysql_db
from garbledave_package.garbledave import garbledave
def main():
obj = schemawiz()
#obj.loadcsvfile('test.csv')
#tbl = obj.createload_mysql_from_csv('test.csv','test3')
#obj.justload_sqlite_from_csv('servers.csv','servers',True)
#print(obj.guess_sqlite_ddl('servers'))
"""
csvfilename = 'a.csv'
ddl = obj.guess_postgres_ddl(csvfilename.replace('.','_'))
print(ddl)
print('/* Tablename used : ' + obj.lastcall_tablename + ' */ \n')
print('/* Postgres DDL - END ----- ----- ----- ----- */ \n')
print(obj.dbthings.postgres_db.does_table_exist('newtbl'))
# add any specific known date formats
#obj.dbthings.postgres_date_formats.append('Mon DD,YY')
if csvfilename != '':
obj.loadcsvfile(csvfilename)
print('/* MySQL DDL - BEGIN ----- schemawiz().guess_mysql_ddl() ----- */ \n')
print(obj.guess_mysql_ddl('sample_csv'))
print('/* MySQL DDL - END ----- ----- ----- ----- */ \n')
print('/* Postgres DDL - BEGIN ----- schemawiz().guess_postgres_ddl() ----- */ \n')
ddl = obj.guess_postgres_ddl(csvfilename.replace('.','_'))
print('/* Tablename used : ' + obj.lastcall_tablename + ' */ \n')
print(ddl)
print('/* Postgres DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery DDL - BEGIN ----- schemawiz().guess_BigQuery_ddl() ----- */ \n')
print(obj.guess_BigQuery_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery External DDL - BEGIN ----- schemawiz().guess_BigQueryExternal_ddl() ----- */ \n')
print(obj.guess_BigQueryExternal_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery External DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery DDL - BEGIN ----- schemawiz().guess_BigQuery_ddl() ----- */ \n')
print(obj.guess_BigQuery_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery DDL - END ----- ----- ----- ----- */ \n')
"""
class database_type:
Postgres = 1
MySQL = 2
sqlite = 3
BigQuery = 4
class dbthinger:
def __init__(self,date_to_check=''):
self.sqlite_db = sqlite_db()
self.mysql_db = mysql_db()
self.postgres_db = postgres_db()
self.postgres_date_formats = ['YYYY/MM/DD','YYYY-MM-DD','YYYY-Mon-DD','MM/DD/YYYY','Mon-DD-YYYY','Mon-DD-YY','Month DD,YY','Month DD,YYYY','DD-Mon-YYYY','YY-Mon-DD','YYYYMMDD','YYMMDD','YYYY-DD-MM','Mon dd/YY']
self.postgres_timestamp_formats = ['YYYY-MM-DD HH:MI:SS']
self.mysql_date_formats = ['%b %d/%y','%m/%d/%Y','%Y/%m/%d']
self.mysql_timestamp_formats = ['%Y/%m/%d %H:%i:%s','%d/%m/%Y %T']
self.date_to_check = date_to_check
if date_to_check != '':
self.chk_date(date_to_check)
def ask_for_database_details(self,thisDatabaseType):
configfilename = '.schemawiz_config' + str(thisDatabaseType)
if thisDatabaseType == database_type.Postgres:
DB_NAME = input('DB_NAME (postgres): ') or 'postgres'
elif thisDatabaseType == database_type.MySQL:
DB_NAME = input('DB_NAME : ') or 'atlas'
elif thisDatabaseType == database_type.sqlite:
DB_NAME = input('DB_NAME : (local_sqlite_db)') or 'local_sqlite_db'
DB_HOST = ''
if (thisDatabaseType == database_type.Postgres) or (thisDatabaseType == database_type.MySQL):
DB_HOST = input('DB_HOST (localhost): ') or 'localhost'
DB_PORT = ''
if thisDatabaseType == database_type.Postgres:
DB_PORT = input('DB_PORT (1532): ') or '1532'
elif thisDatabaseType == database_type.MySQL:
DB_PORT = input('DB_PORT (3306): ') or '3306'
if thisDatabaseType == database_type.Postgres:
DB_USERNAME = input('DB_USERNAME (postgres): ') or 'postgres'
elif thisDatabaseType == database_type.MySQL:
DB_USERNAME = input('DB_USERNAME: ') or 'dave'
DB_SCHEMA = ''
if thisDatabaseType == database_type.Postgres:
DB_SCHEMA = input('DB_SCHEMA (public): ') or 'public'
if thisDatabaseType == database_type.Postgres:
DB_USERPWD = input('DB_USERPWD: ') or '4165605869'
elif thisDatabaseType == database_type.MySQL:
DB_USERPWD = input('DB_USERPWD: ') or 'dave'
if thisDatabaseType == database_type.Postgres:
self.postgres_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME,DB_SCHEMA)
elif thisDatabaseType == database_type.MySQL:
self.mysql_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME)
elif thisDatabaseType == database_type.sqlite:
self.sqlite_db.useConnectionDetails(DB_NAME)
ans_save_connection_details = input('Save connection details? (y/n) :') or 'y'
if ans_save_connection_details.upper() == 'Y':
f = open(configfilename,'w')
if thisDatabaseType == database_type.Postgres:
f.write(garbledave().garbleit(DB_USERNAME + ' - ' + DB_USERPWD + ' - ' + DB_HOST + ' - ' + DB_PORT + ' - ' + DB_NAME + ' - ' + DB_SCHEMA))
elif thisDatabaseType == database_type.MySQL:
f.write(garbledave().garbleit(DB_USERNAME + ' - ' + DB_USERPWD + ' - ' + DB_HOST + ' - ' + DB_PORT + ' - ' + DB_NAME))
elif thisDatabaseType == database_type.sqlite:
f.write(garbledave().garbleit(DB_NAME + ' - '))
f.close()
def connect_local_db(self,thisDatabaseType):
configfilename = '.schemawiz_config' + str(thisDatabaseType)
if (((thisDatabaseType == database_type.sqlite) and (not self.sqlite_db.dbconn)) or (thisDatabaseType == database_type.Postgres) and (not self.postgres_db.dbconn)) or ((thisDatabaseType == database_type.MySQL) and (not self.mysql_db.dbconn)):
try:
f = open(configfilename,'r')
config_line = garbledave().ungarbleit(f.readline())
dbsettings = config_line.split(' - ')
f.close()
if thisDatabaseType == database_type.sqlite:
DB_NAME = dbsettings[0]
self.sqlite_db.useConnectionDetails(DB_NAME)
else:
DB_USERNAME = dbsettings[0]
DB_USERPWD = dbsettings[1]
DB_HOST = dbsettings[2]
DB_PORT = dbsettings[3]
DB_NAME = dbsettings[4]
if thisDatabaseType == database_type.Postgres:
DB_SCHEMA = dbsettings[5]
self.postgres_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME,DB_SCHEMA)
elif thisDatabaseType == database_type.MySQL:
self.mysql_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME)
except Exception as e:
self.ask_for_database_details(thisDatabaseType)
def chk_date(self,possible_date_str):
print (" Checking date " + possible_date_str) #
self.date_type = self.match_date_type(possible_date_str)
if self.date_type == -1:
print('Not a date. date_type = ' + str(self.date_type))
else:
print('Is a date, and matchs date_type ' + str(self.date_type) + ', ' + self.postgres_date_formats[self.date_type])
return self.date_type
def chk_date_format_old(self,date_string,date_format):
try:
dateObject = datetime.datetime.strptime(date_string, date_format)
return True
except ValueError:
return False
def is_an_int(self,prm):
try:
if int(prm) == int(prm):
return True
else:
return False
except:
return False
def is_a_float(self,prm):
try:
if float(prm) == float(prm):
return True
else:
return False
except:
return False
def match_timestamp_type(self,timestamp_string,thisdatabase_type):
if thisdatabase_type == database_type.Postgres:
for i in range(0,len(self.postgres_timestamp_formats)):
fmt = self.postgres_timestamp_formats[i]
if self.chk_postrgres_timestamp_format(timestamp_string,fmt):
return i
else:
return -1
elif thisdatabase_type == database_type.MySQL:
for i in range(0,len(self.mysql_timestamp_formats)):
fmt = self.mysql_timestamp_formats[i]
if self.chk_mysql_timestamp_format(timestamp_string,fmt):
return i
else:
return -1
def chk_mysql_timestamp_format(self,timestamp_string,date_format):
retval = False
if len(timestamp_string) > 12:
sql = "SELECT CASE WHEN STR_TO_DATE('" + timestamp_string + "','" + date_format + "') is not null THEN 'Good' ELSE 'Bad' END as date_reasonablness"
try:
#print(sql)
#sys.exit(0)
if self.mysql_db.queryone(sql) == 'Good':
retval = True
except:
retval = False
return retval
def chk_postrgres_timestamp_format(self,timestamp_string,date_format):
retval = False
if len(timestamp_string) > 12:
sql = "SELECT to_char('" + timestamp_string + "'::timestamp,'" + date_format + "')"
try:
#print(sql)
return_fmt = self.postgres_db.queryone(sql)
retval = True
except Exception as e:
retval = False
return retval
# -1 means no matching date format
# > -1 means the date format matches self.postgres_date_formats[return_value]
def match_date_type(self,date_string,thisdatabase_type):
fmtdict = {}
dateformatscore = {}
bestchoice = -1
bestfmt = -1
besthits = -1
# might be a date
if (((self.is_an_int(date_string) and len(date_string) == 8)) or ((not self.is_an_int(date_string)) and (len(date_string) > 5) and (len(date_string) < 12))):
# loadup with default date formats
if thisdatabase_type == database_type.Postgres:
for i in range(0,len(self.postgres_date_formats)):
dateformatscore[self.postgres_date_formats[i]] = 0
fmtdict[self.postgres_date_formats[i]] = i
elif thisdatabase_type == database_type.MySQL:
for i in range(0,len(self.mysql_date_formats)):
dateformatscore[self.mysql_date_formats[i]] = 0
fmtdict[self.mysql_date_formats[i]] = i
for i in range(0,len(dateformatscore)):
retval = False
if thisdatabase_type == database_type.Postgres:
retval = self.chk_postgres_date_format(date_string,self.postgres_date_formats[i])
if retval:
dateformatscore[self.postgres_date_formats[i]] += 1
elif thisdatabase_type == database_type.MySQL:
retval = self.chk_mysql_date_format(date_string,self.mysql_date_formats[i])
if retval:
dateformatscore[self.mysql_date_formats[i]] += 1
for fmt in dateformatscore:
if dateformatscore[fmt] > bestchoice:
bestchoice = dateformatscore[fmt]
bestfmt = fmt
if bestchoice > 0:
return fmtdict[bestfmt]
else:
return -1
def match_float_type(self,floatvalue):
return self.is_a_float(floatvalue)
def match_integer_type(self,intvalue):
return self.is_an_int(intvalue)
def chk_mysql_date_format(self,date_string,date_format):
sql = """
SELECT CASE WHEN STR_TO_DATE('""" + date_string + """','""" + date_format + """') is null THEN 'bad'
ELSE 'Good'
END as date_reasonablness
"""
try:
#print(sql)
#sys.exit(0)
return_fmt = self.mysql_db.queryone(sql)
if return_fmt == 'Good':
return True
else:
return False
except Exception as e:
return False
def chk_postgres_date_format(self,date_string,date_format):
sql = """
SELECT CASE WHEN abs( to_date('""" + date_string + """','""" + date_format + """') - current_date) > 36500 THEN 'bad'
ELSE 'Good'
END as date_reasonablness
"""
try:
return_fmt = self.postgres_db.queryone(sql)
if return_fmt == 'Good':
return True
else:
return False
except Exception as e:
return False
class schemawiz:
def __init__(self,csvfilename=''):
self.version=2.0
self.dbthings = dbthinger()
self.force_delimiter = ''
self.lastcall_tablename = ''
self.delimiter = ''
self.delimiter_replace = '^~^'
self.logging_on = False
self.SomeFileContents = []
self.column_names = []
self.column_datatypes = []
self.BigQuery_datatypes = []
self.mysql_datatypes = []
self.sqlite_datatypes = []
self.column_sample = []
self.column_dateformats = []
self.analyzed = False
self.IsaDateField = False
self.DateField = ''
self.clusterField1 = ''
self.clusterField2 = ''
self.clusterField3 = ''
self.csvfilename = ''
if csvfilename != '':
self.loadcsvfile(csvfilename)
def newpostgresconnection(self):
os.remove('.schemawiz_config' + str(database_type.Postgres))
def newmysqlconnection(self):
os.remove('.schemawiz_config' + str(database_type.MySQL))
def newsqliteconnection(self):
os.remove('.schemawiz_config' + str(database_type.sqlite))
def newconnections(self):
self.newpostgresconnection()
self.newmysqlconnection()
self.newsqliteconnection()
def justload_sqlite_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
if self.dbthings.sqlite_db.does_table_exist(tablename):
self.dbthings.sqlite_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.sqlite_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_postgres_from_csv(csvfilename)')
return return_value
def createload_sqlite_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
print(csvfilename)
ddl = self.guess_sqlite_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.sqlite_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.sqlite_db.execute(ddl)
self.dbthings.sqlite_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.sqlite_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def justload_postgres_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
if self.dbthings.postgres_db.does_table_exist(tablename):
self.dbthings.postgres_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.postgres_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_postgres_from_csv(csvfilename)')
return return_value
def createload_postgres_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
ddl = self.guess_postgres_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.postgres_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.postgres_db.execute(ddl)
self.dbthings.postgres_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.postgres_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def justload_mysql_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
self.dbthings.mysql_db.connect()
if self.dbthings.mysql_db.does_table_exist(tablename):
self.dbthings.mysql_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.mysql_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_mysql_from_csv(csvfilename)')
return return_value
def createload_mysql_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
ddl = self.guess_mysql_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.mysql_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.mysql_db.execute(ddl)
self.dbthings.mysql_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.mysql_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def add_date_format(self,dt_fmt):
self.dbthings.mysql_date_formats.append(dt_fmt)
self.dbthings.postgres_date_formats.append(dt_fmt)
def add_timestamp_format(self,tmsp_fmt):
self.dbthings.mysql_timestamp_formats.append(tmsp_fmt)
self.dbthings.postgres_timestamp_formats.append(tmsp_fmt)
def lastcall_delimiter(self):
return self.delimiter
def utf8len(self,s):
return len(s.encode('utf-8'))
def logger(self,logline):
if self.logging_on:
print(logline)
def loadcsvfile(self,csvfilename):
if csvfilename != '':
try:
with open(csvfilename) as f:
for csvline in f:
self.csvfilename = csvfilename
self.delimiter = self.GuessDelimiter(csvline)
break
except Exception as e:
print('Cannot read file: ' + csvfilename)
sys.exit(0)
else:
print('schemawiz.loadcsvfile(csvfilename) requires a valid csv file.')
sys.exit(0)
def analyze_csvfile(self,thisdatabase_type):
self.analyzed = False
if self.csvfilename == '':
print('/* No csvfilename was provided to schemawiz.loadcsvfile(). Will use empty template */\n')
self.SomeFileContents.append('field1,field2,field3,field4,field5')
self.SomeFileContents.append('1999/02/18,0,0.001,textD,textE')
self.get_column_names()
self.get_column_types(thisdatabase_type)
self.analyzed = True
else:
self.logger('Checking file size for ' + self.csvfilename + '\n')
file_stats = os.stat(self.csvfilename)
linecount = 0
total_linesize = 0
with open(self.csvfilename) as f:
for line in f:
linecount += 1
if linecount != 1:
total_linesize += self.utf8len(line)
if linecount == 11:
self.datalinesize = total_linesize/10
self.SomeFileContents.append(line)
if (linecount>100):
break
#self.logger('file has ' + str(len(self.SomeFileContents)) + ' lines')
#self.logger('line size is ' + str(self.datalinesize) + ' ytes')
#self.logger('file size is ' + str(file_stats.st_size) + ' bytes')
self.get_column_names()
self.get_column_types(thisdatabase_type)
self.analyzed = True
def get_just_filename(self):
justfilename=''
if self.csvfilename.find('\\') > -1: # have a path and dirs
fileparts = self.csvfilename.split('\\')
justfilename = fileparts[len(fileparts)-1]
else:
if self.csvfilename != '':
justfilename = self.csvfilename
return justfilename
def gettablename(self):
now = (datetime.datetime.now())
rando_tablename= 'tblcsv_' + str(now.year) + ('0' + str(now.month))[-2:] + str(now.day) + str(now.hour) + str(now.minute)
return rando_tablename
def count_chars(self,data,exceptchars=''):
chars_in_hdr = {}
for i in range(0,len(data)):
if data[i] != '\n' and exceptchars.find(data[i]) == -1:
if data[i] in chars_in_hdr:
chars_in_hdr[data[i]] += 1
else:
chars_in_hdr[data[i]] = 1
return chars_in_hdr
def count_alpha(self,alphadict):
count = 0
for ch in alphadict:
if 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(ch) > -1:
count += alphadict[ch]
return count
def count_nbr(self,alphadict):
count = 0
for ch in alphadict:
if '0123456789'.find(ch) > -1:
count += alphadict[ch]
return count
def count_decimals(self,alphadict):
count = 0
for ch in alphadict:
if '.'.find(ch) > -1:
count += alphadict[ch]
return count
def get_datatype(self,datavalue,thisdatabase_type):
chardict = {}
data = ''
if datavalue[0:1] == '"' and datavalue[-1:] == '"':
#self.logger('enclosed in quotes ""')
data = datavalue[1:-1]
#self.logger('data: ' + data)
else:
data = datavalue.strip()
chardict = self.count_chars(data)
alphacount = self.count_alpha(chardict)
nbrcount = self.count_nbr(chardict)
deccount = self.count_decimals(chardict)
lookslike = ''
dtformat = ''
timestamp_nbr = -1
date_format_nbr = -1
if thisdatabase_type != database_type.sqlite:
timestamp_nbr = self.dbthings.match_timestamp_type(data,thisdatabase_type)
date_format_nbr = self.dbthings.match_date_type(data,thisdatabase_type)
if timestamp_nbr != -1:
lookslike = 'timestamp'
if thisdatabase_type == database_type.Postgres:
dtformat = self.dbthings.postgres_timestamp_formats[timestamp_nbr]
elif thisdatabase_type == database_type.MySQL:
dtformat = self.dbthings.mysql_timestamp_formats[timestamp_nbr]
elif date_format_nbr != -1:
lookslike = 'date'
if thisdatabase_type == database_type.Postgres:
dtformat = self.dbthings.postgres_date_formats[date_format_nbr]
elif thisdatabase_type == database_type.MySQL:
dtformat = self.dbthings.mysql_date_formats[date_format_nbr]
elif alphacount == 0 and deccount == 1:
# 123.123232222
if self.dbthings.match_float_type(data):
lookslike = 'numeric'
else:
lookslike = 'text'
elif self.dbthings.match_integer_type(data) :
lookslike = 'bigint'
else:
lookslike = 'text'
return lookslike,dtformat
def handledblquotes(self,rowwithquotes):
newstr = ''
quotecount = 0
cvtmode = False
for i in range (0,len(rowwithquotes)-1):
if rowwithquotes[i] == '"':
quotecount += 1
if (quotecount % 2) == 1:
cvtmode = True
else:
cvtmode = False
if cvtmode and rowwithquotes[i] == self.delimiter:
newstr += self.delimiter_replace
elif rowwithquotes[i] != '"':
newstr += rowwithquotes[i]
return newstr
def get_column_types(self,thisdatabase_type):
found_datatypes = {}
found_datavalues = {}
found_datefomat = {}
for i in range(1,len(self.SomeFileContents)):
cvted_str = self.handledblquotes(self.SomeFileContents[i])
dataline = cvted_str.strip().split(self.delimiter)
for j in range(0,len(dataline)):
fld = dataline[j].replace(self.delimiter_replace,self.delimiter)
if self.column_names[j].lower().endswith('_text'):
thisdatatype = 'text'
dtformat = ''
else:
thisdatatype,dtformat = self.get_datatype(fld,thisdatabase_type)
#print(thisdatatype)
if self.column_names[j] not in found_datatypes:
found_datatypes[self.column_names[j]] = thisdatatype
found_datavalues[self.column_names[j]] = fld
found_datefomat[self.column_names[j]] = dtformat
else:
if found_datatypes[self.column_names[j]] == 'date' and thisdatatype =='date' and found_datefomat[self.column_names[j]] != dtformat:
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] == 'timestamp' and thisdatatype =='timestamp' and found_datefomat[self.column_names[j]] != dtformat:
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] != thisdatatype:
if found_datatypes[self.column_names[j]] == 'text' or thisdatatype == 'text':
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] == 'numeric' or thisdatatype == 'numeric':
found_datatypes[self.column_names[j]] == 'numeric'
elif found_datatypes[self.column_names[j]] == 'date' or thisdatatype == 'date':
found_datatypes[self.column_names[j]] == 'text'
for k in range(0,len(self.column_names)):
if self.column_names[k] not in found_datavalues:
found_datavalues[self.column_names[k]] = ''
found_datefomat[self.column_names[k]] = ''
found_datatypes[self.column_names[k]] = 'text'
self.column_sample.append(found_datavalues[self.column_names[k]].replace('"',''))
self.column_dateformats.append(found_datefomat[self.column_names[k]])
self.column_datatypes.append(found_datatypes[self.column_names[k]])
self.mysql_datatypes.append(self.translate_dt(database_type.MySQL,found_datatypes[self.column_names[k]]))
self.BigQuery_datatypes.append(self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]))
self.sqlite_datatypes.append(self.translate_dt(database_type.sqlite,found_datatypes[self.column_names[k]]))
if not self.IsaDateField and self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]) == 'DATE':
self.IsaDateField = True
self.DateField = self.column_names[k]
elif self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]) != 'FLOAT64':
if self.clusterField1 == '':
self.clusterField1 = self.column_names[k]
elif self.clusterField2 == '':
self.clusterField2 = self.column_names[k]
elif self.clusterField3 == '':
self.clusterField3 = self.column_names[k]
for m in range(0,len(self.column_datatypes)):
self.logger('column ' + str(self.column_names[m]) + ' has data type ' + str(self.column_datatypes[m]))
def translate_dt(self,targettype,postgres_datatype):
if targettype == database_type.BigQuery:
if postgres_datatype.lower().strip() == 'text':
return 'STRING'
elif postgres_datatype.lower().strip() == 'date':
return 'DATE'
elif postgres_datatype.lower().strip() == 'timestamp':
return 'TIMESTAMP'
elif postgres_datatype.lower().strip() == 'integer' or postgres_datatype.lower().strip() == 'bigint':
return 'INT64'
elif postgres_datatype.lower().strip() == 'numeric':
return 'FLOAT64'
else:
return 'UNKNOWN'
elif targettype == database_type.MySQL:
if postgres_datatype.lower().strip() == 'numeric':
return 'float'
else:
return postgres_datatype
elif targettype == database_type.sqlite:
if postgres_datatype.lower().strip() == 'integer' or postgres_datatype.lower().strip() == 'bigint':
return 'integer'
elif postgres_datatype.lower().strip() == 'numeric':
return 'real'
else:
return 'text'
else:
return postgres_datatype
def clean_text(self,ptext): # remove optional double quotes
text = ptext.strip()
if (text[:1] == '"' and text[-1:] == '"'):
return text[1:-1]
else:
return text
def clean_column_name(self,col_name):
col = col_name.replace(' ','_')
new_column_name = ''
for i in range(0,len(col)):
if 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'.find(col[i]) > -1:
new_column_name += col[i]
return new_column_name
def get_column_names(self):
self.delimiter = self.GuessDelimiter(self.SomeFileContents[0])
self.logger('file delimiter is ' + self.delimiter)
self.column_names = self.SomeFileContents[0].strip().split(self.delimiter)
self.logger('Column Names are ' + str(self.column_names))
for i in range(0,len(self.column_names)):
self.column_names[i] = self.clean_column_name(self.column_names[i])
def GuessDelimiter(self,first_row):
if self.force_delimiter != '':
delimiter_guess = self.force_delimiter
else:
if first_row.find('\t') > -1:
delimiter_guess = '\t'
elif first_row.find(',') > -1:
delimiter_guess = ','
else:
delimiter_guess = '~'
return delimiter_guess
def guess_BigQueryExternal_ddl(self,useproject='',usedataset='',usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if useproject == '':
project = 'schemawiz-123'
else:
project = useproject
if usedataset == '':
dataset = 'sampledataset'
else:
dataset = usedataset
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
project = project.replace(' ','').lower()
dataset = dataset.replace(' ','').lower()
tablename = tablename.replace(' ','').lower()
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL) # database_type.BigQuery
sql = 'CREATE EXTERNAL TABLE IF NOT EXISTS `' + project + '.' + dataset + '.' + tablename + '` (\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.BigQuery_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if self.BigQuery_datatypes[i].strip().lower() == 'date' or self.BigQuery_datatypes[i].strip().lower() == 'timestamp':
sql += "OPTIONS (description='" + self.BigQuery_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]')"
sql += ',\n'
sql = sql[:-2] + '\n)'
sql += " OPTIONS (\n format = 'CSV',\n Field_delimiter = '" + self.delimiter + "',\n uris = ['gs://bucket/"
sql += self.get_just_filename() + "*'],\n skip_leading_rows = 1,\n "
sql += "description='" + "This externally stored, BigQuery table was defined by schemawiz for creating a BQ table to use csv files as source.'\n);"
return sql
def guess_BigQuery_ddl(self,useproject='',usedataset='',usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if useproject == '':
project = 'schemawiz-123'
else:
project = useproject
if usedataset == '':
dataset = 'sampledataset'
else:
dataset = usedataset
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
project = project.replace(' ','').lower()
dataset = dataset.replace(' ','').lower()
tablename = tablename.replace(' ','').lower()
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL) # database_type.BigQuery
sql = 'CREATE TABLE IF NOT EXISTS `' + project + '.' + dataset + '.' + tablename + '` (\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.BigQuery_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if self.BigQuery_datatypes[i].strip().lower() == 'date' or self.BigQuery_datatypes[i].strip().lower() == 'timestamp':
sql += "OPTIONS (description='" + self.BigQuery_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]')"
sql += ',\n'
sql = sql[:-2] + '\n)\n'
if self.IsaDateField:
sql += 'PARTITION BY ' + self.DateField + '\n'
if self.clusterField1 != '':
sql += 'CLUSTER BY \n ' + self.clusterField1 + ',\n'
if self.clusterField2 != '':
sql += ' ' + self.clusterField2 + ',\n'
if self.clusterField3 != '':
sql += ' ' + self.clusterField3 + ',\n'
sql = sql[:-2]
sql += "\nOPTIONS (\n require_partition_filter = False,\n "
sql += "description = 'This BigQuery table was defined by schemawiz for loading the csv file " + self.get_just_filename() + ", delimiter (" + self.delimiter + ")' \n);"
return sql
def guess_sqlite_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.sqlite)
if not self.analyzed:
self.analyze_csvfile(database_type.sqlite)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
fldcommentsql = ''
sql = '/* DROP TABLE IF EXISTS ' + tablename + '; */\n'
sql += 'CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.sqlite_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ ,\n'
sql = sql[:-2] + '\n);\n\n'
return sql
def guess_postgres_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.Postgres)
if not self.analyzed:
self.analyze_csvfile(database_type.Postgres)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
fldcommentsql = ''
sql = 'DROP TABLE IF EXISTS ' + tablename + ';\n'
sql += 'CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.column_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ ,\n'
if self.column_datatypes[i].strip().lower() == 'date' or self.column_datatypes[i].strip().lower() == 'timestamp':
fldcommentsql += 'COMMENT ON COLUMN ' + tablename + '.' + self.column_names[i] + " IS '" + self.column_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]';\n"
sql = sql[:-2] + '\n);\n\n'
sql += 'COMMENT ON TABLE ' + tablename + " IS 'This Postgres table was defined by schemawiz for loading the csv file " + self.csvfilename + ", delimiter (" + self.delimiter + ")';\n"
sql += fldcommentsql
#print(sql)
return sql
def guess_mysql_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
sql = '/* DROP TABLE IF EXISTS ' + tablename + '; */\n'
sql += ' CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + str(self.mysql_datatypes[i]) + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if str(self.mysql_datatypes[i]).strip().lower() == 'date' or str(self.mysql_datatypes[i]).strip().lower() == 'timestamp':
sql += 'COMMENT "' + str(self.mysql_datatypes[i]).strip().lower() + ' format in csv [' + self.column_dateformats[i] + ']" '
sql += ' ,\n'
sql = sql[:-2] + '\n) \n'
sql += 'COMMENT="This MySQL table was defined by schemawiz for loading the csv file ' + self.csvfilename + ', delimiter (' + self.delimiter + ')"; \n'
return sql
if __name__ == '__main__':
main()
|
schemawizard-package
|
/schemawizard_package-2.5.2.tar.gz/schemawizard_package-2.5.2/src/schemawizard_package/schemawizard.py
|
schemawizard.py
|
import datetime
import os
import sys
from sqlitedave_package.sqlitedave import sqlite_db
from postgresdave_package.postgresdave import postgres_db
from mysqldave_package.mysqldave import mysql_db
from garbledave_package.garbledave import garbledave
def main():
obj = schemawiz()
#obj.loadcsvfile('test.csv')
#tbl = obj.createload_mysql_from_csv('test.csv','test3')
#obj.justload_sqlite_from_csv('servers.csv','servers',True)
#print(obj.guess_sqlite_ddl('servers'))
"""
csvfilename = 'a.csv'
ddl = obj.guess_postgres_ddl(csvfilename.replace('.','_'))
print(ddl)
print('/* Tablename used : ' + obj.lastcall_tablename + ' */ \n')
print('/* Postgres DDL - END ----- ----- ----- ----- */ \n')
print(obj.dbthings.postgres_db.does_table_exist('newtbl'))
# add any specific known date formats
#obj.dbthings.postgres_date_formats.append('Mon DD,YY')
if csvfilename != '':
obj.loadcsvfile(csvfilename)
print('/* MySQL DDL - BEGIN ----- schemawiz().guess_mysql_ddl() ----- */ \n')
print(obj.guess_mysql_ddl('sample_csv'))
print('/* MySQL DDL - END ----- ----- ----- ----- */ \n')
print('/* Postgres DDL - BEGIN ----- schemawiz().guess_postgres_ddl() ----- */ \n')
ddl = obj.guess_postgres_ddl(csvfilename.replace('.','_'))
print('/* Tablename used : ' + obj.lastcall_tablename + ' */ \n')
print(ddl)
print('/* Postgres DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery DDL - BEGIN ----- schemawiz().guess_BigQuery_ddl() ----- */ \n')
print(obj.guess_BigQuery_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery External DDL - BEGIN ----- schemawiz().guess_BigQueryExternal_ddl() ----- */ \n')
print(obj.guess_BigQueryExternal_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery External DDL - END ----- ----- ----- ----- */ \n')
print('/* BigQuery DDL - BEGIN ----- schemawiz().guess_BigQuery_ddl() ----- */ \n')
print(obj.guess_BigQuery_ddl('watchful-lotus-364517','dave'))
print('\n/* BigQuery DDL - END ----- ----- ----- ----- */ \n')
"""
class database_type:
Postgres = 1
MySQL = 2
sqlite = 3
BigQuery = 4
class dbthinger:
def __init__(self,date_to_check=''):
self.sqlite_db = sqlite_db()
self.mysql_db = mysql_db()
self.postgres_db = postgres_db()
self.postgres_date_formats = ['YYYY/MM/DD','YYYY-MM-DD','YYYY-Mon-DD','MM/DD/YYYY','Mon-DD-YYYY','Mon-DD-YY','Month DD,YY','Month DD,YYYY','DD-Mon-YYYY','YY-Mon-DD','YYYYMMDD','YYMMDD','YYYY-DD-MM','Mon dd/YY']
self.postgres_timestamp_formats = ['YYYY-MM-DD HH:MI:SS']
self.mysql_date_formats = ['%b %d/%y','%m/%d/%Y','%Y/%m/%d']
self.mysql_timestamp_formats = ['%Y/%m/%d %H:%i:%s','%d/%m/%Y %T']
self.date_to_check = date_to_check
if date_to_check != '':
self.chk_date(date_to_check)
def ask_for_database_details(self,thisDatabaseType):
configfilename = '.schemawiz_config' + str(thisDatabaseType)
if thisDatabaseType == database_type.Postgres:
DB_NAME = input('DB_NAME (postgres): ') or 'postgres'
elif thisDatabaseType == database_type.MySQL:
DB_NAME = input('DB_NAME : ') or 'atlas'
elif thisDatabaseType == database_type.sqlite:
DB_NAME = input('DB_NAME : (local_sqlite_db)') or 'local_sqlite_db'
DB_HOST = ''
if (thisDatabaseType == database_type.Postgres) or (thisDatabaseType == database_type.MySQL):
DB_HOST = input('DB_HOST (localhost): ') or 'localhost'
DB_PORT = ''
if thisDatabaseType == database_type.Postgres:
DB_PORT = input('DB_PORT (1532): ') or '1532'
elif thisDatabaseType == database_type.MySQL:
DB_PORT = input('DB_PORT (3306): ') or '3306'
if thisDatabaseType == database_type.Postgres:
DB_USERNAME = input('DB_USERNAME (postgres): ') or 'postgres'
elif thisDatabaseType == database_type.MySQL:
DB_USERNAME = input('DB_USERNAME: ') or 'dave'
DB_SCHEMA = ''
if thisDatabaseType == database_type.Postgres:
DB_SCHEMA = input('DB_SCHEMA (public): ') or 'public'
if thisDatabaseType == database_type.Postgres:
DB_USERPWD = input('DB_USERPWD: ') or '4165605869'
elif thisDatabaseType == database_type.MySQL:
DB_USERPWD = input('DB_USERPWD: ') or 'dave'
if thisDatabaseType == database_type.Postgres:
self.postgres_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME,DB_SCHEMA)
elif thisDatabaseType == database_type.MySQL:
self.mysql_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME)
elif thisDatabaseType == database_type.sqlite:
self.sqlite_db.useConnectionDetails(DB_NAME)
ans_save_connection_details = input('Save connection details? (y/n) :') or 'y'
if ans_save_connection_details.upper() == 'Y':
f = open(configfilename,'w')
if thisDatabaseType == database_type.Postgres:
f.write(garbledave().garbleit(DB_USERNAME + ' - ' + DB_USERPWD + ' - ' + DB_HOST + ' - ' + DB_PORT + ' - ' + DB_NAME + ' - ' + DB_SCHEMA))
elif thisDatabaseType == database_type.MySQL:
f.write(garbledave().garbleit(DB_USERNAME + ' - ' + DB_USERPWD + ' - ' + DB_HOST + ' - ' + DB_PORT + ' - ' + DB_NAME))
elif thisDatabaseType == database_type.sqlite:
f.write(garbledave().garbleit(DB_NAME + ' - '))
f.close()
def connect_local_db(self,thisDatabaseType):
configfilename = '.schemawiz_config' + str(thisDatabaseType)
if (((thisDatabaseType == database_type.sqlite) and (not self.sqlite_db.dbconn)) or (thisDatabaseType == database_type.Postgres) and (not self.postgres_db.dbconn)) or ((thisDatabaseType == database_type.MySQL) and (not self.mysql_db.dbconn)):
try:
f = open(configfilename,'r')
config_line = garbledave().ungarbleit(f.readline())
dbsettings = config_line.split(' - ')
f.close()
if thisDatabaseType == database_type.sqlite:
DB_NAME = dbsettings[0]
self.sqlite_db.useConnectionDetails(DB_NAME)
else:
DB_USERNAME = dbsettings[0]
DB_USERPWD = dbsettings[1]
DB_HOST = dbsettings[2]
DB_PORT = dbsettings[3]
DB_NAME = dbsettings[4]
if thisDatabaseType == database_type.Postgres:
DB_SCHEMA = dbsettings[5]
self.postgres_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME,DB_SCHEMA)
elif thisDatabaseType == database_type.MySQL:
self.mysql_db.useConnectionDetails(DB_USERNAME,DB_USERPWD,DB_HOST,DB_PORT,DB_NAME)
except Exception as e:
self.ask_for_database_details(thisDatabaseType)
def chk_date(self,possible_date_str):
print (" Checking date " + possible_date_str) #
self.date_type = self.match_date_type(possible_date_str)
if self.date_type == -1:
print('Not a date. date_type = ' + str(self.date_type))
else:
print('Is a date, and matchs date_type ' + str(self.date_type) + ', ' + self.postgres_date_formats[self.date_type])
return self.date_type
def chk_date_format_old(self,date_string,date_format):
try:
dateObject = datetime.datetime.strptime(date_string, date_format)
return True
except ValueError:
return False
def is_an_int(self,prm):
try:
if int(prm) == int(prm):
return True
else:
return False
except:
return False
def is_a_float(self,prm):
try:
if float(prm) == float(prm):
return True
else:
return False
except:
return False
def match_timestamp_type(self,timestamp_string,thisdatabase_type):
if thisdatabase_type == database_type.Postgres:
for i in range(0,len(self.postgres_timestamp_formats)):
fmt = self.postgres_timestamp_formats[i]
if self.chk_postrgres_timestamp_format(timestamp_string,fmt):
return i
else:
return -1
elif thisdatabase_type == database_type.MySQL:
for i in range(0,len(self.mysql_timestamp_formats)):
fmt = self.mysql_timestamp_formats[i]
if self.chk_mysql_timestamp_format(timestamp_string,fmt):
return i
else:
return -1
def chk_mysql_timestamp_format(self,timestamp_string,date_format):
retval = False
if len(timestamp_string) > 12:
sql = "SELECT CASE WHEN STR_TO_DATE('" + timestamp_string + "','" + date_format + "') is not null THEN 'Good' ELSE 'Bad' END as date_reasonablness"
try:
#print(sql)
#sys.exit(0)
if self.mysql_db.queryone(sql) == 'Good':
retval = True
except:
retval = False
return retval
def chk_postrgres_timestamp_format(self,timestamp_string,date_format):
retval = False
if len(timestamp_string) > 12:
sql = "SELECT to_char('" + timestamp_string + "'::timestamp,'" + date_format + "')"
try:
#print(sql)
return_fmt = self.postgres_db.queryone(sql)
retval = True
except Exception as e:
retval = False
return retval
# -1 means no matching date format
# > -1 means the date format matches self.postgres_date_formats[return_value]
def match_date_type(self,date_string,thisdatabase_type):
fmtdict = {}
dateformatscore = {}
bestchoice = -1
bestfmt = -1
besthits = -1
# might be a date
if (((self.is_an_int(date_string) and len(date_string) == 8)) or ((not self.is_an_int(date_string)) and (len(date_string) > 5) and (len(date_string) < 12))):
# loadup with default date formats
if thisdatabase_type == database_type.Postgres:
for i in range(0,len(self.postgres_date_formats)):
dateformatscore[self.postgres_date_formats[i]] = 0
fmtdict[self.postgres_date_formats[i]] = i
elif thisdatabase_type == database_type.MySQL:
for i in range(0,len(self.mysql_date_formats)):
dateformatscore[self.mysql_date_formats[i]] = 0
fmtdict[self.mysql_date_formats[i]] = i
for i in range(0,len(dateformatscore)):
retval = False
if thisdatabase_type == database_type.Postgres:
retval = self.chk_postgres_date_format(date_string,self.postgres_date_formats[i])
if retval:
dateformatscore[self.postgres_date_formats[i]] += 1
elif thisdatabase_type == database_type.MySQL:
retval = self.chk_mysql_date_format(date_string,self.mysql_date_formats[i])
if retval:
dateformatscore[self.mysql_date_formats[i]] += 1
for fmt in dateformatscore:
if dateformatscore[fmt] > bestchoice:
bestchoice = dateformatscore[fmt]
bestfmt = fmt
if bestchoice > 0:
return fmtdict[bestfmt]
else:
return -1
def match_float_type(self,floatvalue):
return self.is_a_float(floatvalue)
def match_integer_type(self,intvalue):
return self.is_an_int(intvalue)
def chk_mysql_date_format(self,date_string,date_format):
sql = """
SELECT CASE WHEN STR_TO_DATE('""" + date_string + """','""" + date_format + """') is null THEN 'bad'
ELSE 'Good'
END as date_reasonablness
"""
try:
#print(sql)
#sys.exit(0)
return_fmt = self.mysql_db.queryone(sql)
if return_fmt == 'Good':
return True
else:
return False
except Exception as e:
return False
def chk_postgres_date_format(self,date_string,date_format):
sql = """
SELECT CASE WHEN abs( to_date('""" + date_string + """','""" + date_format + """') - current_date) > 36500 THEN 'bad'
ELSE 'Good'
END as date_reasonablness
"""
try:
return_fmt = self.postgres_db.queryone(sql)
if return_fmt == 'Good':
return True
else:
return False
except Exception as e:
return False
class schemawiz:
def __init__(self,csvfilename=''):
self.version=2.0
self.dbthings = dbthinger()
self.force_delimiter = ''
self.lastcall_tablename = ''
self.delimiter = ''
self.delimiter_replace = '^~^'
self.logging_on = False
self.SomeFileContents = []
self.column_names = []
self.column_datatypes = []
self.BigQuery_datatypes = []
self.mysql_datatypes = []
self.sqlite_datatypes = []
self.column_sample = []
self.column_dateformats = []
self.analyzed = False
self.IsaDateField = False
self.DateField = ''
self.clusterField1 = ''
self.clusterField2 = ''
self.clusterField3 = ''
self.csvfilename = ''
if csvfilename != '':
self.loadcsvfile(csvfilename)
def newpostgresconnection(self):
os.remove('.schemawiz_config' + str(database_type.Postgres))
def newmysqlconnection(self):
os.remove('.schemawiz_config' + str(database_type.MySQL))
def newsqliteconnection(self):
os.remove('.schemawiz_config' + str(database_type.sqlite))
def newconnections(self):
self.newpostgresconnection()
self.newmysqlconnection()
self.newsqliteconnection()
def justload_sqlite_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
if self.dbthings.sqlite_db.does_table_exist(tablename):
self.dbthings.sqlite_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.sqlite_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_postgres_from_csv(csvfilename)')
return return_value
def createload_sqlite_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
print(csvfilename)
ddl = self.guess_sqlite_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.sqlite_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.sqlite_db.execute(ddl)
self.dbthings.sqlite_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.sqlite_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def justload_postgres_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
if self.dbthings.postgres_db.does_table_exist(tablename):
self.dbthings.postgres_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.postgres_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_postgres_from_csv(csvfilename)')
return return_value
def createload_postgres_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
ddl = self.guess_postgres_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.postgres_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.postgres_db.execute(ddl)
self.dbthings.postgres_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.postgres_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def justload_mysql_from_csv(self,csvfilename,tablename,withtruncate=False):
return_value = ''
self.loadcsvfile(csvfilename)
delimiter = self.lastcall_delimiter()
self.dbthings.mysql_db.connect()
if self.dbthings.mysql_db.does_table_exist(tablename):
self.dbthings.mysql_db.load_csv_to_table(csvfilename,tablename,withtruncate,delimiter)
rowcount = self.dbthings.mysql_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' does not exist. Cannot load. \n alternatively try: createload_mysql_from_csv(csvfilename)')
return return_value
def createload_mysql_from_csv(self,csvfilename,sztablename='',ddlfilename=''):
return_value = ''
self.loadcsvfile(csvfilename)
ddl = self.guess_mysql_ddl(sztablename)
delimiter = self.lastcall_delimiter()
if sztablename == '':
tablename = self.lastcall_tablename
else:
tablename = sztablename
if not self.dbthings.mysql_db.does_table_exist(tablename):
if ddlfilename != '':
f = open(ddlfilename,'w')
f.write(ddl)
f.close()
print(ddl)
self.dbthings.mysql_db.execute(ddl)
self.dbthings.mysql_db.load_csv_to_table(csvfilename,tablename,True,delimiter)
rowcount = self.dbthings.mysql_db.queryone('SELECT COUNT(*) FROM ' + tablename)
print('Created/Loaded table ' + tablename + ' with ' + str(rowcount) + ' rows.')
return_value = tablename
else:
print('Table ' + tablename + ' already exists. Stopping Load.')
return return_value
def add_date_format(self,dt_fmt):
self.dbthings.mysql_date_formats.append(dt_fmt)
self.dbthings.postgres_date_formats.append(dt_fmt)
def add_timestamp_format(self,tmsp_fmt):
self.dbthings.mysql_timestamp_formats.append(tmsp_fmt)
self.dbthings.postgres_timestamp_formats.append(tmsp_fmt)
def lastcall_delimiter(self):
return self.delimiter
def utf8len(self,s):
return len(s.encode('utf-8'))
def logger(self,logline):
if self.logging_on:
print(logline)
def loadcsvfile(self,csvfilename):
if csvfilename != '':
try:
with open(csvfilename) as f:
for csvline in f:
self.csvfilename = csvfilename
self.delimiter = self.GuessDelimiter(csvline)
break
except Exception as e:
print('Cannot read file: ' + csvfilename)
sys.exit(0)
else:
print('schemawiz.loadcsvfile(csvfilename) requires a valid csv file.')
sys.exit(0)
def analyze_csvfile(self,thisdatabase_type):
self.analyzed = False
if self.csvfilename == '':
print('/* No csvfilename was provided to schemawiz.loadcsvfile(). Will use empty template */\n')
self.SomeFileContents.append('field1,field2,field3,field4,field5')
self.SomeFileContents.append('1999/02/18,0,0.001,textD,textE')
self.get_column_names()
self.get_column_types(thisdatabase_type)
self.analyzed = True
else:
self.logger('Checking file size for ' + self.csvfilename + '\n')
file_stats = os.stat(self.csvfilename)
linecount = 0
total_linesize = 0
with open(self.csvfilename) as f:
for line in f:
linecount += 1
if linecount != 1:
total_linesize += self.utf8len(line)
if linecount == 11:
self.datalinesize = total_linesize/10
self.SomeFileContents.append(line)
if (linecount>100):
break
#self.logger('file has ' + str(len(self.SomeFileContents)) + ' lines')
#self.logger('line size is ' + str(self.datalinesize) + ' ytes')
#self.logger('file size is ' + str(file_stats.st_size) + ' bytes')
self.get_column_names()
self.get_column_types(thisdatabase_type)
self.analyzed = True
def get_just_filename(self):
justfilename=''
if self.csvfilename.find('\\') > -1: # have a path and dirs
fileparts = self.csvfilename.split('\\')
justfilename = fileparts[len(fileparts)-1]
else:
if self.csvfilename != '':
justfilename = self.csvfilename
return justfilename
def gettablename(self):
now = (datetime.datetime.now())
rando_tablename= 'tblcsv_' + str(now.year) + ('0' + str(now.month))[-2:] + str(now.day) + str(now.hour) + str(now.minute)
return rando_tablename
def count_chars(self,data,exceptchars=''):
chars_in_hdr = {}
for i in range(0,len(data)):
if data[i] != '\n' and exceptchars.find(data[i]) == -1:
if data[i] in chars_in_hdr:
chars_in_hdr[data[i]] += 1
else:
chars_in_hdr[data[i]] = 1
return chars_in_hdr
def count_alpha(self,alphadict):
count = 0
for ch in alphadict:
if 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(ch) > -1:
count += alphadict[ch]
return count
def count_nbr(self,alphadict):
count = 0
for ch in alphadict:
if '0123456789'.find(ch) > -1:
count += alphadict[ch]
return count
def count_decimals(self,alphadict):
count = 0
for ch in alphadict:
if '.'.find(ch) > -1:
count += alphadict[ch]
return count
def get_datatype(self,datavalue,thisdatabase_type):
chardict = {}
data = ''
if datavalue[0:1] == '"' and datavalue[-1:] == '"':
#self.logger('enclosed in quotes ""')
data = datavalue[1:-1]
#self.logger('data: ' + data)
else:
data = datavalue.strip()
chardict = self.count_chars(data)
alphacount = self.count_alpha(chardict)
nbrcount = self.count_nbr(chardict)
deccount = self.count_decimals(chardict)
lookslike = ''
dtformat = ''
timestamp_nbr = -1
date_format_nbr = -1
if thisdatabase_type != database_type.sqlite:
timestamp_nbr = self.dbthings.match_timestamp_type(data,thisdatabase_type)
date_format_nbr = self.dbthings.match_date_type(data,thisdatabase_type)
if timestamp_nbr != -1:
lookslike = 'timestamp'
if thisdatabase_type == database_type.Postgres:
dtformat = self.dbthings.postgres_timestamp_formats[timestamp_nbr]
elif thisdatabase_type == database_type.MySQL:
dtformat = self.dbthings.mysql_timestamp_formats[timestamp_nbr]
elif date_format_nbr != -1:
lookslike = 'date'
if thisdatabase_type == database_type.Postgres:
dtformat = self.dbthings.postgres_date_formats[date_format_nbr]
elif thisdatabase_type == database_type.MySQL:
dtformat = self.dbthings.mysql_date_formats[date_format_nbr]
elif alphacount == 0 and deccount == 1:
# 123.123232222
if self.dbthings.match_float_type(data):
lookslike = 'numeric'
else:
lookslike = 'text'
elif self.dbthings.match_integer_type(data) :
lookslike = 'bigint'
else:
lookslike = 'text'
return lookslike,dtformat
def handledblquotes(self,rowwithquotes):
newstr = ''
quotecount = 0
cvtmode = False
for i in range (0,len(rowwithquotes)-1):
if rowwithquotes[i] == '"':
quotecount += 1
if (quotecount % 2) == 1:
cvtmode = True
else:
cvtmode = False
if cvtmode and rowwithquotes[i] == self.delimiter:
newstr += self.delimiter_replace
elif rowwithquotes[i] != '"':
newstr += rowwithquotes[i]
return newstr
def get_column_types(self,thisdatabase_type):
found_datatypes = {}
found_datavalues = {}
found_datefomat = {}
for i in range(1,len(self.SomeFileContents)):
cvted_str = self.handledblquotes(self.SomeFileContents[i])
dataline = cvted_str.strip().split(self.delimiter)
for j in range(0,len(dataline)):
fld = dataline[j].replace(self.delimiter_replace,self.delimiter)
if self.column_names[j].lower().endswith('_text'):
thisdatatype = 'text'
dtformat = ''
else:
thisdatatype,dtformat = self.get_datatype(fld,thisdatabase_type)
#print(thisdatatype)
if self.column_names[j] not in found_datatypes:
found_datatypes[self.column_names[j]] = thisdatatype
found_datavalues[self.column_names[j]] = fld
found_datefomat[self.column_names[j]] = dtformat
else:
if found_datatypes[self.column_names[j]] == 'date' and thisdatatype =='date' and found_datefomat[self.column_names[j]] != dtformat:
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] == 'timestamp' and thisdatatype =='timestamp' and found_datefomat[self.column_names[j]] != dtformat:
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] != thisdatatype:
if found_datatypes[self.column_names[j]] == 'text' or thisdatatype == 'text':
found_datatypes[self.column_names[j]] == 'text'
elif found_datatypes[self.column_names[j]] == 'numeric' or thisdatatype == 'numeric':
found_datatypes[self.column_names[j]] == 'numeric'
elif found_datatypes[self.column_names[j]] == 'date' or thisdatatype == 'date':
found_datatypes[self.column_names[j]] == 'text'
for k in range(0,len(self.column_names)):
if self.column_names[k] not in found_datavalues:
found_datavalues[self.column_names[k]] = ''
found_datefomat[self.column_names[k]] = ''
found_datatypes[self.column_names[k]] = 'text'
self.column_sample.append(found_datavalues[self.column_names[k]].replace('"',''))
self.column_dateformats.append(found_datefomat[self.column_names[k]])
self.column_datatypes.append(found_datatypes[self.column_names[k]])
self.mysql_datatypes.append(self.translate_dt(database_type.MySQL,found_datatypes[self.column_names[k]]))
self.BigQuery_datatypes.append(self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]))
self.sqlite_datatypes.append(self.translate_dt(database_type.sqlite,found_datatypes[self.column_names[k]]))
if not self.IsaDateField and self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]) == 'DATE':
self.IsaDateField = True
self.DateField = self.column_names[k]
elif self.translate_dt(database_type.BigQuery,found_datatypes[self.column_names[k]]) != 'FLOAT64':
if self.clusterField1 == '':
self.clusterField1 = self.column_names[k]
elif self.clusterField2 == '':
self.clusterField2 = self.column_names[k]
elif self.clusterField3 == '':
self.clusterField3 = self.column_names[k]
for m in range(0,len(self.column_datatypes)):
self.logger('column ' + str(self.column_names[m]) + ' has data type ' + str(self.column_datatypes[m]))
def translate_dt(self,targettype,postgres_datatype):
if targettype == database_type.BigQuery:
if postgres_datatype.lower().strip() == 'text':
return 'STRING'
elif postgres_datatype.lower().strip() == 'date':
return 'DATE'
elif postgres_datatype.lower().strip() == 'timestamp':
return 'TIMESTAMP'
elif postgres_datatype.lower().strip() == 'integer' or postgres_datatype.lower().strip() == 'bigint':
return 'INT64'
elif postgres_datatype.lower().strip() == 'numeric':
return 'FLOAT64'
else:
return 'UNKNOWN'
elif targettype == database_type.MySQL:
if postgres_datatype.lower().strip() == 'numeric':
return 'float'
else:
return postgres_datatype
elif targettype == database_type.sqlite:
if postgres_datatype.lower().strip() == 'integer' or postgres_datatype.lower().strip() == 'bigint':
return 'integer'
elif postgres_datatype.lower().strip() == 'numeric':
return 'real'
else:
return 'text'
else:
return postgres_datatype
def clean_text(self,ptext): # remove optional double quotes
text = ptext.strip()
if (text[:1] == '"' and text[-1:] == '"'):
return text[1:-1]
else:
return text
def clean_column_name(self,col_name):
col = col_name.replace(' ','_')
new_column_name = ''
for i in range(0,len(col)):
if 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'.find(col[i]) > -1:
new_column_name += col[i]
return new_column_name
def get_column_names(self):
self.delimiter = self.GuessDelimiter(self.SomeFileContents[0])
self.logger('file delimiter is ' + self.delimiter)
self.column_names = self.SomeFileContents[0].strip().split(self.delimiter)
self.logger('Column Names are ' + str(self.column_names))
for i in range(0,len(self.column_names)):
self.column_names[i] = self.clean_column_name(self.column_names[i])
def GuessDelimiter(self,first_row):
if self.force_delimiter != '':
delimiter_guess = self.force_delimiter
else:
if first_row.find('\t') > -1:
delimiter_guess = '\t'
elif first_row.find(',') > -1:
delimiter_guess = ','
else:
delimiter_guess = '~'
return delimiter_guess
def guess_BigQueryExternal_ddl(self,useproject='',usedataset='',usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if useproject == '':
project = 'schemawiz-123'
else:
project = useproject
if usedataset == '':
dataset = 'sampledataset'
else:
dataset = usedataset
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
project = project.replace(' ','').lower()
dataset = dataset.replace(' ','').lower()
tablename = tablename.replace(' ','').lower()
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL) # database_type.BigQuery
sql = 'CREATE EXTERNAL TABLE IF NOT EXISTS `' + project + '.' + dataset + '.' + tablename + '` (\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.BigQuery_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if self.BigQuery_datatypes[i].strip().lower() == 'date' or self.BigQuery_datatypes[i].strip().lower() == 'timestamp':
sql += "OPTIONS (description='" + self.BigQuery_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]')"
sql += ',\n'
sql = sql[:-2] + '\n)'
sql += " OPTIONS (\n format = 'CSV',\n Field_delimiter = '" + self.delimiter + "',\n uris = ['gs://bucket/"
sql += self.get_just_filename() + "*'],\n skip_leading_rows = 1,\n "
sql += "description='" + "This externally stored, BigQuery table was defined by schemawiz for creating a BQ table to use csv files as source.'\n);"
return sql
def guess_BigQuery_ddl(self,useproject='',usedataset='',usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if useproject == '':
project = 'schemawiz-123'
else:
project = useproject
if usedataset == '':
dataset = 'sampledataset'
else:
dataset = usedataset
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
project = project.replace(' ','').lower()
dataset = dataset.replace(' ','').lower()
tablename = tablename.replace(' ','').lower()
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL) # database_type.BigQuery
sql = 'CREATE TABLE IF NOT EXISTS `' + project + '.' + dataset + '.' + tablename + '` (\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.BigQuery_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if self.BigQuery_datatypes[i].strip().lower() == 'date' or self.BigQuery_datatypes[i].strip().lower() == 'timestamp':
sql += "OPTIONS (description='" + self.BigQuery_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]')"
sql += ',\n'
sql = sql[:-2] + '\n)\n'
if self.IsaDateField:
sql += 'PARTITION BY ' + self.DateField + '\n'
if self.clusterField1 != '':
sql += 'CLUSTER BY \n ' + self.clusterField1 + ',\n'
if self.clusterField2 != '':
sql += ' ' + self.clusterField2 + ',\n'
if self.clusterField3 != '':
sql += ' ' + self.clusterField3 + ',\n'
sql = sql[:-2]
sql += "\nOPTIONS (\n require_partition_filter = False,\n "
sql += "description = 'This BigQuery table was defined by schemawiz for loading the csv file " + self.get_just_filename() + ", delimiter (" + self.delimiter + ")' \n);"
return sql
def guess_sqlite_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.sqlite)
if not self.analyzed:
self.analyze_csvfile(database_type.sqlite)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
fldcommentsql = ''
sql = '/* DROP TABLE IF EXISTS ' + tablename + '; */\n'
sql += 'CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.sqlite_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ ,\n'
sql = sql[:-2] + '\n);\n\n'
return sql
def guess_postgres_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.Postgres)
if not self.analyzed:
self.analyze_csvfile(database_type.Postgres)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
fldcommentsql = ''
sql = 'DROP TABLE IF EXISTS ' + tablename + ';\n'
sql += 'CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + self.column_datatypes[i] + ' \t\t/* eg. ' + self.column_sample[i] + ' */ ,\n'
if self.column_datatypes[i].strip().lower() == 'date' or self.column_datatypes[i].strip().lower() == 'timestamp':
fldcommentsql += 'COMMENT ON COLUMN ' + tablename + '.' + self.column_names[i] + " IS '" + self.column_datatypes[i].strip().lower() + " format in csv [" + self.column_dateformats[i] + "]';\n"
sql = sql[:-2] + '\n);\n\n'
sql += 'COMMENT ON TABLE ' + tablename + " IS 'This Postgres table was defined by schemawiz for loading the csv file " + self.csvfilename + ", delimiter (" + self.delimiter + ")';\n"
sql += fldcommentsql
#print(sql)
return sql
def guess_mysql_ddl(self,usetablename=''):
self.dbthings.connect_local_db(database_type.MySQL)
if not self.analyzed:
self.analyze_csvfile(database_type.MySQL)
if usetablename == '':
tablename = self.gettablename()
else:
tablename = usetablename
self.lastcall_tablename = tablename
sql = '/* DROP TABLE IF EXISTS ' + tablename + '; */\n'
sql += ' CREATE TABLE IF NOT EXISTS ' + tablename + '(\n'
for i in range(0,len(self.column_names)):
sql += '\t' + self.column_names[i] + ' ' + str(self.mysql_datatypes[i]) + ' \t\t/* eg. ' + self.column_sample[i] + ' */ '
if str(self.mysql_datatypes[i]).strip().lower() == 'date' or str(self.mysql_datatypes[i]).strip().lower() == 'timestamp':
sql += 'COMMENT "' + str(self.mysql_datatypes[i]).strip().lower() + ' format in csv [' + self.column_dateformats[i] + ']" '
sql += ' ,\n'
sql = sql[:-2] + '\n) \n'
sql += 'COMMENT="This MySQL table was defined by schemawiz for loading the csv file ' + self.csvfilename + ', delimiter (' + self.delimiter + ')"; \n'
return sql
if __name__ == '__main__':
main()
| 0.037688 | 0.052936 |
Schemazer (Flask-Schemazer)
===========================
*Created by Dmitriy Danshin:*
https://gitlab.tingerlink.pro/tingerlink/schemazer
Introduction
------------
Project which allows to describe the schema API. To set input parameters, binding, ranges, pattern of verification values, and to tie it to the route of the flask view.
Using Schemazer check decorator::
@current_app.schemazer.route(TestSchema.headers.withRequiredParameter)
Installation
------------
To install Schemazer, simply::
pip install schemazer
Examples
--------
Create custom schema API or use ``commons.base.SchemazerSchema``::
class Schema(SchemazerSchema):
auth = AuthGroup
Create custom methods groups::
class AuthGroup(SchemazerGroup):
__group_name__ = 'auth'
signInEmail = SchemazerMethod(
group_name=__group_name__,
name='signInEmail',
description='Sign in by email.',
parameters=[
AuthParameters.Email(),
AuthParameters.Password()
],
response=SchemazerResponse(schema=TokenField()),
errors=[AuthErrors.UserNotFound,
AuthErrors.AuthTokenExpired],
limits=[AllLimit()]
)
Parameters::
class Email(SchemazerParameter):
name = 'email'
description = 'Email'
type = str
required = True
example = '[email protected]'
validator = Validator(EmailFormat)
SchemazerResponse schema::
class AuthTokenResponse(SchemazerResponse):
description = 'Token'
schema = SchemazerResponseObjectField(
name='auth_token',
is_list=True,
fields=[TokenField(), ExpiresInField()]
)
SchemazerResponse field schema::
class TokenField(StringField):
name = 'token'
description = 'Unique auth token.'
example = '1q2w3e4r5t6y7u8i9o0p1q2w3e4r5t6y7u8i9o0p'
Init schema::
Schemazer(app, Schema())
Documentation
-------------
For add documentation by api add::
from schemazer.docs_view import doc_bp
app = Flask(__name__)
app.register_blueprint(doc_bp)
SchemazerResponse examples
-----------------
Error response schema::
{
"error":
{
"code": "ErrorClass.ErrorName",
"msg": "Error in param `param1`",
"failure_param": "param1",
"params": {
"param1": "1234",
"param2": "****"
}
}
}
Schemazer configuration
------------------------
Add config for you flask app after Schemazer init::
app.config.update({'SCHEMAZER_...': '...'})
Schemazer config params start with ``SCHEMAZER_`` prefix::
SCHEMAZER_VERSION = 1.0
Config parameters
===================
Override in your flask app::
SCHEMAZER_ERROR_HTTP_CODE = 200
SCHEMAZER_HOST = localhost
SCHEMAZER_HTTP_SCHEMA = http
SCHEMAZER_VERSION = schemazer
DEFAULT ERRORS
==============
Schemazer have default errors objects.
Import objects from::
from schemazer.commons.errors import *
Default errors objects::
RequestErrors
BadRequest
NotFound
Undefined
|
schemazer
|
/schemazer-2.0.7.tar.gz/schemazer-2.0.7/README.rst
|
README.rst
|
Schemazer (Flask-Schemazer)
===========================
*Created by Dmitriy Danshin:*
https://gitlab.tingerlink.pro/tingerlink/schemazer
Introduction
------------
Project which allows to describe the schema API. To set input parameters, binding, ranges, pattern of verification values, and to tie it to the route of the flask view.
Using Schemazer check decorator::
@current_app.schemazer.route(TestSchema.headers.withRequiredParameter)
Installation
------------
To install Schemazer, simply::
pip install schemazer
Examples
--------
Create custom schema API or use ``commons.base.SchemazerSchema``::
class Schema(SchemazerSchema):
auth = AuthGroup
Create custom methods groups::
class AuthGroup(SchemazerGroup):
__group_name__ = 'auth'
signInEmail = SchemazerMethod(
group_name=__group_name__,
name='signInEmail',
description='Sign in by email.',
parameters=[
AuthParameters.Email(),
AuthParameters.Password()
],
response=SchemazerResponse(schema=TokenField()),
errors=[AuthErrors.UserNotFound,
AuthErrors.AuthTokenExpired],
limits=[AllLimit()]
)
Parameters::
class Email(SchemazerParameter):
name = 'email'
description = 'Email'
type = str
required = True
example = '[email protected]'
validator = Validator(EmailFormat)
SchemazerResponse schema::
class AuthTokenResponse(SchemazerResponse):
description = 'Token'
schema = SchemazerResponseObjectField(
name='auth_token',
is_list=True,
fields=[TokenField(), ExpiresInField()]
)
SchemazerResponse field schema::
class TokenField(StringField):
name = 'token'
description = 'Unique auth token.'
example = '1q2w3e4r5t6y7u8i9o0p1q2w3e4r5t6y7u8i9o0p'
Init schema::
Schemazer(app, Schema())
Documentation
-------------
For add documentation by api add::
from schemazer.docs_view import doc_bp
app = Flask(__name__)
app.register_blueprint(doc_bp)
SchemazerResponse examples
-----------------
Error response schema::
{
"error":
{
"code": "ErrorClass.ErrorName",
"msg": "Error in param `param1`",
"failure_param": "param1",
"params": {
"param1": "1234",
"param2": "****"
}
}
}
Schemazer configuration
------------------------
Add config for you flask app after Schemazer init::
app.config.update({'SCHEMAZER_...': '...'})
Schemazer config params start with ``SCHEMAZER_`` prefix::
SCHEMAZER_VERSION = 1.0
Config parameters
===================
Override in your flask app::
SCHEMAZER_ERROR_HTTP_CODE = 200
SCHEMAZER_HOST = localhost
SCHEMAZER_HTTP_SCHEMA = http
SCHEMAZER_VERSION = schemazer
DEFAULT ERRORS
==============
Schemazer have default errors objects.
Import objects from::
from schemazer.commons.errors import *
Default errors objects::
RequestErrors
BadRequest
NotFound
Undefined
| 0.831246 | 0.305218 |
# [Schemdraw](https://bitbucket.org/cdelker/schemdraw/src/master/) Extension for [Python-Markdown](https://python-markdown.github.io/)
*a simpler way to document circuits in markdown*
**Inspiration:** This project is inspired by the wonderful project:
[`plantuml-markdown`](https://github.com/mikitex70/plantuml-markdown). So,
shoutout to the folks who've toiled on that project to make it great!
## Usage
This package allows you to configure a schematic drawing, directly in markdown
using a code-fenced sample as follows:
```
::schemdraw:: alt="My super diagram"
+= elm.Resistor().right().label('1Ω')
+= elm.Capacitor().down().label('10μF')
+= elm.Line().left()
+= elm.SourceSin().up().label('10V')
::end-schemdraw::
```
## :warning: Security Note
This package makes use of Python's `exec` functionality, which is inherently
somewhat insecure, as it allows for arbitrary code execution. Only carfully
curated drawings logic should be used.
## Installation
### Installing from [PyPI](https://pypi.org/project/schemdraw-markdown/)
Yeah! It's "official," now! You can just *pip-install* the package with:
```shell
$ pip3 install schemdraw-markdown
```
#### Installing from Source
1. Clone Repository
2. From within local Repository folder, issue:
```shell
pip install .
```
|
schemdraw-markdown
|
/schemdraw-markdown-0.0.3.tar.gz/schemdraw-markdown-0.0.3/README.md
|
README.md
|
::schemdraw:: alt="My super diagram"
+= elm.Resistor().right().label('1Ω')
+= elm.Capacitor().down().label('10μF')
+= elm.Line().left()
+= elm.SourceSin().up().label('10V')
::end-schemdraw::
$ pip3 install schemdraw-markdown
pip install .
| 0.339609 | 0.826782 |
# schemdraw
Schemdraw is a python package for producing high-quality electrical circuit schematic diagrams. Typical usage:
```python
import schemdraw
import schemdraw.elements as elm
with schemdraw.Drawing(file='schematic.svg') as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
```
Included are symbols for basic electrical components (resistors, capacitors, diodes, transistors, etc.), opamps and signal processing elements. Additionally, Schemdraw can produce digital timing diagras, state machine diagrams, and flowcharts.
Documentation is available at [readthedocs](https://schemdraw.readthedocs.io)
The most current version can be found in the [source code git repository](https://github.com/cdelker/schemdraw).
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/README.md
|
README.md
|
import schemdraw
import schemdraw.elements as elm
with schemdraw.Drawing(file='schematic.svg') as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
| 0.175856 | 0.673974 |
Development
===========
Report bugs and feature requests on the `Issue Tracker <https://github.com/cdelker/schemdraw/issues>`_.
Code contributions are welcome, especially with new circuit elements (and we'd be happy to expand beyond electrical elements too). To contribute code, please fork the `source code repository <https://github.com/cdelker/schemdraw/>`_ and issue a pull request. Make sure to include any new elements somewhere in the test Jupyter notebooks and in the documentation.
- `Source Code <https://github.com/cdelker/schemdraw>`_
|
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/contributing.rst
|
contributing.rst
|
Development
===========
Report bugs and feature requests on the `Issue Tracker <https://github.com/cdelker/schemdraw/issues>`_.
Code contributions are welcome, especially with new circuit elements (and we'd be happy to expand beyond electrical elements too). To contribute code, please fork the `source code repository <https://github.com/cdelker/schemdraw/>`_ and issue a pull request. Make sure to include any new elements somewhere in the test Jupyter notebooks and in the documentation.
- `Source Code <https://github.com/cdelker/schemdraw>`_
|
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.694406 | 0.571229 |
Schemdraw documentation
=======================
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Schemdraw is a Python package for producing high-quality electrical circuit schematic diagrams.
Circuit elements are added, one at a time, similar to how you might draw them by hand, using Python methods.
For example,
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
creates a new schemdraw drawing with a resistor going to the right with a label of "1Ω".
The next element added to the drawing will start at the endpoint of the resistor.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
d += elm.Capacitor().down().label('10μF')
d += elm.Line().left()
d += elm.SourceSin().up().label('10V')
|
.. toctree::
:maxdepth: 1
:caption: Contents:
usage/start
usage/index
elements/elements
gallery/index
usage/customizing
classes/index
changes
contributing
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/index.rst
|
index.rst
|
Schemdraw documentation
=======================
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Schemdraw is a Python package for producing high-quality electrical circuit schematic diagrams.
Circuit elements are added, one at a time, similar to how you might draw them by hand, using Python methods.
For example,
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
creates a new schemdraw drawing with a resistor going to the right with a label of "1Ω".
The next element added to the drawing will start at the endpoint of the resistor.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
d += elm.Capacitor().down().label('10μF')
d += elm.Line().left()
d += elm.SourceSin().up().label('10V')
|
.. toctree::
:maxdepth: 1
:caption: Contents:
usage/start
usage/index
elements/elements
gallery/index
usage/customizing
classes/index
changes
contributing
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.742515 | 0.41561 |
Signal Processing
=================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import dsp
Signal processing elements can be drawn by importing the :py:mod:`schemdraw.dsp.dsp` module:
.. code-block:: python
from schemdraw import dsp
Because each element may have multiple connections in and out, these elements
are not 2-terminal elements that extend "leads", so they must be manually connected with
`Line` or `Arrow` elements. The square elements define anchors 'N', 'S', 'E', and 'W' for
the four directions. Circle-based elements also includ 'NE', 'NW', 'SE', and 'SW'
anchors.
Directional elements, such as `Amp`, `Adc`, and `Dac` define anchors `input` and `out`.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().right().at((x,y)).label(name, loc='rgt', ofst=.2, halign='left', valign='center')
return d
elms = [dsp.Square, dsp.Circle, dsp.Sum, dsp.SumSigma, dsp.Mixer, dsp.Speaker,
dsp.Amp, dsp.OscillatorBox, dsp.Oscillator, dsp.Filter,
partial(dsp.Filter, response='lp'), partial(dsp.Filter, response='bp'),
partial(dsp.Filter, response='hp'), dsp.Adc, dsp.Dac, dsp.Demod,
dsp.Circulator, dsp.Isolator, dsp.VGA
]
drawElements(elms, dx=6)
Labels are placed in the center of the element. The generic `Square` and `Circle` elements can be used with a label to define other operations. For example, an integrator
may be created using:
.. jupyter-execute::
dsp.Square().label('$\int$')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/dsp.rst
|
dsp.rst
|
Signal Processing
=================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import dsp
Signal processing elements can be drawn by importing the :py:mod:`schemdraw.dsp.dsp` module:
.. code-block:: python
from schemdraw import dsp
Because each element may have multiple connections in and out, these elements
are not 2-terminal elements that extend "leads", so they must be manually connected with
`Line` or `Arrow` elements. The square elements define anchors 'N', 'S', 'E', and 'W' for
the four directions. Circle-based elements also includ 'NE', 'NW', 'SE', and 'SW'
anchors.
Directional elements, such as `Amp`, `Adc`, and `Dac` define anchors `input` and `out`.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().right().at((x,y)).label(name, loc='rgt', ofst=.2, halign='left', valign='center')
return d
elms = [dsp.Square, dsp.Circle, dsp.Sum, dsp.SumSigma, dsp.Mixer, dsp.Speaker,
dsp.Amp, dsp.OscillatorBox, dsp.Oscillator, dsp.Filter,
partial(dsp.Filter, response='lp'), partial(dsp.Filter, response='bp'),
partial(dsp.Filter, response='hp'), dsp.Adc, dsp.Dac, dsp.Demod,
dsp.Circulator, dsp.Isolator, dsp.VGA
]
drawElements(elms, dx=6)
Labels are placed in the center of the element. The generic `Square` and `Circle` elements can be used with a label to define other operations. For example, an integrator
may be created using:
.. jupyter-execute::
dsp.Square().label('$\int$')
| 0.826327 | 0.500061 |
Digital Logic
=============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Logic gates can be drawn by importing the :py:mod:`schemdraw.logic.logic` module:
.. code-block:: python
from schemdraw import logic
Logic gates are shown below. Gates define anchors for `out` and `in1`, `in2`, etc.
`Buf`, `Not`, and `NotNot`, and their Schmitt-trigger counterparts, are two-terminal elements that extend leads.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
d += getattr(logic, e)().right().at((x,y)).label(e, loc='right', ofst=.2, halign='left', valign='center')
return d
elms = ['And', 'Nand', 'Or', 'Nor', 'Xor', 'Xnor',
'Buf', 'Not', 'NotNot', 'Tgate', 'Tristate',
'Schmitt', 'SchmittNot', 'SchmittAnd', 'SchmittNand']
drawElements(elms, dx=6)
Gates with more than 2 inputs can be created using the `inputs` parameter. With more than 3 inputs, the back of the gate will extend up and down.
.. jupyter-execute::
logic.Nand(inputs=3)
.. jupyter-execute::
logic.Nor(inputs=4)
Finally, any input can be pre-inverted (active low) using the `inputnots` keyword with a list of input numbers, starting at 1 to match the anchor names, on which to add an invert bubble.
.. jupyter-execute::
logic.Nand(inputs=3, inputnots=[1])
Logic Parser
------------
Logic trees can also be created from a string logic expression such as "(a and b) or c" using using :py:func:`schemdraw.parsing.logic_parser.logicparse`.
The logic parser requires the `pyparsing <https://pyparsing-docs.readthedocs.io/en/latest/>`_ module.
Examples:
.. jupyter-execute::
from schemdraw.parsing import logicparse
logicparse('not ((w and x) or (y and z))', outlabel='$\overline{Q}$')
.. jupyter-execute::
logicparse('((a xor b) and (b or c) and (d or e)) or ((w and x) or (y and z))')
Logicparse understands spelled-out logic functions "and", "or", "nand", "nor", "xor", "xnor", "not", but also common symbols such as "+", "&", "⊕" representing "or", "and", and "xor".
.. jupyter-execute::
logicparse('¬ (a ∨ b) & (c ⊻ d)') # Using symbols
Use the `gateH` and `gateW` parameters to adjust how gates line up:
.. jupyter-execute::
logicparse('(not a) and b or c', gateH=.5)
Truth Tables
------------
Simple tables can be drawn using the :py:class:`schemdraw.logic.table.Table` class. This class is included in the logic module as its primary purpose was for drawing logical truth tables.
The tables are defined using typical Markdown syntax. The `colfmt` parameter works like the LaTeX tabular environment parameter for defining lines to draw between table columns: "cc|c" draws three centered columns, with a vertical line before the last column.
Each column must be specified with a 'c', 'r', or 'l' for center, right, or left justification
Two pipes (`||`), or a double pipe character (`ǁ`) draw a double bar between columns.
Row lines are added to the table string itself, with either `---` or `===` in the row.
.. jupyter-execute::
table = '''
A | B | C
---|---|---
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
'''
logic.Table(table, colfmt='cc||c')
Karnaugh Maps
-------------
Karnaugh Maps, or K-Maps, are useful for simplifying a logical truth table into the smallest number of gates. Schemdraw can draw K-Maps, with 2, 3, or 4 input variables, using the :py:class:`schemdraw.logic.kmap.Kmap` class.
.. jupyter-execute::
logic.Kmap(names='ABCD')
The `names` parameter must be a string with 2, 3, or 4 characters, each defining the name of one input variable.
The `truthtable` parameter contains a list of tuples defining the logic values to display in the map. The first `len(names)` elements are 0's and 1's defining the position of the cell, and the last element is the string to display in that cell.
The `default` parameter is a string to show in each cell of the K-Map when that cell is undefined in the `truthtable`.
For example, this 2x2 K-Map has a '1' in the 01 position, and 0's elsewhere:
.. jupyter-execute::
logic.Kmap(names='AB', truthtable=[('01', '1')])
K-Maps are typically used by grouping sets of 1's together. These groupings can be drawn using the `groups` parameter. The keys of the `groups` dictionary define which cells to group together, and the values of the dictionary define style parameters for the circle around the group.
Each key must be a string of length `len(names)`, with either a `0`, `1`, or `.` in each position. As an example, with `names='ABCD'`, a group key of `"1..."` will place a circle around all cells where A=1. Or `".00."` draws a circle around all cells where B and C are both 0. Groups will automatically "wrap" around the edges.
Parameters of the style dictionary include `color`, `fill`, `lw`, and `ls`.
.. jupyter-execute::
logic.Kmap(names='ABCD',
truthtable=[('1100', '1'),
('1101', '1'),
('1111', '1'),
('1110', '1'),
('0101', '1'),
('0111', 'X'),
('1101', '1'),
('1111', '1'),
('0000', '1'),
('1000', '1')],
groups={'11..': {'color': 'red', 'fill': '#ff000033'},
'.1.1': {'color': 'blue', 'fill': '#0000ff33'},
'.000': {'color': 'green', 'fill': '#00ff0033'}})
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/logic.rst
|
logic.rst
|
Digital Logic
=============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Logic gates can be drawn by importing the :py:mod:`schemdraw.logic.logic` module:
.. code-block:: python
from schemdraw import logic
Logic gates are shown below. Gates define anchors for `out` and `in1`, `in2`, etc.
`Buf`, `Not`, and `NotNot`, and their Schmitt-trigger counterparts, are two-terminal elements that extend leads.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
d += getattr(logic, e)().right().at((x,y)).label(e, loc='right', ofst=.2, halign='left', valign='center')
return d
elms = ['And', 'Nand', 'Or', 'Nor', 'Xor', 'Xnor',
'Buf', 'Not', 'NotNot', 'Tgate', 'Tristate',
'Schmitt', 'SchmittNot', 'SchmittAnd', 'SchmittNand']
drawElements(elms, dx=6)
Gates with more than 2 inputs can be created using the `inputs` parameter. With more than 3 inputs, the back of the gate will extend up and down.
.. jupyter-execute::
logic.Nand(inputs=3)
.. jupyter-execute::
logic.Nor(inputs=4)
Finally, any input can be pre-inverted (active low) using the `inputnots` keyword with a list of input numbers, starting at 1 to match the anchor names, on which to add an invert bubble.
.. jupyter-execute::
logic.Nand(inputs=3, inputnots=[1])
Logic Parser
------------
Logic trees can also be created from a string logic expression such as "(a and b) or c" using using :py:func:`schemdraw.parsing.logic_parser.logicparse`.
The logic parser requires the `pyparsing <https://pyparsing-docs.readthedocs.io/en/latest/>`_ module.
Examples:
.. jupyter-execute::
from schemdraw.parsing import logicparse
logicparse('not ((w and x) or (y and z))', outlabel='$\overline{Q}$')
.. jupyter-execute::
logicparse('((a xor b) and (b or c) and (d or e)) or ((w and x) or (y and z))')
Logicparse understands spelled-out logic functions "and", "or", "nand", "nor", "xor", "xnor", "not", but also common symbols such as "+", "&", "⊕" representing "or", "and", and "xor".
.. jupyter-execute::
logicparse('¬ (a ∨ b) & (c ⊻ d)') # Using symbols
Use the `gateH` and `gateW` parameters to adjust how gates line up:
.. jupyter-execute::
logicparse('(not a) and b or c', gateH=.5)
Truth Tables
------------
Simple tables can be drawn using the :py:class:`schemdraw.logic.table.Table` class. This class is included in the logic module as its primary purpose was for drawing logical truth tables.
The tables are defined using typical Markdown syntax. The `colfmt` parameter works like the LaTeX tabular environment parameter for defining lines to draw between table columns: "cc|c" draws three centered columns, with a vertical line before the last column.
Each column must be specified with a 'c', 'r', or 'l' for center, right, or left justification
Two pipes (`||`), or a double pipe character (`ǁ`) draw a double bar between columns.
Row lines are added to the table string itself, with either `---` or `===` in the row.
.. jupyter-execute::
table = '''
A | B | C
---|---|---
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
'''
logic.Table(table, colfmt='cc||c')
Karnaugh Maps
-------------
Karnaugh Maps, or K-Maps, are useful for simplifying a logical truth table into the smallest number of gates. Schemdraw can draw K-Maps, with 2, 3, or 4 input variables, using the :py:class:`schemdraw.logic.kmap.Kmap` class.
.. jupyter-execute::
logic.Kmap(names='ABCD')
The `names` parameter must be a string with 2, 3, or 4 characters, each defining the name of one input variable.
The `truthtable` parameter contains a list of tuples defining the logic values to display in the map. The first `len(names)` elements are 0's and 1's defining the position of the cell, and the last element is the string to display in that cell.
The `default` parameter is a string to show in each cell of the K-Map when that cell is undefined in the `truthtable`.
For example, this 2x2 K-Map has a '1' in the 01 position, and 0's elsewhere:
.. jupyter-execute::
logic.Kmap(names='AB', truthtable=[('01', '1')])
K-Maps are typically used by grouping sets of 1's together. These groupings can be drawn using the `groups` parameter. The keys of the `groups` dictionary define which cells to group together, and the values of the dictionary define style parameters for the circle around the group.
Each key must be a string of length `len(names)`, with either a `0`, `1`, or `.` in each position. As an example, with `names='ABCD'`, a group key of `"1..."` will place a circle around all cells where A=1. Or `".00."` draws a circle around all cells where B and C are both 0. Groups will automatically "wrap" around the edges.
Parameters of the style dictionary include `color`, `fill`, `lw`, and `ls`.
.. jupyter-execute::
logic.Kmap(names='ABCD',
truthtable=[('1100', '1'),
('1101', '1'),
('1111', '1'),
('1110', '1'),
('0101', '1'),
('0111', 'X'),
('1101', '1'),
('1111', '1'),
('0000', '1'),
('1000', '1')],
groups={'11..': {'color': 'red', 'fill': '#ff000033'},
'.1.1': {'color': 'blue', 'fill': '#0000ff33'},
'.000': {'color': 'green', 'fill': '#00ff0033'}})
| 0.887296 | 0.711681 |
Connectors
==========
.. jupyter-execute::
:hide-code:
from functools import partial
import schemdraw
from schemdraw import elements as elm
All connectors are defined with a default pin spacing of 0.6, matching the default pin spacing of the :py:class:`schemdraw.elements.intcircuits.Ic` class, for easy connection of multiple signals.
Headers
^^^^^^^
A :py:class:`schemdraw.elements.connectors.Header` is a generic Header block with any number of rows and columns. It can have round, square, or screw-head connection points.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
return d
elmlist = [elm.Header,
partial(elm.Header, shownumber=True),
partial(elm.Header, rows=3, cols=2),
partial(elm.Header, style='square'),
partial(elm.Header, style='screw'),
partial(elm.Header, pinsleft=['A', 'B', 'C', 'D'], pinalignleft='center')]
drawElements(elmlist, cols=2, dy=4)
Header pins are given anchor names `pin1`, `pin2`, etc.
Pin number labels and anchor names can be ordered left-to-right (`lr`), up-to-down (`ud`), or counterclockwise (`ccw`) like a traditional IC, depending on the `numbering` argument.
The `flip` argument can be set True to put pin 1 at the bottom.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d.add(elm.Header(shownumber=True, cols=2, numbering='lr', label="lr"))
d.add(elm.Header(at=[3, 0], shownumber=True, cols=2, numbering='ud', label="ud"))
d.add(elm.Header(at=[6, 0], shownumber=True, cols=2, numbering='ccw', label="ccw"))
d.draw()
A :py:class:`schemdraw.elements.connectors.Jumper` element is also defined, as a simple rectangle, for easy placing onto a header.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
J = d.add(elm.Header(cols=2, style='square'))
d.add(elm.Jumper().at(J.pin3).fill('lightgray'))
.. jupyter-execute::
:hide-code:
d.draw()
D-Sub Connectors
^^^^^^^^^^^^^^^^
Both :py:class:`schemdraw.elements.connectors.DB9` and :py:class:`schemdraw.elements.connectors.DB25` subminiature connectors are defined, with anchors `pin1` through `pin9` or `pin25`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.DB9(label='DB9'))
d.add(elm.DB9(at=[3, 0], number=True, label='DB9(number=True)'))
d.add(elm.DB25(at=[6, 0], label='DB25'))
d.draw()
Multiple Lines
^^^^^^^^^^^^^^
The :py:class:`schemdraw.elements.connectors.RightLines` and :py:class:`schemdraw.elements.connectors.OrthoLines` elements are useful for connecting multiple pins of an integrated circuit or header all at once. Both need an `at` and `to` location specified, along with the `n` parameter for setting the number of lines to draw. Use RightLines when the Headers are perpindicular to each other.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='t', slot='1/4'),
elm.IcPin(name='B', side='t', slot='2/4'),
elm.IcPin(name='C', side='t', slot='3/4'),
elm.IcPin(name='D', side='t', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((5,4)))
d.add(elm.RightLines(n=4).at(D2.pin1).to(D1.D).label('RightLines'))
.. jupyter-execute::
:hide-code:
d.draw()
OrthoLines draw a z-shaped orthogonal connection. Use OrthoLines when the Headers are parallel but vertically offset.
Use the `xstart` parameter, between 0 and 1, to specify the position where the first OrthoLine turns vertical.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='r', slot='1/4'),
elm.IcPin(name='B', side='r', slot='2/4'),
elm.IcPin(name='C', side='r', slot='3/4'),
elm.IcPin(name='D', side='r', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((7, -3)))
d.add(elm.OrthoLines(n=4).at(D1.D).to(D2.pin1).label('OrthoLines'))
.. jupyter-execute::
:hide-code:
d.draw()
Data Busses
^^^^^^^^^^^
Sometimes, multiple I/O pins to an integrated circuit are lumped together into a data bus.
The connections to a bus can be drawn using the :py:class:`schemdraw.elements.connectors.BusConnect` element, which takes `n` the number of data lines and an argument.
:py:class:`schemdraw.elements.connectors.BusLine` is simply a wider line used to extend the full bus to its destination.
BusConnect elements define anchors `start`, `end` on the endpoints of the wide bus line, and `pin1`, `pin2`, etc. for the individual signals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 2-4
J = d.add(elm.Header(rows=6))
B = d.add(elm.BusConnect(n=6).at(J.pin1))
d.add(elm.BusLine().down().at(B.end).length(3))
B2 = d.add(elm.BusConnect(n=6).anchor('start').reverse())
d.add(elm.Header(rows=6).at(B2.pin1).anchor('pin1'))
.. jupyter-execute::
:hide-code:
d.draw()
Outlets
^^^^^^^
Power outlets and plugs are drawn using `OutletX` classes, with international styles A through L. Each has anchors
`hot`, `neutral`, and `ground` (if applicable).
The `plug` parameter fills the prongs to indicate a plug versus an outlet.
.. jupyter-execute::
:hide-code:
outlets = [elm.OutletA, elm.OutletB, elm.OutletC, elm.OutletD, elm.OutletE, elm.OutletF,
elm.OutletG, elm.OutletH, elm.OutletI, elm.OutletJ, elm.OutletK, elm.OutletL]
d = schemdraw.Drawing()
for i, outlet in enumerate(outlets):
K = outlet().label(outlet.__name__, loc='top')
d.here = (i % 4) * 4, (i//4) * -4
d += K
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/connectors.rst
|
connectors.rst
|
Connectors
==========
.. jupyter-execute::
:hide-code:
from functools import partial
import schemdraw
from schemdraw import elements as elm
All connectors are defined with a default pin spacing of 0.6, matching the default pin spacing of the :py:class:`schemdraw.elements.intcircuits.Ic` class, for easy connection of multiple signals.
Headers
^^^^^^^
A :py:class:`schemdraw.elements.connectors.Header` is a generic Header block with any number of rows and columns. It can have round, square, or screw-head connection points.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
return d
elmlist = [elm.Header,
partial(elm.Header, shownumber=True),
partial(elm.Header, rows=3, cols=2),
partial(elm.Header, style='square'),
partial(elm.Header, style='screw'),
partial(elm.Header, pinsleft=['A', 'B', 'C', 'D'], pinalignleft='center')]
drawElements(elmlist, cols=2, dy=4)
Header pins are given anchor names `pin1`, `pin2`, etc.
Pin number labels and anchor names can be ordered left-to-right (`lr`), up-to-down (`ud`), or counterclockwise (`ccw`) like a traditional IC, depending on the `numbering` argument.
The `flip` argument can be set True to put pin 1 at the bottom.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d.add(elm.Header(shownumber=True, cols=2, numbering='lr', label="lr"))
d.add(elm.Header(at=[3, 0], shownumber=True, cols=2, numbering='ud', label="ud"))
d.add(elm.Header(at=[6, 0], shownumber=True, cols=2, numbering='ccw', label="ccw"))
d.draw()
A :py:class:`schemdraw.elements.connectors.Jumper` element is also defined, as a simple rectangle, for easy placing onto a header.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
J = d.add(elm.Header(cols=2, style='square'))
d.add(elm.Jumper().at(J.pin3).fill('lightgray'))
.. jupyter-execute::
:hide-code:
d.draw()
D-Sub Connectors
^^^^^^^^^^^^^^^^
Both :py:class:`schemdraw.elements.connectors.DB9` and :py:class:`schemdraw.elements.connectors.DB25` subminiature connectors are defined, with anchors `pin1` through `pin9` or `pin25`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.DB9(label='DB9'))
d.add(elm.DB9(at=[3, 0], number=True, label='DB9(number=True)'))
d.add(elm.DB25(at=[6, 0], label='DB25'))
d.draw()
Multiple Lines
^^^^^^^^^^^^^^
The :py:class:`schemdraw.elements.connectors.RightLines` and :py:class:`schemdraw.elements.connectors.OrthoLines` elements are useful for connecting multiple pins of an integrated circuit or header all at once. Both need an `at` and `to` location specified, along with the `n` parameter for setting the number of lines to draw. Use RightLines when the Headers are perpindicular to each other.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='t', slot='1/4'),
elm.IcPin(name='B', side='t', slot='2/4'),
elm.IcPin(name='C', side='t', slot='3/4'),
elm.IcPin(name='D', side='t', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((5,4)))
d.add(elm.RightLines(n=4).at(D2.pin1).to(D1.D).label('RightLines'))
.. jupyter-execute::
:hide-code:
d.draw()
OrthoLines draw a z-shaped orthogonal connection. Use OrthoLines when the Headers are parallel but vertically offset.
Use the `xstart` parameter, between 0 and 1, to specify the position where the first OrthoLine turns vertical.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='r', slot='1/4'),
elm.IcPin(name='B', side='r', slot='2/4'),
elm.IcPin(name='C', side='r', slot='3/4'),
elm.IcPin(name='D', side='r', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((7, -3)))
d.add(elm.OrthoLines(n=4).at(D1.D).to(D2.pin1).label('OrthoLines'))
.. jupyter-execute::
:hide-code:
d.draw()
Data Busses
^^^^^^^^^^^
Sometimes, multiple I/O pins to an integrated circuit are lumped together into a data bus.
The connections to a bus can be drawn using the :py:class:`schemdraw.elements.connectors.BusConnect` element, which takes `n` the number of data lines and an argument.
:py:class:`schemdraw.elements.connectors.BusLine` is simply a wider line used to extend the full bus to its destination.
BusConnect elements define anchors `start`, `end` on the endpoints of the wide bus line, and `pin1`, `pin2`, etc. for the individual signals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 2-4
J = d.add(elm.Header(rows=6))
B = d.add(elm.BusConnect(n=6).at(J.pin1))
d.add(elm.BusLine().down().at(B.end).length(3))
B2 = d.add(elm.BusConnect(n=6).anchor('start').reverse())
d.add(elm.Header(rows=6).at(B2.pin1).anchor('pin1'))
.. jupyter-execute::
:hide-code:
d.draw()
Outlets
^^^^^^^
Power outlets and plugs are drawn using `OutletX` classes, with international styles A through L. Each has anchors
`hot`, `neutral`, and `ground` (if applicable).
The `plug` parameter fills the prongs to indicate a plug versus an outlet.
.. jupyter-execute::
:hide-code:
outlets = [elm.OutletA, elm.OutletB, elm.OutletC, elm.OutletD, elm.OutletE, elm.OutletF,
elm.OutletG, elm.OutletH, elm.OutletI, elm.OutletJ, elm.OutletK, elm.OutletL]
d = schemdraw.Drawing()
for i, outlet in enumerate(outlets):
K = outlet().label(outlet.__name__, loc='top')
d.here = (i % 4) * 4, (i//4) * -4
d += K
d.draw()
| 0.881621 | 0.463809 |
Compound Elements
=================
Several compound elements defined based on other basic elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['start', 'end', 'center', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Optocoupler
-----------
:py:class:`schemdraw.elements.compound.Optocoupler` can be drawn with or without a base contact.
.. jupyter-execute::
:hide-code:
drawElements([elm.Optocoupler, partial(elm.Optocoupler, base=True)])
Relay
-----
:py:class:`schemdraw.elements.compound.Relay` can be drawn with different options for switches and inductor solenoids.
.. jupyter-execute::
:hide-code:
drawElements([elm.Relay,
partial(elm.Relay, switch='spdt'),
partial(elm.Relay, switch='dpst'),
partial(elm.Relay, switch='dpdt')],
cols=2, dy=3)
Wheatstone
----------
:py:class:`schemdraw.elements.compound.Wheatstone` can be drawn with or without the output voltage taps.
The `labels` argument specifies a list of labels for each resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Wheatstone()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Wheatstone', loc='S', ofst=(0, -.5)))
d += (W:=elm.Wheatstone(vout=True).at((7, 0))
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('vo1', loc='vo1', color='blue', fontsize=10)
.label('vo2', loc='vo2', color='blue', fontsize=10)
.label('Wheatstone(vout=True)', loc='S', ofst=(0, -.5)))
d.draw()
Rectifier
----------
:py:class:`schemdraw.elements.compound.Rectifier` draws four diodes at 45 degree angles.
The `labels` argument specifies a list of labels for each diode.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Rectifier()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Rectifier', loc='S', ofst=(0, -.5)))
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/compound.rst
|
compound.rst
|
Compound Elements
=================
Several compound elements defined based on other basic elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['start', 'end', 'center', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Optocoupler
-----------
:py:class:`schemdraw.elements.compound.Optocoupler` can be drawn with or without a base contact.
.. jupyter-execute::
:hide-code:
drawElements([elm.Optocoupler, partial(elm.Optocoupler, base=True)])
Relay
-----
:py:class:`schemdraw.elements.compound.Relay` can be drawn with different options for switches and inductor solenoids.
.. jupyter-execute::
:hide-code:
drawElements([elm.Relay,
partial(elm.Relay, switch='spdt'),
partial(elm.Relay, switch='dpst'),
partial(elm.Relay, switch='dpdt')],
cols=2, dy=3)
Wheatstone
----------
:py:class:`schemdraw.elements.compound.Wheatstone` can be drawn with or without the output voltage taps.
The `labels` argument specifies a list of labels for each resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Wheatstone()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Wheatstone', loc='S', ofst=(0, -.5)))
d += (W:=elm.Wheatstone(vout=True).at((7, 0))
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('vo1', loc='vo1', color='blue', fontsize=10)
.label('vo2', loc='vo2', color='blue', fontsize=10)
.label('Wheatstone(vout=True)', loc='S', ofst=(0, -.5)))
d.draw()
Rectifier
----------
:py:class:`schemdraw.elements.compound.Rectifier` draws four diodes at 45 degree angles.
The `labels` argument specifies a list of labels for each diode.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Rectifier()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Rectifier', loc='S', ofst=(0, -.5)))
d.draw()
| 0.808181 | 0.350171 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _integratedcircuit:
Integrated Circuits
-------------------
The :py:class:`schemdraw.elements.intcircuits.Ic` class is used to make integrated circuits, multiplexers, and other black box elements. The :py:class:`schemdraw.elements.intcircuits.IcPin` class is used to define each input/output pin before adding it to the Ic.
All pins will be given an anchor name of `inXY` where X is the side (L, R, T, B), and Y is the pin number along that side.
Pins also define anchors based on the `name` parameter.
If the `anchorname` parameter is provided for the pin, this name will be used, so that the pin `name` can be any string even if it cannot be used as a Python variable name.
Here, a J-K flip flop, as part of an HC7476 integrated circuit, is drawn with input names and pin numbers.
.. jupyter-execute::
JK = elm.Ic(pins=[elm.IcPin(name='>', pin='1', side='left'),
elm.IcPin(name='K', pin='16', side='left'),
elm.IcPin(name='J', pin='4', side='left'),
elm.IcPin(name='$\overline{Q}$', pin='14', side='right', anchorname='QBAR'),
elm.IcPin(name='Q', pin='15', side='right')],
edgepadW = .5, # Make it a bit wider
pinspacing=1).label('HC7476', 'bottom', fontsize=12)
display(JK)
Notice the use of `$\overline{Q}$` to acheive the label on the inverting output.
The anchor positions can be accessed using attributes, such as `JK.Q` for the
non-inverting output. However, inverting output is named `$\overline{Q}`, which is
not accessible using the typical dot notation. It could be accessed using
`getattr(JK, '$\overline{Q}$')`, but to avoid this an alternative anchorname of `QBAR`
was defined.
Multiplexers
^^^^^^^^^^^^
Multiplexers and demultiplexers are drawn with the :py:class:`schemdraw.elements.intcircuits.Multiplexer` class which wraps the Ic class.
.. jupyter-execute::
elm.Multiplexer(
pins=[elm.IcPin(name='C', side='L'),
elm.IcPin(name='B', side='L'),
elm.IcPin(name='A', side='L'),
elm.IcPin(name='Q', side='R'),
elm.IcPin(name='T', side='B', invert=True)],
edgepadH=-.5)
See the :ref:`gallery` for more examples.
Seven-Segment Display
^^^^^^^^^^^^^^^^^^^^^
A seven-segment display, in :py:class:`schemdraw.elements.intcircuits.SevenSegment`, provides a single digit
with several options including decimal point and common anode or common cathode mode. The :py:meth:`schemdraw.elements.intcircuits.sevensegdigit` method generates a list of Segment objects that can be used to add
a digit to another element, for example to make a multi-digit display.
.. jupyter-execute::
:hide-code:
elm.SevenSegment()
DIP Integrated Circuits
^^^^^^^^^^^^^^^^^^^^^^^
Integrated circuits can be drawn in dual-inline package style with :py:class:`schemdraw.elements.intcircuits.IcDIP`.
Anchors allow connecting elements externally to show the IC in a circuit, or interanally to show the internal
configuration of the IC (see :ref:`dip741`.)
.. jupyter-execute::
:hide-code:
elm.IcDIP()
Predefined ICs
^^^^^^^^^^^^^^
A few common integrated circuits are predefined as shown below.
.. jupyter-execute::
:hide-code:
elm.Ic555().label('Ic555()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.VoltageRegulator().label('VoltageRegulator()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.DFlipFlop().label('DFlipFlop()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.JKFlipFlop().label('JKFlipFlop()', 'bottom')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/intcircuits.rst
|
intcircuits.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _integratedcircuit:
Integrated Circuits
-------------------
The :py:class:`schemdraw.elements.intcircuits.Ic` class is used to make integrated circuits, multiplexers, and other black box elements. The :py:class:`schemdraw.elements.intcircuits.IcPin` class is used to define each input/output pin before adding it to the Ic.
All pins will be given an anchor name of `inXY` where X is the side (L, R, T, B), and Y is the pin number along that side.
Pins also define anchors based on the `name` parameter.
If the `anchorname` parameter is provided for the pin, this name will be used, so that the pin `name` can be any string even if it cannot be used as a Python variable name.
Here, a J-K flip flop, as part of an HC7476 integrated circuit, is drawn with input names and pin numbers.
.. jupyter-execute::
JK = elm.Ic(pins=[elm.IcPin(name='>', pin='1', side='left'),
elm.IcPin(name='K', pin='16', side='left'),
elm.IcPin(name='J', pin='4', side='left'),
elm.IcPin(name='$\overline{Q}$', pin='14', side='right', anchorname='QBAR'),
elm.IcPin(name='Q', pin='15', side='right')],
edgepadW = .5, # Make it a bit wider
pinspacing=1).label('HC7476', 'bottom', fontsize=12)
display(JK)
Notice the use of `$\overline{Q}$` to acheive the label on the inverting output.
The anchor positions can be accessed using attributes, such as `JK.Q` for the
non-inverting output. However, inverting output is named `$\overline{Q}`, which is
not accessible using the typical dot notation. It could be accessed using
`getattr(JK, '$\overline{Q}$')`, but to avoid this an alternative anchorname of `QBAR`
was defined.
Multiplexers
^^^^^^^^^^^^
Multiplexers and demultiplexers are drawn with the :py:class:`schemdraw.elements.intcircuits.Multiplexer` class which wraps the Ic class.
.. jupyter-execute::
elm.Multiplexer(
pins=[elm.IcPin(name='C', side='L'),
elm.IcPin(name='B', side='L'),
elm.IcPin(name='A', side='L'),
elm.IcPin(name='Q', side='R'),
elm.IcPin(name='T', side='B', invert=True)],
edgepadH=-.5)
See the :ref:`gallery` for more examples.
Seven-Segment Display
^^^^^^^^^^^^^^^^^^^^^
A seven-segment display, in :py:class:`schemdraw.elements.intcircuits.SevenSegment`, provides a single digit
with several options including decimal point and common anode or common cathode mode. The :py:meth:`schemdraw.elements.intcircuits.sevensegdigit` method generates a list of Segment objects that can be used to add
a digit to another element, for example to make a multi-digit display.
.. jupyter-execute::
:hide-code:
elm.SevenSegment()
DIP Integrated Circuits
^^^^^^^^^^^^^^^^^^^^^^^
Integrated circuits can be drawn in dual-inline package style with :py:class:`schemdraw.elements.intcircuits.IcDIP`.
Anchors allow connecting elements externally to show the IC in a circuit, or interanally to show the internal
configuration of the IC (see :ref:`dip741`.)
.. jupyter-execute::
:hide-code:
elm.IcDIP()
Predefined ICs
^^^^^^^^^^^^^^
A few common integrated circuits are predefined as shown below.
.. jupyter-execute::
:hide-code:
elm.Ic555().label('Ic555()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.VoltageRegulator().label('VoltageRegulator()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.DFlipFlop().label('DFlipFlop()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.JKFlipFlop().label('JKFlipFlop()', 'bottom')
| 0.891501 | 0.58747 |
Timing Diagrams
===============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Digital timing diagrams may be drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` Element in the :py:mod:`schemdraw.logic` module.
Timing diagrams are set up using the WaveJSON syntax used by the `WaveDrom <https://wavedrom.com/>`_ JavaScript application.
.. code-block:: python
from schemdraw import logic
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}]})
The input is a dictionary containing a `signal`, which is a list of each wave to show in the diagram. Each signal is a dictionary which must contain a `name` and `wave`.
An empty dictionary leaves a blank row in the diagram.
Every character in the `wave` specifies the state of the wave for one period. A dot `.` means the previous state is repeated.
Wave characters 'n' and 'p' specify clock signals, and 'N', and 'P' draw clocks with arrows.
'1' and '0' are used to define high and low signals. '2' draws a data block, and '3' through '9' draw data filled with a color. 'x' draws a don't-care or undefined data state.
Data blocks can be labeled by adding a 'data' item to the wave's dictionary.
This example shows the different wave sections:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clock n', 'wave': 'n......'},
{'name': 'clock p', 'wave': 'p......'},
{'name': 'clock N', 'wave': 'N......'},
{'name': 'clock P', 'wave': 'P......'},
{},
{'name': '1s and 0s', 'wave': '0.1.01.'},
{'name': 'data', 'wave': '2..=.2.'}, # '=' is the same as '2'
{'name': 'data named', 'wave': '3.4.6..', 'data': ['A', 'B', 'C']},
{'name': 'dont care', 'wave': 'xx..x..'},
{},
{'name': 'high z', 'wave': 'z.10.z.'},
{'name': 'pull up/down', 'wave': '0u..d.1'},
]})
Putting them together in a more realistic example:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}]})
The `config` key, containing a dictionary with `hscale`, may be used to change the width of one period in the diagram:
.. jupyter-execute::
:emphasize-lines: 6
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}],
'config': {'hscale': 2}})
Signals may also be nested into different groups:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': ['Group',
['Set 1',
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}],
['Set 2',
{'name': 'C', 'wave': '0..1..01.'},
{'name': 'D', 'wave': '101..0...'}]
]})
Using the `node` key in a waveform, plus the `edge` key in the top-level dictionary, provides a way to show transitions between different edges.
.. jupyter-execute::
:emphasize-lines: 5
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.', 'node': '...a.....'},
{'name': 'B', 'wave': '101..0...', 'node': '.....b...'}],
'edge': ['a~>b']
})
Each string in the edge list must start and end with a node name (single character). The characters between them define the type of connecting line: '-' for straight line, '~' for curve, '-\|' for orthogonal lines, and \< or \> to include arrowheads.
For example, 'a-~>b' draws a curved line with arrowhead between nodes a and b.
Using JSON
----------
Because the examples from WaveDrom use JavaScript and JSON, they sometimes cannot be directly pasted into Python as dictionaries.
The :py:meth:`schemdraw.logic.timing.TimingDiagram.from_json` method allows input of the WaveJSON as a string pasted directly from the Javascript/JSON examples without modification.
Notice lack of quoting on the dictionary keys, requiring the `from_json` method to parse the string.
.. jupyter-execute::
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "P......" },
{ name: "bus", wave: "x.==.=x", data: ["head", "body", "tail", "data"] },
{ name: "wire", wave: "0.1..0." }
]}''')
Schemdraw's Customizations
--------------------------
Schemdraw extends the WaveJSON spcification with a few additional options.
Style Parameters
****************
Each wave dictionary accpets a `color` and `lw` parameter.
The rise/fall time for transitions can be set using the `risetime` parameter to TimingDiagram. Other colors and font sizes may be speficied using keyword arguments to :py:class:`schemdraw.logic.timing.TimingDiagram`.
Asynchronous Signals
********************
WaveDrom does not have a means for defining asynchronous signals - all waves must transition on period boundaries. Schemdraw adds asyncrhonous signals using the `async` parameter, as a list of period multiples for each transition in the wave. Note the beginning and end time of the wave must also be specified, so the length of the `async` list must be one more than the length of `wave`.
.. jupyter-execute::
:emphasize-lines: 4
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'n......'},
{'name': 'B', 'wave': '010', 'async': [0, 1.6, 4.25, 7]}]},
risetime=.03)
Extended Edge Notation
**********************
Additional "edge" string notations are allowed for more complex labeling of edge timings, including asynchronous start and end times and labels just above or below a wave.
Each edge string using this syntax takes the form
.. code-block:: python
'[WaveNum:Period]<->[WaveNum:Period]{color,ls} Label'
Everything after the first space will be drawn as the label in the center of the line.
The values in square brackets designate the start and end position of the line.
`WaveNum` is the integer row number (starting at 0) of the wave, and `Period` is the possibly fractional number of periods in time for the node. `WaveNum` may be appended by a `^` or `v` to designate notations just above, or just below, the wave, respectively.
Between the two square-bracket expressions is the standard line/arrow type designator. In optional curly braces, the line color and linestyle may be entered.
Some examples are shown here:
.. jupyter-execute::
:emphasize-lines: 5-7
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': 'x3...x'},
{'name': 'B', 'wave': 'x6.6.x'}],
'edge': ['[0^:1]+[0^:5] $t_1$',
'[1^:1]<->[1^:3] $t_o$',
'[0^:3]-[1v:3]{gray,:}',
]},
ygap=.5, grid=False)
When placing edge labels above or below the wave, it can be useful to add the `ygap` parameter to TimingDiagram to increase the spacing between waves.
See the :ref:`gallerytiming` Gallery for more examples.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/timing.rst
|
timing.rst
|
Timing Diagrams
===============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Digital timing diagrams may be drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` Element in the :py:mod:`schemdraw.logic` module.
Timing diagrams are set up using the WaveJSON syntax used by the `WaveDrom <https://wavedrom.com/>`_ JavaScript application.
.. code-block:: python
from schemdraw import logic
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}]})
The input is a dictionary containing a `signal`, which is a list of each wave to show in the diagram. Each signal is a dictionary which must contain a `name` and `wave`.
An empty dictionary leaves a blank row in the diagram.
Every character in the `wave` specifies the state of the wave for one period. A dot `.` means the previous state is repeated.
Wave characters 'n' and 'p' specify clock signals, and 'N', and 'P' draw clocks with arrows.
'1' and '0' are used to define high and low signals. '2' draws a data block, and '3' through '9' draw data filled with a color. 'x' draws a don't-care or undefined data state.
Data blocks can be labeled by adding a 'data' item to the wave's dictionary.
This example shows the different wave sections:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clock n', 'wave': 'n......'},
{'name': 'clock p', 'wave': 'p......'},
{'name': 'clock N', 'wave': 'N......'},
{'name': 'clock P', 'wave': 'P......'},
{},
{'name': '1s and 0s', 'wave': '0.1.01.'},
{'name': 'data', 'wave': '2..=.2.'}, # '=' is the same as '2'
{'name': 'data named', 'wave': '3.4.6..', 'data': ['A', 'B', 'C']},
{'name': 'dont care', 'wave': 'xx..x..'},
{},
{'name': 'high z', 'wave': 'z.10.z.'},
{'name': 'pull up/down', 'wave': '0u..d.1'},
]})
Putting them together in a more realistic example:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}]})
The `config` key, containing a dictionary with `hscale`, may be used to change the width of one period in the diagram:
.. jupyter-execute::
:emphasize-lines: 6
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}],
'config': {'hscale': 2}})
Signals may also be nested into different groups:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': ['Group',
['Set 1',
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}],
['Set 2',
{'name': 'C', 'wave': '0..1..01.'},
{'name': 'D', 'wave': '101..0...'}]
]})
Using the `node` key in a waveform, plus the `edge` key in the top-level dictionary, provides a way to show transitions between different edges.
.. jupyter-execute::
:emphasize-lines: 5
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.', 'node': '...a.....'},
{'name': 'B', 'wave': '101..0...', 'node': '.....b...'}],
'edge': ['a~>b']
})
Each string in the edge list must start and end with a node name (single character). The characters between them define the type of connecting line: '-' for straight line, '~' for curve, '-\|' for orthogonal lines, and \< or \> to include arrowheads.
For example, 'a-~>b' draws a curved line with arrowhead between nodes a and b.
Using JSON
----------
Because the examples from WaveDrom use JavaScript and JSON, they sometimes cannot be directly pasted into Python as dictionaries.
The :py:meth:`schemdraw.logic.timing.TimingDiagram.from_json` method allows input of the WaveJSON as a string pasted directly from the Javascript/JSON examples without modification.
Notice lack of quoting on the dictionary keys, requiring the `from_json` method to parse the string.
.. jupyter-execute::
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "P......" },
{ name: "bus", wave: "x.==.=x", data: ["head", "body", "tail", "data"] },
{ name: "wire", wave: "0.1..0." }
]}''')
Schemdraw's Customizations
--------------------------
Schemdraw extends the WaveJSON spcification with a few additional options.
Style Parameters
****************
Each wave dictionary accpets a `color` and `lw` parameter.
The rise/fall time for transitions can be set using the `risetime` parameter to TimingDiagram. Other colors and font sizes may be speficied using keyword arguments to :py:class:`schemdraw.logic.timing.TimingDiagram`.
Asynchronous Signals
********************
WaveDrom does not have a means for defining asynchronous signals - all waves must transition on period boundaries. Schemdraw adds asyncrhonous signals using the `async` parameter, as a list of period multiples for each transition in the wave. Note the beginning and end time of the wave must also be specified, so the length of the `async` list must be one more than the length of `wave`.
.. jupyter-execute::
:emphasize-lines: 4
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'n......'},
{'name': 'B', 'wave': '010', 'async': [0, 1.6, 4.25, 7]}]},
risetime=.03)
Extended Edge Notation
**********************
Additional "edge" string notations are allowed for more complex labeling of edge timings, including asynchronous start and end times and labels just above or below a wave.
Each edge string using this syntax takes the form
.. code-block:: python
'[WaveNum:Period]<->[WaveNum:Period]{color,ls} Label'
Everything after the first space will be drawn as the label in the center of the line.
The values in square brackets designate the start and end position of the line.
`WaveNum` is the integer row number (starting at 0) of the wave, and `Period` is the possibly fractional number of periods in time for the node. `WaveNum` may be appended by a `^` or `v` to designate notations just above, or just below, the wave, respectively.
Between the two square-bracket expressions is the standard line/arrow type designator. In optional curly braces, the line color and linestyle may be entered.
Some examples are shown here:
.. jupyter-execute::
:emphasize-lines: 5-7
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': 'x3...x'},
{'name': 'B', 'wave': 'x6.6.x'}],
'edge': ['[0^:1]+[0^:5] $t_1$',
'[1^:1]<->[1^:3] $t_o$',
'[0^:3]-[1v:3]{gray,:}',
]},
ygap=.5, grid=False)
When placing edge labels above or below the wave, it can be useful to add the `ygap` parameter to TimingDiagram to increase the spacing between waves.
See the :ref:`gallerytiming` Gallery for more examples.
| 0.880682 | 0.617599 |
Flowcharts and Diagrams
=======================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import flow
Schemdraw provides basic symbols for flowcharting and state diagrams.
The :py:mod:`schemdraw.flow.flow` module contains a set of functions for defining
flowchart blocks and connecting lines that can be added to schemdraw Drawings.
.. code-block:: python
from schemdraw import flow
Flowchart blocks:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Start().label('Start').drop('E'))
d.add(flow.Arrow())
d.add(flow.Ellipse().label('Ellipse'))
d.add(flow.Arrow())
d.add(flow.Box(label='Box'))
d.add(flow.Arrow())
d.add(flow.RoundBox(label='RoundBox').drop('S'))
d.add(flow.Arrow().down())
d.add(flow.Subroutine(label='Subroutine').drop('W'))
d.add(flow.Arrow().left())
d.add(flow.Data(label='Data'))
d.add(flow.Arrow())
d.add(flow.Decision(label='Decision'))
d.add(flow.Arrow())
d.add(flow.Connect(label='Connect'))
d.draw()
Some elements have been defined with multiple names, which can be used depending on the context or user preference:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Terminal().label('Terminal').drop('E'))
d.add(flow.Arrow())
d.add(flow.Process().label('Process'))
d.add(flow.Arrow())
d.add(flow.RoundProcess().label('RoundProcess'))
d.add(flow.Arrow())
d.add(flow.Circle(label='Circle'))
d.add(flow.Arrow())
d.add(flow.State(label='State'))
d.add(flow.Arrow())
d.add(flow.StateEnd(label='StateEnd'))
d.draw()
All flowchart symbols have 16 anchor positions named for the compass directions: 'N', 'S', 'E', 'W', 'NE', 'SE, 'NNE', etc., plus a 'center' anchor.
The :py:class:`schemdraw.elements.intcircuits.Ic` element can be used with the flowchart elements to create blocks with other inputs/outputs per side if needed.
The size of each block must be specified manually using `w` and `h` or `r` parameters to size each block to fit any labels.
Connecting Lines
----------------
Typical flowcharts will use `Line` or `Arrow` elements to connect the boxes. The line and arrow elements have been included in the `flow` module for convenience.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Do something').drop('E')
d += flow.Arrow().right()
d += flow.Process().label('Do something\nelse')
Some flow diagrams, such as State Machine diagrams, often use curved connectors between states. Several Arc connectors are available.
Each Arc element takes an `arrow` parameter, which may be '->', '<-', or '<->', to define the end(s) on which to draw arrowheads.
Arc2
^^^^
`Arc2` draws a symmetric quadratic Bezier curve between the endpoints, with curvature controlled by parameter `k`. Endpoints of the arc should be specified using `at()` and `to()` methods.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State(arrow='->').label('B').at((4, 0)))
d += flow.Arc2(arrow='->').at(a.NE).to(b.NW).color('deeppink').label('Arc2')
d += flow.Arc2(k=.2, arrow='<->').at(b.SW).to(a.SE).color('mediumblue').label('Arc2')
.. jupyter-execute::
:hide-code:
d.draw()
ArcZ and ArcN
^^^^^^^^^^^^^
These draw symmetric cubic Bezier curves between the endpoints. The `ArcZ` curve approaches the endpoints horizontally, and `ArcN` approaches them vertically.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((4, 4)))
d += (c := flow.State().label('C').at((8, 0)))
d += flow.ArcN(arrow='<->').at(a.N).to(b.S).color('deeppink').label('ArcN')
d += flow.ArcZ(arrow='<->').at(b.E).to(c.W).color('mediumblue').label('ArcZ')
.. jupyter-execute::
:hide-code:
d.draw()
Arc3
^^^^
The `Arc3` curve is an arbitrary cubic Bezier curve, defined by endpoints and angle of approach to each endpoint. `ArcZ` and `ArcN` are simply `Arc3` defined with the angles as 0 and 180, or 90 and 270, respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((3, 3)))
d += flow.Arc3(th1=75, th2=-45, arrow='<->').at(a.N).to(b.SE).color('deeppink').label('Arc3')
.. jupyter-execute::
:hide-code:
d.draw()
ArcLoop
^^^^^^^
The `ArcLoop` curve draws a partial circle that intersects the two endpoints, with the given radius. Often used in state machine diagrams to indicate cases where the state does not change.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += flow.ArcLoop(arrow='<-').at(a.NW).to(a.NNE).color('mediumblue').label('ArcLoop', halign='center')
.. jupyter-execute::
:hide-code:
d.draw()
Decisions
---------
To label the decision branches, the :py:class:`schemdraw.flow.flow.Decision` element takes keyword
arguments for each cardinal direction. For example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
decision = flow.Decision(W='Yes', E='No', S='Maybe').label('Question?')
.. jupyter-execute::
:hide-code:
dec = d.add(decision)
d.add(flow.Line().at(dec.W).left())
d.add(flow.Line().at(dec.E).right())
d.add(flow.Line().at(dec.S).down())
d.draw()
Layout and Flow
---------------
Without any directions specified, boxes flow top to bottom (see left image).
If a direction is specified (right image), the flow will continue in that direction, starting the next arrow at an appropriate anchor.
Otherwise, the `drop` method is useful for specifing where to begin the next arrow.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
d += flow.Terminal().label('Start').at((4, 0))
d += flow.Arrow().theta(-45)
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
See the :ref:`galleryflow` Gallery for more examples.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/flow.rst
|
flow.rst
|
Flowcharts and Diagrams
=======================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import flow
Schemdraw provides basic symbols for flowcharting and state diagrams.
The :py:mod:`schemdraw.flow.flow` module contains a set of functions for defining
flowchart blocks and connecting lines that can be added to schemdraw Drawings.
.. code-block:: python
from schemdraw import flow
Flowchart blocks:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Start().label('Start').drop('E'))
d.add(flow.Arrow())
d.add(flow.Ellipse().label('Ellipse'))
d.add(flow.Arrow())
d.add(flow.Box(label='Box'))
d.add(flow.Arrow())
d.add(flow.RoundBox(label='RoundBox').drop('S'))
d.add(flow.Arrow().down())
d.add(flow.Subroutine(label='Subroutine').drop('W'))
d.add(flow.Arrow().left())
d.add(flow.Data(label='Data'))
d.add(flow.Arrow())
d.add(flow.Decision(label='Decision'))
d.add(flow.Arrow())
d.add(flow.Connect(label='Connect'))
d.draw()
Some elements have been defined with multiple names, which can be used depending on the context or user preference:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Terminal().label('Terminal').drop('E'))
d.add(flow.Arrow())
d.add(flow.Process().label('Process'))
d.add(flow.Arrow())
d.add(flow.RoundProcess().label('RoundProcess'))
d.add(flow.Arrow())
d.add(flow.Circle(label='Circle'))
d.add(flow.Arrow())
d.add(flow.State(label='State'))
d.add(flow.Arrow())
d.add(flow.StateEnd(label='StateEnd'))
d.draw()
All flowchart symbols have 16 anchor positions named for the compass directions: 'N', 'S', 'E', 'W', 'NE', 'SE, 'NNE', etc., plus a 'center' anchor.
The :py:class:`schemdraw.elements.intcircuits.Ic` element can be used with the flowchart elements to create blocks with other inputs/outputs per side if needed.
The size of each block must be specified manually using `w` and `h` or `r` parameters to size each block to fit any labels.
Connecting Lines
----------------
Typical flowcharts will use `Line` or `Arrow` elements to connect the boxes. The line and arrow elements have been included in the `flow` module for convenience.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Do something').drop('E')
d += flow.Arrow().right()
d += flow.Process().label('Do something\nelse')
Some flow diagrams, such as State Machine diagrams, often use curved connectors between states. Several Arc connectors are available.
Each Arc element takes an `arrow` parameter, which may be '->', '<-', or '<->', to define the end(s) on which to draw arrowheads.
Arc2
^^^^
`Arc2` draws a symmetric quadratic Bezier curve between the endpoints, with curvature controlled by parameter `k`. Endpoints of the arc should be specified using `at()` and `to()` methods.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State(arrow='->').label('B').at((4, 0)))
d += flow.Arc2(arrow='->').at(a.NE).to(b.NW).color('deeppink').label('Arc2')
d += flow.Arc2(k=.2, arrow='<->').at(b.SW).to(a.SE).color('mediumblue').label('Arc2')
.. jupyter-execute::
:hide-code:
d.draw()
ArcZ and ArcN
^^^^^^^^^^^^^
These draw symmetric cubic Bezier curves between the endpoints. The `ArcZ` curve approaches the endpoints horizontally, and `ArcN` approaches them vertically.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((4, 4)))
d += (c := flow.State().label('C').at((8, 0)))
d += flow.ArcN(arrow='<->').at(a.N).to(b.S).color('deeppink').label('ArcN')
d += flow.ArcZ(arrow='<->').at(b.E).to(c.W).color('mediumblue').label('ArcZ')
.. jupyter-execute::
:hide-code:
d.draw()
Arc3
^^^^
The `Arc3` curve is an arbitrary cubic Bezier curve, defined by endpoints and angle of approach to each endpoint. `ArcZ` and `ArcN` are simply `Arc3` defined with the angles as 0 and 180, or 90 and 270, respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((3, 3)))
d += flow.Arc3(th1=75, th2=-45, arrow='<->').at(a.N).to(b.SE).color('deeppink').label('Arc3')
.. jupyter-execute::
:hide-code:
d.draw()
ArcLoop
^^^^^^^
The `ArcLoop` curve draws a partial circle that intersects the two endpoints, with the given radius. Often used in state machine diagrams to indicate cases where the state does not change.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += flow.ArcLoop(arrow='<-').at(a.NW).to(a.NNE).color('mediumblue').label('ArcLoop', halign='center')
.. jupyter-execute::
:hide-code:
d.draw()
Decisions
---------
To label the decision branches, the :py:class:`schemdraw.flow.flow.Decision` element takes keyword
arguments for each cardinal direction. For example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
decision = flow.Decision(W='Yes', E='No', S='Maybe').label('Question?')
.. jupyter-execute::
:hide-code:
dec = d.add(decision)
d.add(flow.Line().at(dec.W).left())
d.add(flow.Line().at(dec.E).right())
d.add(flow.Line().at(dec.S).down())
d.draw()
Layout and Flow
---------------
Without any directions specified, boxes flow top to bottom (see left image).
If a direction is specified (right image), the flow will continue in that direction, starting the next arrow at an appropriate anchor.
Otherwise, the `drop` method is useful for specifing where to begin the next arrow.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
d += flow.Terminal().label('Start').at((4, 0))
d += flow.Arrow().theta(-45)
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
See the :ref:`galleryflow` Gallery for more examples.
| 0.886482 | 0.667792 |
.. _electrical:
Basic Elements
==============
See :ref:`elecelements` for complete class definitions for these elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
from schemdraw.elements import *
def drawElements(elmlist, cols=3, dx=8, dy=2, lblofst=None, lblloc='rgt'):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
if isinstance(e, str):
name = e
e = getattr(elm, e)
else:
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc=lblloc, halign='left', valign='center', ofst=lblofst)
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['center', 'start', 'end', 'istart', 'iend',
'isource', 'idrain', 'iemitter', 'icollector', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Two-terminal
------------
Two-terminal devices subclass :py:class:`schemdraw.elements.Element2Term`, and have leads that will be extended to make the element the desired length depending on the arguments.
All two-terminal elements define `start`, `end`, and `center` anchors for placing, and a few define other anchors as shown in blue in the tables below.
Some elements have optional parameters, shown in parenthesis in the table below.
.. _styledelements:
Styled Elements
^^^^^^^^^^^^^^^
These elements change based on IEEE/U.S. vs IEC/European style configured by :py:meth:`schemdraw.elements.style`.
Selectable elements, such as `Resistor`, point to either `ResistorIEEE` or `ResistorIEC`, for example.
IEEE Style
**********
IEEE style, common in the U.S., is the default, or it can be configured using
.. code-block:: python
elm.style(elm.STYLE_IEEE)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEEE)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
IEC/European Style
******************
IEC style can be enabled using
.. code-block:: python
elm.style(elm.STYLE_IEC)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEC)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
Resistors
^^^^^^^^^
Both styles of resistors are always available using these classes.
.. jupyter-execute::
:hide-code:
elmlist = [ResistorIEEE, ResistorIEC, ResistorVarIEEE, ResistorVarIEC, Rshunt, PotentiometerIEEE,
PotentiometerIEC, FuseUS, FuseIEEE, FuseIEC]
drawElements(elmlist, cols=2)
Capacitors and Inductors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Capacitor, partial(Capacitor, polar=True),
Capacitor2, partial(Capacitor2, polar=True),
CapacitorVar, CapacitorTrim, Inductor, Inductor2,
partial(Inductor2, loops=2)]
drawElements(elmlist, cols=2)
Diodes
^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Diode,
partial(Diode, fill=True), Schottky, DiodeTunnel, DiodeShockley,
Zener, Varactor, LED, LED2, Photodiode, Diac, Triac, SCR]
drawElements(elmlist, cols=2)
Pathological
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullator, Norator, CurrentMirror, VoltageMirror]
drawElements(elmlist, cols=2)
Miscellaneous
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Breaker, Crystal, CPE, Josephson, Motor, Lamp, Neon, Thermistor, Memristor, Memristor2, Jack, Plug]
drawElements(elmlist, cols=2)
Sources and Meters
^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Source, SourceV, SourceI, SourceSin, SourcePulse,
SourceSquare, SourceTriangle,
SourceRamp, SourceControlled,
SourceControlledV, SourceControlledI, BatteryCell,
Battery, MeterV, MeterA, MeterI, MeterOhm,
Solar]
drawElements(elmlist, cols=2)
Switches
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Button, partial(Button, nc=True),
Switch, partial(Switch, action='open'),
partial(Switch, action='close'),
SwitchReed]
drawElements(elmlist, cols=2)
Lines and Arrows
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Line, Arrow, partial(Arrow, double=True), DataBusLine]
drawElements(elmlist, cols=2)
Single-Terminal
---------------
Single terminal elements are drawn about a single point, and do not move the current drawing position.
Power and Ground
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Ground, GroundSignal, GroundChassis,
Vss, Vdd]
drawElements(elmlist, dx=4, cols=3)
Antennas
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Antenna, AntennaLoop, AntennaLoop2]
drawElements(elmlist, dx=4, cols=3)
Connection Dots
^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Dot, partial(Dot, open=True), DotDotDot,
Arrowhead, NoConnect]
drawElements(elmlist, dx=4, cols=3)
Switches
--------
The standard toggle switch is listed with other two-terminal elements above.
Other switch configurations are shown here.
Single-pole double-throw
^^^^^^^^^^^^^^^^^^^^^^^^
Two options for SPDT switches can be also be drawn with arrows by
adding `action='open'` or `action='close'` parameters.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchSpdt, SwitchSpdt2,
partial(SwitchSpdt, action='open'), partial(SwitchSpdt2, action='open'),
partial(SwitchSpdt, action='close'), partial(SwitchSpdt2, action='close')]
drawElements(elmlist, cols=2, dx=9, dy=3, lblofst=(.5, 0))
Double-pole
^^^^^^^^^^^
DPST and DPDT switches have a `link` parameter for disabling the dotted line
lnking the poles.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchDpst, SwitchDpdt,
partial(SwitchDpst, link=False),
partial(SwitchDpdt, link=False)]
drawElements(elmlist, cols=2, dx=8, dy=4, lblofst=(.7, 0))
Rotary Switch
^^^^^^^^^^^^^
The rotary switch :py:class:`schemdraw.elements.switches.SwitchRotary` takes several parameters, with `n` being the number of contacts and other parameters defining the contact placement.
.. jupyter-execute::
:hide-code:
(SwitchRotary(n=6).label('SwitchRotary(n=6)', ofst=(0,0.5))
.label('P', loc='P', halign='right', color='blue', fontsize=9, ofst=(-.2, 0))
.label('T1', loc='T1', color='blue', fontsize=9, ofst=(0, -.2))
.label('T2', loc='T2', color='blue', fontsize=9, ofst=(0, -.5))
.label('T3', loc='T3', color='blue', fontsize=9, ofst=(.2, 0))
.label('T4', loc='T4', color='blue', fontsize=9, ofst=(.2, 0))
.label('T5', loc='T5', color='blue', fontsize=9, ofst=(0, .2))
.label('T6', loc='T6', color='blue', fontsize=9, ofst=(0, .2))
)
DIP Switch
^^^^^^^^^^
A set of switches in a dual-inline package, where can show each switch flipped up or down.
See :py:class:`schemdraw.elements.switches.SwitchDIP` for options.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (elm.SwitchDIP().label('SwitchDIP', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11))
d += (elm.SwitchDIP(pattern=(0, 0, 1)).label('SwitchDIP(pattern=(0, 0, 1))', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11).at((5, 0)))
d.draw()
Audio Elements
--------------
Speakers, Microphones, Jacks
.. jupyter-execute::
:hide-code:
elmlist = [Speaker, Mic]
drawElements(elmlist, cols=2, dy=5, dx=5, lblofst=[.7, 0])
.. jupyter-execute::
:hide-code:
elmlist = [AudioJack, partial(AudioJack, ring=True),
partial(AudioJack, switch=True),
partial(AudioJack, switch=True, ring=True, ringswitch=True)]
drawElements(elmlist, cols=1, dy=3, lblofst=[1.7, 0])
Labels
------
The `Label` element can be used to add a label anywhere.
The `Gap` is like an "invisible" element, useful for marking the voltage between output terminals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += elm.Line().right().length(1)
d += elm.Dot(open=True)
d += elm.Gap().down().label(['+','Gap','–'])
d += elm.Dot(open=True)
d += elm.Line().left().length(1)
d += elm.Label(label='Label').at([3.5, -.5])
d += elm.Tag().right().at([5, -.5]).label('Tag')
d.draw()
Operational Amplifiers
----------------------
The :py:class:`schemdraw.elements.opamp.Opamp` element defines several anchors for various inputs, including voltage supplies and offset nulls. Optional leads can be added using the `leads` parameter, with anchors exteded to the ends of the leads.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (op := elm.Opamp().label('Opamp', ofst=.6))
d += elm.Dot().at(op.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op.n1a).color('blue').label('n1a', loc='bottom')
d += (op2 := elm.Opamp(sign=False).at([5, 0]).right().label('Opamp(sign=False)', ofst=.6))
d += elm.Dot().at(op2.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op2.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op2.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op2.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op2.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op2.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op2.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op2.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op2.n1a).color('blue').label('n1a', loc='bottom')
d += (op:=elm.Opamp(leads=True).at([10, 0]).right().label('Opamp(leads=True)', ofst=.6)
.label('in1', loc='in1', halign='right', color='blue')
.label('in2', loc='in2', halign='right', color='blue')
.label('out', loc='out', halign='left', color='blue'))
d += elm.Dot().at(op.in1).color('blue')
d += elm.Dot().at(op.in2).color('blue')
d += elm.Dot().at(op.out).color('blue')
d.draw()
Transistors
-----------
Bipolar Junction Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Bjt, BjtNpn, BjtPnp,
partial(Bjt, circle=True),
partial(BjtNpn, circle=True), partial(BjtPnp, circle=True),
BjtPnp2c, partial(BjtPnp2c, circle=True),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=(0, .2))
Field-Effect Transistors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [NFet, PFet, partial(NFet, bulk=True), partial(PFet, bulk=True),
JFet, JFetN, JFetP, partial(JFetN, circle=True), partial(JFetP, circle=True),
AnalogNFet, AnalogPFet, AnalogBiasedFet, partial(AnalogNFet, bulk=True),
partial(AnalogPFet, bulk=True), partial(AnalogBiasedFet, bulk=True),
partial(AnalogNFet, arrow=False), partial(AnalogPFet, arrow=False),
partial(AnalogBiasedFet, arrow=False), partial(AnalogNFet, offset_gate=False),
partial(AnalogPFet, offset_gate=False), partial(AnalogBiasedFet, offset_gate=False),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=[0, -.8])
"Two-Terminal" Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^
Another set of transistor elements subclass :py:class:`schemdraw.elements.Element2Term` so they
have emitter and collector (or source and drain) leads extended to the desired length.
These can be easier to place centered between endpoints, for example.
.. jupyter-execute::
:hide-code:
elmlist = [BjtNpn2, BjtPnp2, BjtPnp2c2, NFet2, PFet2, JFetN2, JFetP2]
drawElements(elmlist, dx=6.5, dy=3)
Two-ports
-----------
Twoport elements share the interface defined by :py:class:`schemdraw.elements.twoports.ElementTwoport`, providing a set of anchors and various styling options. The terminals and box can be enabled or disabled using the `terminals` and `box` arguments. In addition, the `boxfill`, `boxlw`, and `boxls` provide the option to style the outline separately from other elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (tp := elm.TwoPort().label('TwoPort', ofst=.6)).anchor('center')
d += elm.Dot().at(tp.in_p).color('blue').label('in_p', loc='left', valign='center')
d += elm.Dot().at(tp.in_n).color('blue').label('in_n', loc='left', valign='center')
d += elm.Dot().at(tp.out_p).color('blue').label('out_p', loc='right', valign='center')
d += elm.Dot().at(tp.out_n).color('blue').label('in_n', loc='right', valign='center')
d += elm.Dot().at(tp.center).color('blue').label('center', loc='top')
d += (tp := elm.TwoPort(terminals=False, boxlw=3).label('TwoPort(terminals=False, boxlw=3)', ofst=.6)).anchor('center').at([7,0])
d.draw()
Generic
^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [TwoPort, partial(TwoPort, reverse_output=True), partial(TwoPort, arrow=False),
partial(TwoPort, sign=False)]
drawElements(elmlist, dy=3, cols=2)
Transactors (ideal amplifiers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like the generic twoport, the transactors provide the option to reverse the direction of the output or current using the `reverse_output` argument.
.. jupyter-execute::
:hide-code:
elmlist = [VoltageTransactor, TransimpedanceTransactor,TransadmittanceTransactor, CurrentTransactor]
drawElements(elmlist, dy=3, cols=2)
Pathological
^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullor, VMCMPair]
drawElements(elmlist, dy=3, cols=2)
Custom
^^^^^^
The :py:class:`schemdraw.elements.twoports.ElementTwoport` class can be used to define custom twoports by specifying an `input_element` and `output_element`. The `bpadx`, `bpady`, `minw`, `unit`, `width` can be used to tune the horizontal and vertical padding, minimum width of the elements, length of components, and width of the twoport respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.ElementTwoport(input_element=elm.Inductor2(),
output_element=elm.SwitchReed(),
unit=2.5, width=2.5).anchor('center')
d += elm.ElementTwoport(input_element=elm.Lamp(),
output_element=elm.Photodiode().reverse().flip(),
width=3).anchor('center').at([7,0])
.. jupyter-execute::
:hide-code:
d.draw()
Cables
------
:py:class:`schemdraw.elements.cables.Coax` and :py:class:`schemdraw.elements.cables.Triax` cables are 2-Terminal elements that can be made with several options and anchors.
Coax parameters include length, radius, and leadlen for setting the distance between leads and the shell.
Triax parameters include length, radiusinner, radiusouter, leadlen, and shieldofststart for offseting the outer shield from the inner guard.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10)
d += elm.Coax().label('Coax')
d += elm.Coax(length=4, radius=.5).label('Coax(length=5, radius=.5)')
d += (C := elm.Coax().at([0, -3]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'lft', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Triax().at([0, -7]).right().label('Triax')
d += elm.Triax(length=4, radiusinner=.5).label('Triax(length=5, radiusinner=.5)')
d += (C := elm.Triax().at([1, -10]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'left', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Line().theta(45).at(C.guardend_top).length(1).label('guardend_top', 'rgt', halign='left').color('blue')
d += elm.Line().theta(-45).at(C.guardend).length(1).label('guardend', 'rgt', halign='left').color('blue')
d += elm.Line().theta(135).at(C.guardstart_top).length(.3).label('guardstart_top', 'left', halign='right').color('blue')
d += elm.Line().theta(-145).at(C.guardstart).length(.5).label('guardstart', 'left', halign='right').color('blue')
d.draw()
.. jupyter-execute::
:hide-code:
elmlist = [CoaxConnect]
drawElements(elmlist, dx=1, dy=1, lblofst=[.5, 0])
Transformers
------------
The :py:class:`schemdraw.elements.xform.Transformer` element is used to create various transformers.
Anchors `p1`, `p2`, `s1`, and `s2` are defined for all transformers.
Other anchors can be created using the `taps` method to add tap locations to
either side.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.Transformer().label('Transformer'))
d.add(elm.Transformer(loop=True).at([5, 0]).label('Transformer(loop=True)'))
d.here = [0, -4]
d.draw()
Here is a transformers with anchor "B" added using the `tap` method. Note the tap by itself
does not draw anything, but defines a named anchor to connect to.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=12)
x = d.add(elm.Transformer(t1=4, t2=8)
.tap(name='B', pos=3, side='secondary'))
d += elm.Line().at(x.s1).length(d.unit/4).label('s1', 'rgt').color('blue')
d += elm.Line().at(x.s2).length(d.unit/4).label('s2', 'rgt').color('blue')
d += elm.Line().at(x.p1).length(d.unit/4).left().label('p1', 'lft').color('blue')
d += elm.Line().at(x.p2).length(d.unit/4).left().label('p2', 'lft').color('blue')
d += elm.Line().at(x.B).length(d.unit/4).right().label('B', 'rgt').color('blue')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/electrical.rst
|
electrical.rst
|
.. _electrical:
Basic Elements
==============
See :ref:`elecelements` for complete class definitions for these elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
from schemdraw.elements import *
def drawElements(elmlist, cols=3, dx=8, dy=2, lblofst=None, lblloc='rgt'):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
if isinstance(e, str):
name = e
e = getattr(elm, e)
else:
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc=lblloc, halign='left', valign='center', ofst=lblofst)
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['center', 'start', 'end', 'istart', 'iend',
'isource', 'idrain', 'iemitter', 'icollector', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Two-terminal
------------
Two-terminal devices subclass :py:class:`schemdraw.elements.Element2Term`, and have leads that will be extended to make the element the desired length depending on the arguments.
All two-terminal elements define `start`, `end`, and `center` anchors for placing, and a few define other anchors as shown in blue in the tables below.
Some elements have optional parameters, shown in parenthesis in the table below.
.. _styledelements:
Styled Elements
^^^^^^^^^^^^^^^
These elements change based on IEEE/U.S. vs IEC/European style configured by :py:meth:`schemdraw.elements.style`.
Selectable elements, such as `Resistor`, point to either `ResistorIEEE` or `ResistorIEC`, for example.
IEEE Style
**********
IEEE style, common in the U.S., is the default, or it can be configured using
.. code-block:: python
elm.style(elm.STYLE_IEEE)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEEE)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
IEC/European Style
******************
IEC style can be enabled using
.. code-block:: python
elm.style(elm.STYLE_IEC)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEC)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
Resistors
^^^^^^^^^
Both styles of resistors are always available using these classes.
.. jupyter-execute::
:hide-code:
elmlist = [ResistorIEEE, ResistorIEC, ResistorVarIEEE, ResistorVarIEC, Rshunt, PotentiometerIEEE,
PotentiometerIEC, FuseUS, FuseIEEE, FuseIEC]
drawElements(elmlist, cols=2)
Capacitors and Inductors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Capacitor, partial(Capacitor, polar=True),
Capacitor2, partial(Capacitor2, polar=True),
CapacitorVar, CapacitorTrim, Inductor, Inductor2,
partial(Inductor2, loops=2)]
drawElements(elmlist, cols=2)
Diodes
^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Diode,
partial(Diode, fill=True), Schottky, DiodeTunnel, DiodeShockley,
Zener, Varactor, LED, LED2, Photodiode, Diac, Triac, SCR]
drawElements(elmlist, cols=2)
Pathological
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullator, Norator, CurrentMirror, VoltageMirror]
drawElements(elmlist, cols=2)
Miscellaneous
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Breaker, Crystal, CPE, Josephson, Motor, Lamp, Neon, Thermistor, Memristor, Memristor2, Jack, Plug]
drawElements(elmlist, cols=2)
Sources and Meters
^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Source, SourceV, SourceI, SourceSin, SourcePulse,
SourceSquare, SourceTriangle,
SourceRamp, SourceControlled,
SourceControlledV, SourceControlledI, BatteryCell,
Battery, MeterV, MeterA, MeterI, MeterOhm,
Solar]
drawElements(elmlist, cols=2)
Switches
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Button, partial(Button, nc=True),
Switch, partial(Switch, action='open'),
partial(Switch, action='close'),
SwitchReed]
drawElements(elmlist, cols=2)
Lines and Arrows
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Line, Arrow, partial(Arrow, double=True), DataBusLine]
drawElements(elmlist, cols=2)
Single-Terminal
---------------
Single terminal elements are drawn about a single point, and do not move the current drawing position.
Power and Ground
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Ground, GroundSignal, GroundChassis,
Vss, Vdd]
drawElements(elmlist, dx=4, cols=3)
Antennas
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Antenna, AntennaLoop, AntennaLoop2]
drawElements(elmlist, dx=4, cols=3)
Connection Dots
^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Dot, partial(Dot, open=True), DotDotDot,
Arrowhead, NoConnect]
drawElements(elmlist, dx=4, cols=3)
Switches
--------
The standard toggle switch is listed with other two-terminal elements above.
Other switch configurations are shown here.
Single-pole double-throw
^^^^^^^^^^^^^^^^^^^^^^^^
Two options for SPDT switches can be also be drawn with arrows by
adding `action='open'` or `action='close'` parameters.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchSpdt, SwitchSpdt2,
partial(SwitchSpdt, action='open'), partial(SwitchSpdt2, action='open'),
partial(SwitchSpdt, action='close'), partial(SwitchSpdt2, action='close')]
drawElements(elmlist, cols=2, dx=9, dy=3, lblofst=(.5, 0))
Double-pole
^^^^^^^^^^^
DPST and DPDT switches have a `link` parameter for disabling the dotted line
lnking the poles.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchDpst, SwitchDpdt,
partial(SwitchDpst, link=False),
partial(SwitchDpdt, link=False)]
drawElements(elmlist, cols=2, dx=8, dy=4, lblofst=(.7, 0))
Rotary Switch
^^^^^^^^^^^^^
The rotary switch :py:class:`schemdraw.elements.switches.SwitchRotary` takes several parameters, with `n` being the number of contacts and other parameters defining the contact placement.
.. jupyter-execute::
:hide-code:
(SwitchRotary(n=6).label('SwitchRotary(n=6)', ofst=(0,0.5))
.label('P', loc='P', halign='right', color='blue', fontsize=9, ofst=(-.2, 0))
.label('T1', loc='T1', color='blue', fontsize=9, ofst=(0, -.2))
.label('T2', loc='T2', color='blue', fontsize=9, ofst=(0, -.5))
.label('T3', loc='T3', color='blue', fontsize=9, ofst=(.2, 0))
.label('T4', loc='T4', color='blue', fontsize=9, ofst=(.2, 0))
.label('T5', loc='T5', color='blue', fontsize=9, ofst=(0, .2))
.label('T6', loc='T6', color='blue', fontsize=9, ofst=(0, .2))
)
DIP Switch
^^^^^^^^^^
A set of switches in a dual-inline package, where can show each switch flipped up or down.
See :py:class:`schemdraw.elements.switches.SwitchDIP` for options.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (elm.SwitchDIP().label('SwitchDIP', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11))
d += (elm.SwitchDIP(pattern=(0, 0, 1)).label('SwitchDIP(pattern=(0, 0, 1))', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11).at((5, 0)))
d.draw()
Audio Elements
--------------
Speakers, Microphones, Jacks
.. jupyter-execute::
:hide-code:
elmlist = [Speaker, Mic]
drawElements(elmlist, cols=2, dy=5, dx=5, lblofst=[.7, 0])
.. jupyter-execute::
:hide-code:
elmlist = [AudioJack, partial(AudioJack, ring=True),
partial(AudioJack, switch=True),
partial(AudioJack, switch=True, ring=True, ringswitch=True)]
drawElements(elmlist, cols=1, dy=3, lblofst=[1.7, 0])
Labels
------
The `Label` element can be used to add a label anywhere.
The `Gap` is like an "invisible" element, useful for marking the voltage between output terminals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += elm.Line().right().length(1)
d += elm.Dot(open=True)
d += elm.Gap().down().label(['+','Gap','–'])
d += elm.Dot(open=True)
d += elm.Line().left().length(1)
d += elm.Label(label='Label').at([3.5, -.5])
d += elm.Tag().right().at([5, -.5]).label('Tag')
d.draw()
Operational Amplifiers
----------------------
The :py:class:`schemdraw.elements.opamp.Opamp` element defines several anchors for various inputs, including voltage supplies and offset nulls. Optional leads can be added using the `leads` parameter, with anchors exteded to the ends of the leads.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (op := elm.Opamp().label('Opamp', ofst=.6))
d += elm.Dot().at(op.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op.n1a).color('blue').label('n1a', loc='bottom')
d += (op2 := elm.Opamp(sign=False).at([5, 0]).right().label('Opamp(sign=False)', ofst=.6))
d += elm.Dot().at(op2.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op2.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op2.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op2.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op2.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op2.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op2.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op2.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op2.n1a).color('blue').label('n1a', loc='bottom')
d += (op:=elm.Opamp(leads=True).at([10, 0]).right().label('Opamp(leads=True)', ofst=.6)
.label('in1', loc='in1', halign='right', color='blue')
.label('in2', loc='in2', halign='right', color='blue')
.label('out', loc='out', halign='left', color='blue'))
d += elm.Dot().at(op.in1).color('blue')
d += elm.Dot().at(op.in2).color('blue')
d += elm.Dot().at(op.out).color('blue')
d.draw()
Transistors
-----------
Bipolar Junction Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Bjt, BjtNpn, BjtPnp,
partial(Bjt, circle=True),
partial(BjtNpn, circle=True), partial(BjtPnp, circle=True),
BjtPnp2c, partial(BjtPnp2c, circle=True),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=(0, .2))
Field-Effect Transistors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [NFet, PFet, partial(NFet, bulk=True), partial(PFet, bulk=True),
JFet, JFetN, JFetP, partial(JFetN, circle=True), partial(JFetP, circle=True),
AnalogNFet, AnalogPFet, AnalogBiasedFet, partial(AnalogNFet, bulk=True),
partial(AnalogPFet, bulk=True), partial(AnalogBiasedFet, bulk=True),
partial(AnalogNFet, arrow=False), partial(AnalogPFet, arrow=False),
partial(AnalogBiasedFet, arrow=False), partial(AnalogNFet, offset_gate=False),
partial(AnalogPFet, offset_gate=False), partial(AnalogBiasedFet, offset_gate=False),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=[0, -.8])
"Two-Terminal" Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^
Another set of transistor elements subclass :py:class:`schemdraw.elements.Element2Term` so they
have emitter and collector (or source and drain) leads extended to the desired length.
These can be easier to place centered between endpoints, for example.
.. jupyter-execute::
:hide-code:
elmlist = [BjtNpn2, BjtPnp2, BjtPnp2c2, NFet2, PFet2, JFetN2, JFetP2]
drawElements(elmlist, dx=6.5, dy=3)
Two-ports
-----------
Twoport elements share the interface defined by :py:class:`schemdraw.elements.twoports.ElementTwoport`, providing a set of anchors and various styling options. The terminals and box can be enabled or disabled using the `terminals` and `box` arguments. In addition, the `boxfill`, `boxlw`, and `boxls` provide the option to style the outline separately from other elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (tp := elm.TwoPort().label('TwoPort', ofst=.6)).anchor('center')
d += elm.Dot().at(tp.in_p).color('blue').label('in_p', loc='left', valign='center')
d += elm.Dot().at(tp.in_n).color('blue').label('in_n', loc='left', valign='center')
d += elm.Dot().at(tp.out_p).color('blue').label('out_p', loc='right', valign='center')
d += elm.Dot().at(tp.out_n).color('blue').label('in_n', loc='right', valign='center')
d += elm.Dot().at(tp.center).color('blue').label('center', loc='top')
d += (tp := elm.TwoPort(terminals=False, boxlw=3).label('TwoPort(terminals=False, boxlw=3)', ofst=.6)).anchor('center').at([7,0])
d.draw()
Generic
^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [TwoPort, partial(TwoPort, reverse_output=True), partial(TwoPort, arrow=False),
partial(TwoPort, sign=False)]
drawElements(elmlist, dy=3, cols=2)
Transactors (ideal amplifiers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like the generic twoport, the transactors provide the option to reverse the direction of the output or current using the `reverse_output` argument.
.. jupyter-execute::
:hide-code:
elmlist = [VoltageTransactor, TransimpedanceTransactor,TransadmittanceTransactor, CurrentTransactor]
drawElements(elmlist, dy=3, cols=2)
Pathological
^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullor, VMCMPair]
drawElements(elmlist, dy=3, cols=2)
Custom
^^^^^^
The :py:class:`schemdraw.elements.twoports.ElementTwoport` class can be used to define custom twoports by specifying an `input_element` and `output_element`. The `bpadx`, `bpady`, `minw`, `unit`, `width` can be used to tune the horizontal and vertical padding, minimum width of the elements, length of components, and width of the twoport respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.ElementTwoport(input_element=elm.Inductor2(),
output_element=elm.SwitchReed(),
unit=2.5, width=2.5).anchor('center')
d += elm.ElementTwoport(input_element=elm.Lamp(),
output_element=elm.Photodiode().reverse().flip(),
width=3).anchor('center').at([7,0])
.. jupyter-execute::
:hide-code:
d.draw()
Cables
------
:py:class:`schemdraw.elements.cables.Coax` and :py:class:`schemdraw.elements.cables.Triax` cables are 2-Terminal elements that can be made with several options and anchors.
Coax parameters include length, radius, and leadlen for setting the distance between leads and the shell.
Triax parameters include length, radiusinner, radiusouter, leadlen, and shieldofststart for offseting the outer shield from the inner guard.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10)
d += elm.Coax().label('Coax')
d += elm.Coax(length=4, radius=.5).label('Coax(length=5, radius=.5)')
d += (C := elm.Coax().at([0, -3]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'lft', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Triax().at([0, -7]).right().label('Triax')
d += elm.Triax(length=4, radiusinner=.5).label('Triax(length=5, radiusinner=.5)')
d += (C := elm.Triax().at([1, -10]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'left', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Line().theta(45).at(C.guardend_top).length(1).label('guardend_top', 'rgt', halign='left').color('blue')
d += elm.Line().theta(-45).at(C.guardend).length(1).label('guardend', 'rgt', halign='left').color('blue')
d += elm.Line().theta(135).at(C.guardstart_top).length(.3).label('guardstart_top', 'left', halign='right').color('blue')
d += elm.Line().theta(-145).at(C.guardstart).length(.5).label('guardstart', 'left', halign='right').color('blue')
d.draw()
.. jupyter-execute::
:hide-code:
elmlist = [CoaxConnect]
drawElements(elmlist, dx=1, dy=1, lblofst=[.5, 0])
Transformers
------------
The :py:class:`schemdraw.elements.xform.Transformer` element is used to create various transformers.
Anchors `p1`, `p2`, `s1`, and `s2` are defined for all transformers.
Other anchors can be created using the `taps` method to add tap locations to
either side.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.Transformer().label('Transformer'))
d.add(elm.Transformer(loop=True).at([5, 0]).label('Transformer(loop=True)'))
d.here = [0, -4]
d.draw()
Here is a transformers with anchor "B" added using the `tap` method. Note the tap by itself
does not draw anything, but defines a named anchor to connect to.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=12)
x = d.add(elm.Transformer(t1=4, t2=8)
.tap(name='B', pos=3, side='secondary'))
d += elm.Line().at(x.s1).length(d.unit/4).label('s1', 'rgt').color('blue')
d += elm.Line().at(x.s2).length(d.unit/4).label('s2', 'rgt').color('blue')
d += elm.Line().at(x.p1).length(d.unit/4).left().label('p1', 'lft').color('blue')
d += elm.Line().at(x.p2).length(d.unit/4).left().label('p2', 'lft').color('blue')
d += elm.Line().at(x.B).length(d.unit/4).right().label('B', 'rgt').color('blue')
| 0.875973 | 0.407805 |
Digital Logic
=============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Logic gates can be drawn by importing the :py:mod:`schemdraw.logic.logic` module:
.. code-block:: python
from schemdraw import logic
Logic gates are shown below. Gates define anchors for `out` and `in1`, `in2`, etc.
`Buf`, `Not`, and `NotNot`, and their Schmitt-trigger counterparts, are two-terminal elements that extend leads.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
d += getattr(logic, e)().right().at((x,y)).label(e, loc='right', ofst=.2, halign='left', valign='center')
return d
elms = ['And', 'Nand', 'Or', 'Nor', 'Xor', 'Xnor',
'Buf', 'Not', 'NotNot', 'Tgate', 'Tristate',
'Schmitt', 'SchmittNot', 'SchmittAnd', 'SchmittNand']
drawElements(elms, dx=6)
Gates with more than 2 inputs can be created using the `inputs` parameter. With more than 3 inputs, the back of the gate will extend up and down.
.. jupyter-execute::
logic.Nand(inputs=3)
.. jupyter-execute::
logic.Nor(inputs=4)
Finally, any input can be pre-inverted (active low) using the `inputnots` keyword with a list of input numbers, starting at 1 to match the anchor names, on which to add an invert bubble.
.. jupyter-execute::
logic.Nand(inputs=3, inputnots=[1])
Logic Parser
------------
Logic trees can also be created from a string logic expression such as "(a and b) or c" using using :py:func:`schemdraw.parsing.logic_parser.logicparse`.
The logic parser requires the `pyparsing <https://pyparsing-docs.readthedocs.io/en/latest/>`_ module.
Examples:
.. jupyter-execute::
from schemdraw.parsing import logicparse
logicparse('not ((w and x) or (y and z))', outlabel='$\overline{Q}$')
.. jupyter-execute::
logicparse('((a xor b) and (b or c) and (d or e)) or ((w and x) or (y and z))')
Logicparse understands spelled-out logic functions "and", "or", "nand", "nor", "xor", "xnor", "not", but also common symbols such as "+", "&", "⊕" representing "or", "and", and "xor".
.. jupyter-execute::
logicparse('¬ (a ∨ b) & (c ⊻ d)') # Using symbols
Use the `gateH` and `gateW` parameters to adjust how gates line up:
.. jupyter-execute::
logicparse('(not a) and b or c', gateH=.5)
Truth Tables
------------
Simple tables can be drawn using the :py:class:`schemdraw.logic.table.Table` class. This class is included in the logic module as its primary purpose was for drawing logical truth tables.
The tables are defined using typical Markdown syntax. The `colfmt` parameter works like the LaTeX tabular environment parameter for defining lines to draw between table columns: "cc|c" draws three centered columns, with a vertical line before the last column.
Each column must be specified with a 'c', 'r', or 'l' for center, right, or left justification
Two pipes (`||`), or a double pipe character (`ǁ`) draw a double bar between columns.
Row lines are added to the table string itself, with either `---` or `===` in the row.
.. jupyter-execute::
table = '''
A | B | C
---|---|---
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
'''
logic.Table(table, colfmt='cc||c')
Karnaugh Maps
-------------
Karnaugh Maps, or K-Maps, are useful for simplifying a logical truth table into the smallest number of gates. Schemdraw can draw K-Maps, with 2, 3, or 4 input variables, using the :py:class:`schemdraw.logic.kmap.Kmap` class.
.. jupyter-execute::
logic.Kmap(names='ABCD')
The `names` parameter must be a string with 2, 3, or 4 characters, each defining the name of one input variable.
The `truthtable` parameter contains a list of tuples defining the logic values to display in the map. The first `len(names)` elements are 0's and 1's defining the position of the cell, and the last element is the string to display in that cell.
The `default` parameter is a string to show in each cell of the K-Map when that cell is undefined in the `truthtable`.
For example, this 2x2 K-Map has a '1' in the 01 position, and 0's elsewhere:
.. jupyter-execute::
logic.Kmap(names='AB', truthtable=[('01', '1')])
K-Maps are typically used by grouping sets of 1's together. These groupings can be drawn using the `groups` parameter. The keys of the `groups` dictionary define which cells to group together, and the values of the dictionary define style parameters for the circle around the group.
Each key must be a string of length `len(names)`, with either a `0`, `1`, or `.` in each position. As an example, with `names='ABCD'`, a group key of `"1..."` will place a circle around all cells where A=1. Or `".00."` draws a circle around all cells where B and C are both 0. Groups will automatically "wrap" around the edges.
Parameters of the style dictionary include `color`, `fill`, `lw`, and `ls`.
.. jupyter-execute::
logic.Kmap(names='ABCD',
truthtable=[('1100', '1'),
('1101', '1'),
('1111', '1'),
('1110', '1'),
('0101', '1'),
('0111', 'X'),
('1101', '1'),
('1111', '1'),
('0000', '1'),
('1000', '1')],
groups={'11..': {'color': 'red', 'fill': '#ff000033'},
'.1.1': {'color': 'blue', 'fill': '#0000ff33'},
'.000': {'color': 'green', 'fill': '#00ff0033'}})
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/logic-checkpoint.rst
|
logic-checkpoint.rst
|
Digital Logic
=============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Logic gates can be drawn by importing the :py:mod:`schemdraw.logic.logic` module:
.. code-block:: python
from schemdraw import logic
Logic gates are shown below. Gates define anchors for `out` and `in1`, `in2`, etc.
`Buf`, `Not`, and `NotNot`, and their Schmitt-trigger counterparts, are two-terminal elements that extend leads.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
d += getattr(logic, e)().right().at((x,y)).label(e, loc='right', ofst=.2, halign='left', valign='center')
return d
elms = ['And', 'Nand', 'Or', 'Nor', 'Xor', 'Xnor',
'Buf', 'Not', 'NotNot', 'Tgate', 'Tristate',
'Schmitt', 'SchmittNot', 'SchmittAnd', 'SchmittNand']
drawElements(elms, dx=6)
Gates with more than 2 inputs can be created using the `inputs` parameter. With more than 3 inputs, the back of the gate will extend up and down.
.. jupyter-execute::
logic.Nand(inputs=3)
.. jupyter-execute::
logic.Nor(inputs=4)
Finally, any input can be pre-inverted (active low) using the `inputnots` keyword with a list of input numbers, starting at 1 to match the anchor names, on which to add an invert bubble.
.. jupyter-execute::
logic.Nand(inputs=3, inputnots=[1])
Logic Parser
------------
Logic trees can also be created from a string logic expression such as "(a and b) or c" using using :py:func:`schemdraw.parsing.logic_parser.logicparse`.
The logic parser requires the `pyparsing <https://pyparsing-docs.readthedocs.io/en/latest/>`_ module.
Examples:
.. jupyter-execute::
from schemdraw.parsing import logicparse
logicparse('not ((w and x) or (y and z))', outlabel='$\overline{Q}$')
.. jupyter-execute::
logicparse('((a xor b) and (b or c) and (d or e)) or ((w and x) or (y and z))')
Logicparse understands spelled-out logic functions "and", "or", "nand", "nor", "xor", "xnor", "not", but also common symbols such as "+", "&", "⊕" representing "or", "and", and "xor".
.. jupyter-execute::
logicparse('¬ (a ∨ b) & (c ⊻ d)') # Using symbols
Use the `gateH` and `gateW` parameters to adjust how gates line up:
.. jupyter-execute::
logicparse('(not a) and b or c', gateH=.5)
Truth Tables
------------
Simple tables can be drawn using the :py:class:`schemdraw.logic.table.Table` class. This class is included in the logic module as its primary purpose was for drawing logical truth tables.
The tables are defined using typical Markdown syntax. The `colfmt` parameter works like the LaTeX tabular environment parameter for defining lines to draw between table columns: "cc|c" draws three centered columns, with a vertical line before the last column.
Each column must be specified with a 'c', 'r', or 'l' for center, right, or left justification
Two pipes (`||`), or a double pipe character (`ǁ`) draw a double bar between columns.
Row lines are added to the table string itself, with either `---` or `===` in the row.
.. jupyter-execute::
table = '''
A | B | C
---|---|---
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
'''
logic.Table(table, colfmt='cc||c')
Karnaugh Maps
-------------
Karnaugh Maps, or K-Maps, are useful for simplifying a logical truth table into the smallest number of gates. Schemdraw can draw K-Maps, with 2, 3, or 4 input variables, using the :py:class:`schemdraw.logic.kmap.Kmap` class.
.. jupyter-execute::
logic.Kmap(names='ABCD')
The `names` parameter must be a string with 2, 3, or 4 characters, each defining the name of one input variable.
The `truthtable` parameter contains a list of tuples defining the logic values to display in the map. The first `len(names)` elements are 0's and 1's defining the position of the cell, and the last element is the string to display in that cell.
The `default` parameter is a string to show in each cell of the K-Map when that cell is undefined in the `truthtable`.
For example, this 2x2 K-Map has a '1' in the 01 position, and 0's elsewhere:
.. jupyter-execute::
logic.Kmap(names='AB', truthtable=[('01', '1')])
K-Maps are typically used by grouping sets of 1's together. These groupings can be drawn using the `groups` parameter. The keys of the `groups` dictionary define which cells to group together, and the values of the dictionary define style parameters for the circle around the group.
Each key must be a string of length `len(names)`, with either a `0`, `1`, or `.` in each position. As an example, with `names='ABCD'`, a group key of `"1..."` will place a circle around all cells where A=1. Or `".00."` draws a circle around all cells where B and C are both 0. Groups will automatically "wrap" around the edges.
Parameters of the style dictionary include `color`, `fill`, `lw`, and `ls`.
.. jupyter-execute::
logic.Kmap(names='ABCD',
truthtable=[('1100', '1'),
('1101', '1'),
('1111', '1'),
('1110', '1'),
('0101', '1'),
('0111', 'X'),
('1101', '1'),
('1111', '1'),
('0000', '1'),
('1000', '1')],
groups={'11..': {'color': 'red', 'fill': '#ff000033'},
'.1.1': {'color': 'blue', 'fill': '#0000ff33'},
'.000': {'color': 'green', 'fill': '#00ff0033'}})
| 0.887296 | 0.711681 |
.. _electrical:
Basic Elements
==============
See :ref:`elecelements` for complete class definitions for these elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
from schemdraw.elements import *
def drawElements(elmlist, cols=3, dx=8, dy=2, lblofst=None, lblloc='rgt'):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
if isinstance(e, str):
name = e
e = getattr(elm, e)
else:
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc=lblloc, halign='left', valign='center', ofst=lblofst)
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['center', 'start', 'end', 'istart', 'iend',
'isource', 'idrain', 'iemitter', 'icollector', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Two-terminal
------------
Two-terminal devices subclass :py:class:`schemdraw.elements.Element2Term`, and have leads that will be extended to make the element the desired length depending on the arguments.
All two-terminal elements define `start`, `end`, and `center` anchors for placing, and a few define other anchors as shown in blue in the tables below.
Some elements have optional parameters, shown in parenthesis in the table below.
.. _styledelements:
Styled Elements
^^^^^^^^^^^^^^^
These elements change based on IEEE/U.S. vs IEC/European style configured by :py:meth:`schemdraw.elements.style`.
Selectable elements, such as `Resistor`, point to either `ResistorIEEE` or `ResistorIEC`, for example.
IEEE Style
**********
IEEE style, common in the U.S., is the default, or it can be configured using
.. code-block:: python
elm.style(elm.STYLE_IEEE)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEEE)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
IEC/European Style
******************
IEC style can be enabled using
.. code-block:: python
elm.style(elm.STYLE_IEC)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEC)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
Resistors
^^^^^^^^^
Both styles of resistors are always available using these classes.
.. jupyter-execute::
:hide-code:
elmlist = [ResistorIEEE, ResistorIEC, ResistorVarIEEE, ResistorVarIEC, Rshunt, PotentiometerIEEE,
PotentiometerIEC, FuseUS, FuseIEEE, FuseIEC]
drawElements(elmlist, cols=2)
Capacitors and Inductors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Capacitor, partial(Capacitor, polar=True),
Capacitor2, partial(Capacitor2, polar=True),
CapacitorVar, CapacitorTrim, Inductor, Inductor2,
partial(Inductor2, loops=2)]
drawElements(elmlist, cols=2)
Diodes
^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Diode,
partial(Diode, fill=True), Schottky, DiodeTunnel, DiodeShockley,
Zener, Varactor, LED, LED2, Photodiode, Diac, Triac, SCR]
drawElements(elmlist, cols=2)
Pathological
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullator, Norator, CurrentMirror, VoltageMirror]
drawElements(elmlist, cols=2)
Miscellaneous
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Breaker, Crystal, CPE, Josephson, Motor, Lamp, Neon, Thermistor, Memristor, Memristor2, Jack, Plug]
drawElements(elmlist, cols=2)
Sources and Meters
^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Source, SourceV, SourceI, SourceSin, SourcePulse,
SourceSquare, SourceTriangle,
SourceRamp, SourceControlled,
SourceControlledV, SourceControlledI, BatteryCell,
Battery, MeterV, MeterA, MeterI, MeterOhm,
Solar]
drawElements(elmlist, cols=2)
Switches
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Button, partial(Button, nc=True),
Switch, partial(Switch, action='open'),
partial(Switch, action='close'),
SwitchReed]
drawElements(elmlist, cols=2)
Lines and Arrows
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Line, Arrow, partial(Arrow, double=True), DataBusLine]
drawElements(elmlist, cols=2)
Single-Terminal
---------------
Single terminal elements are drawn about a single point, and do not move the current drawing position.
Power and Ground
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Ground, GroundSignal, GroundChassis,
Vss, Vdd]
drawElements(elmlist, dx=4, cols=3)
Antennas
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Antenna, AntennaLoop, AntennaLoop2]
drawElements(elmlist, dx=4, cols=3)
Connection Dots
^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Dot, partial(Dot, open=True), DotDotDot,
Arrowhead, NoConnect]
drawElements(elmlist, dx=4, cols=3)
Switches
--------
The standard toggle switch is listed with other two-terminal elements above.
Other switch configurations are shown here.
Single-pole double-throw
^^^^^^^^^^^^^^^^^^^^^^^^
Two options for SPDT switches can be also be drawn with arrows by
adding `action='open'` or `action='close'` parameters.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchSpdt, SwitchSpdt2,
partial(SwitchSpdt, action='open'), partial(SwitchSpdt2, action='open'),
partial(SwitchSpdt, action='close'), partial(SwitchSpdt2, action='close')]
drawElements(elmlist, cols=2, dx=9, dy=3, lblofst=(.5, 0))
Double-pole
^^^^^^^^^^^
DPST and DPDT switches have a `link` parameter for disabling the dotted line
lnking the poles.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchDpst, SwitchDpdt,
partial(SwitchDpst, link=False),
partial(SwitchDpdt, link=False)]
drawElements(elmlist, cols=2, dx=8, dy=4, lblofst=(.7, 0))
Rotary Switch
^^^^^^^^^^^^^
The rotary switch :py:class:`schemdraw.elements.switches.SwitchRotary` takes several parameters, with `n` being the number of contacts and other parameters defining the contact placement.
.. jupyter-execute::
:hide-code:
(SwitchRotary(n=6).label('SwitchRotary(n=6)', ofst=(0,0.5))
.label('P', loc='P', halign='right', color='blue', fontsize=9, ofst=(-.2, 0))
.label('T1', loc='T1', color='blue', fontsize=9, ofst=(0, -.2))
.label('T2', loc='T2', color='blue', fontsize=9, ofst=(0, -.5))
.label('T3', loc='T3', color='blue', fontsize=9, ofst=(.2, 0))
.label('T4', loc='T4', color='blue', fontsize=9, ofst=(.2, 0))
.label('T5', loc='T5', color='blue', fontsize=9, ofst=(0, .2))
.label('T6', loc='T6', color='blue', fontsize=9, ofst=(0, .2))
)
DIP Switch
^^^^^^^^^^
A set of switches in a dual-inline package, where can show each switch flipped up or down.
See :py:class:`schemdraw.elements.switches.SwitchDIP` for options.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (elm.SwitchDIP().label('SwitchDIP', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11))
d += (elm.SwitchDIP(pattern=(0, 0, 1)).label('SwitchDIP(pattern=(0, 0, 1))', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11).at((5, 0)))
d.draw()
Audio Elements
--------------
Speakers, Microphones, Jacks
.. jupyter-execute::
:hide-code:
elmlist = [Speaker, Mic]
drawElements(elmlist, cols=2, dy=5, dx=5, lblofst=[.7, 0])
.. jupyter-execute::
:hide-code:
elmlist = [AudioJack, partial(AudioJack, ring=True),
partial(AudioJack, switch=True),
partial(AudioJack, switch=True, ring=True, ringswitch=True)]
drawElements(elmlist, cols=1, dy=3, lblofst=[1.7, 0])
Labels
------
The `Label` element can be used to add a label anywhere.
The `Gap` is like an "invisible" element, useful for marking the voltage between output terminals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += elm.Line().right().length(1)
d += elm.Dot(open=True)
d += elm.Gap().down().label(['+','Gap','–'])
d += elm.Dot(open=True)
d += elm.Line().left().length(1)
d += elm.Label(label='Label').at([3.5, -.5])
d += elm.Tag().right().at([5, -.5]).label('Tag')
d.draw()
Operational Amplifiers
----------------------
The :py:class:`schemdraw.elements.opamp.Opamp` element defines several anchors for various inputs, including voltage supplies and offset nulls. Optional leads can be added using the `leads` parameter, with anchors exteded to the ends of the leads.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (op := elm.Opamp().label('Opamp', ofst=.6))
d += elm.Dot().at(op.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op.n1a).color('blue').label('n1a', loc='bottom')
d += (op2 := elm.Opamp(sign=False).at([5, 0]).right().label('Opamp(sign=False)', ofst=.6))
d += elm.Dot().at(op2.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op2.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op2.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op2.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op2.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op2.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op2.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op2.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op2.n1a).color('blue').label('n1a', loc='bottom')
d += (op:=elm.Opamp(leads=True).at([10, 0]).right().label('Opamp(leads=True)', ofst=.6)
.label('in1', loc='in1', halign='right', color='blue')
.label('in2', loc='in2', halign='right', color='blue')
.label('out', loc='out', halign='left', color='blue'))
d += elm.Dot().at(op.in1).color('blue')
d += elm.Dot().at(op.in2).color('blue')
d += elm.Dot().at(op.out).color('blue')
d.draw()
Transistors
-----------
Bipolar Junction Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Bjt, BjtNpn, BjtPnp,
partial(Bjt, circle=True),
partial(BjtNpn, circle=True), partial(BjtPnp, circle=True),
BjtPnp2c, partial(BjtPnp2c, circle=True),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=(0, .2))
Field-Effect Transistors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [NFet, PFet, partial(NFet, bulk=True), partial(PFet, bulk=True),
JFet, JFetN, JFetP, partial(JFetN, circle=True), partial(JFetP, circle=True),
AnalogNFet, AnalogPFet, AnalogBiasedFet, partial(AnalogNFet, bulk=True),
partial(AnalogPFet, bulk=True), partial(AnalogBiasedFet, bulk=True),
partial(AnalogNFet, arrow=False), partial(AnalogPFet, arrow=False),
partial(AnalogBiasedFet, arrow=False), partial(AnalogNFet, offset_gate=False),
partial(AnalogPFet, offset_gate=False), partial(AnalogBiasedFet, offset_gate=False),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=[0, -.8])
"Two-Terminal" Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^
Another set of transistor elements subclass :py:class:`schemdraw.elements.Element2Term` so they
have emitter and collector (or source and drain) leads extended to the desired length.
These can be easier to place centered between endpoints, for example.
.. jupyter-execute::
:hide-code:
elmlist = [BjtNpn2, BjtPnp2, BjtPnp2c2, NFet2, PFet2, JFetN2, JFetP2]
drawElements(elmlist, dx=6.5, dy=3)
Two-ports
-----------
Twoport elements share the interface defined by :py:class:`schemdraw.elements.twoports.ElementTwoport`, providing a set of anchors and various styling options. The terminals and box can be enabled or disabled using the `terminals` and `box` arguments. In addition, the `boxfill`, `boxlw`, and `boxls` provide the option to style the outline separately from other elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (tp := elm.TwoPort().label('TwoPort', ofst=.6)).anchor('center')
d += elm.Dot().at(tp.in_p).color('blue').label('in_p', loc='left', valign='center')
d += elm.Dot().at(tp.in_n).color('blue').label('in_n', loc='left', valign='center')
d += elm.Dot().at(tp.out_p).color('blue').label('out_p', loc='right', valign='center')
d += elm.Dot().at(tp.out_n).color('blue').label('in_n', loc='right', valign='center')
d += elm.Dot().at(tp.center).color('blue').label('center', loc='top')
d += (tp := elm.TwoPort(terminals=False, boxlw=3).label('TwoPort(terminals=False, boxlw=3)', ofst=.6)).anchor('center').at([7,0])
d.draw()
Generic
^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [TwoPort, partial(TwoPort, reverse_output=True), partial(TwoPort, arrow=False),
partial(TwoPort, sign=False)]
drawElements(elmlist, dy=3, cols=2)
Transactors (ideal amplifiers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like the generic twoport, the transactors provide the option to reverse the direction of the output or current using the `reverse_output` argument.
.. jupyter-execute::
:hide-code:
elmlist = [VoltageTransactor, TransimpedanceTransactor,TransadmittanceTransactor, CurrentTransactor]
drawElements(elmlist, dy=3, cols=2)
Pathological
^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullor, VMCMPair]
drawElements(elmlist, dy=3, cols=2)
Custom
^^^^^^
The :py:class:`schemdraw.elements.twoports.ElementTwoport` class can be used to define custom twoports by specifying an `input_element` and `output_element`. The `bpadx`, `bpady`, `minw`, `unit`, `width` can be used to tune the horizontal and vertical padding, minimum width of the elements, length of components, and width of the twoport respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.ElementTwoport(input_element=elm.Inductor2(),
output_element=elm.SwitchReed(),
unit=2.5, width=2.5).anchor('center')
d += elm.ElementTwoport(input_element=elm.Lamp(),
output_element=elm.Photodiode().reverse().flip(),
width=3).anchor('center').at([7,0])
.. jupyter-execute::
:hide-code:
d.draw()
Cables
------
:py:class:`schemdraw.elements.cables.Coax` and :py:class:`schemdraw.elements.cables.Triax` cables are 2-Terminal elements that can be made with several options and anchors.
Coax parameters include length, radius, and leadlen for setting the distance between leads and the shell.
Triax parameters include length, radiusinner, radiusouter, leadlen, and shieldofststart for offseting the outer shield from the inner guard.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10)
d += elm.Coax().label('Coax')
d += elm.Coax(length=4, radius=.5).label('Coax(length=5, radius=.5)')
d += (C := elm.Coax().at([0, -3]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'lft', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Triax().at([0, -7]).right().label('Triax')
d += elm.Triax(length=4, radiusinner=.5).label('Triax(length=5, radiusinner=.5)')
d += (C := elm.Triax().at([1, -10]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'left', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Line().theta(45).at(C.guardend_top).length(1).label('guardend_top', 'rgt', halign='left').color('blue')
d += elm.Line().theta(-45).at(C.guardend).length(1).label('guardend', 'rgt', halign='left').color('blue')
d += elm.Line().theta(135).at(C.guardstart_top).length(.3).label('guardstart_top', 'left', halign='right').color('blue')
d += elm.Line().theta(-145).at(C.guardstart).length(.5).label('guardstart', 'left', halign='right').color('blue')
d.draw()
.. jupyter-execute::
:hide-code:
elmlist = [CoaxConnect]
drawElements(elmlist, dx=1, dy=1, lblofst=[.5, 0])
Transformers
------------
The :py:class:`schemdraw.elements.xform.Transformer` element is used to create various transformers.
Anchors `p1`, `p2`, `s1`, and `s2` are defined for all transformers.
Other anchors can be created using the `taps` method to add tap locations to
either side.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.Transformer().label('Transformer'))
d.add(elm.Transformer(loop=True).at([5, 0]).label('Transformer(loop=True)'))
d.here = [0, -4]
d.draw()
Here is a transformers with anchor "B" added using the `tap` method. Note the tap by itself
does not draw anything, but defines a named anchor to connect to.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=12)
x = d.add(elm.Transformer(t1=4, t2=8)
.tap(name='B', pos=3, side='secondary'))
d += elm.Line().at(x.s1).length(d.unit/4).label('s1', 'rgt').color('blue')
d += elm.Line().at(x.s2).length(d.unit/4).label('s2', 'rgt').color('blue')
d += elm.Line().at(x.p1).length(d.unit/4).left().label('p1', 'lft').color('blue')
d += elm.Line().at(x.p2).length(d.unit/4).left().label('p2', 'lft').color('blue')
d += elm.Line().at(x.B).length(d.unit/4).right().label('B', 'rgt').color('blue')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/electrical-checkpoint.rst
|
electrical-checkpoint.rst
|
.. _electrical:
Basic Elements
==============
See :ref:`elecelements` for complete class definitions for these elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
from schemdraw.elements import *
def drawElements(elmlist, cols=3, dx=8, dy=2, lblofst=None, lblloc='rgt'):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
if isinstance(e, str):
name = e
e = getattr(elm, e)
else:
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc=lblloc, halign='left', valign='center', ofst=lblofst)
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['center', 'start', 'end', 'istart', 'iend',
'isource', 'idrain', 'iemitter', 'icollector', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Two-terminal
------------
Two-terminal devices subclass :py:class:`schemdraw.elements.Element2Term`, and have leads that will be extended to make the element the desired length depending on the arguments.
All two-terminal elements define `start`, `end`, and `center` anchors for placing, and a few define other anchors as shown in blue in the tables below.
Some elements have optional parameters, shown in parenthesis in the table below.
.. _styledelements:
Styled Elements
^^^^^^^^^^^^^^^
These elements change based on IEEE/U.S. vs IEC/European style configured by :py:meth:`schemdraw.elements.style`.
Selectable elements, such as `Resistor`, point to either `ResistorIEEE` or `ResistorIEC`, for example.
IEEE Style
**********
IEEE style, common in the U.S., is the default, or it can be configured using
.. code-block:: python
elm.style(elm.STYLE_IEEE)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEEE)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
IEC/European Style
******************
IEC style can be enabled using
.. code-block:: python
elm.style(elm.STYLE_IEC)
.. jupyter-execute::
:hide-code:
elm.style(elm.STYLE_IEC)
elmlist = ['Resistor', 'ResistorVar', 'ResistorVar', 'Potentiometer', 'Photoresistor', 'Fuse']
drawElements(elmlist, cols=2)
Resistors
^^^^^^^^^
Both styles of resistors are always available using these classes.
.. jupyter-execute::
:hide-code:
elmlist = [ResistorIEEE, ResistorIEC, ResistorVarIEEE, ResistorVarIEC, Rshunt, PotentiometerIEEE,
PotentiometerIEC, FuseUS, FuseIEEE, FuseIEC]
drawElements(elmlist, cols=2)
Capacitors and Inductors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Capacitor, partial(Capacitor, polar=True),
Capacitor2, partial(Capacitor2, polar=True),
CapacitorVar, CapacitorTrim, Inductor, Inductor2,
partial(Inductor2, loops=2)]
drawElements(elmlist, cols=2)
Diodes
^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Diode,
partial(Diode, fill=True), Schottky, DiodeTunnel, DiodeShockley,
Zener, Varactor, LED, LED2, Photodiode, Diac, Triac, SCR]
drawElements(elmlist, cols=2)
Pathological
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullator, Norator, CurrentMirror, VoltageMirror]
drawElements(elmlist, cols=2)
Miscellaneous
^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Breaker, Crystal, CPE, Josephson, Motor, Lamp, Neon, Thermistor, Memristor, Memristor2, Jack, Plug]
drawElements(elmlist, cols=2)
Sources and Meters
^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Source, SourceV, SourceI, SourceSin, SourcePulse,
SourceSquare, SourceTriangle,
SourceRamp, SourceControlled,
SourceControlledV, SourceControlledI, BatteryCell,
Battery, MeterV, MeterA, MeterI, MeterOhm,
Solar]
drawElements(elmlist, cols=2)
Switches
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Button, partial(Button, nc=True),
Switch, partial(Switch, action='open'),
partial(Switch, action='close'),
SwitchReed]
drawElements(elmlist, cols=2)
Lines and Arrows
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Line, Arrow, partial(Arrow, double=True), DataBusLine]
drawElements(elmlist, cols=2)
Single-Terminal
---------------
Single terminal elements are drawn about a single point, and do not move the current drawing position.
Power and Ground
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Ground, GroundSignal, GroundChassis,
Vss, Vdd]
drawElements(elmlist, dx=4, cols=3)
Antennas
^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Antenna, AntennaLoop, AntennaLoop2]
drawElements(elmlist, dx=4, cols=3)
Connection Dots
^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
# One-terminal, don't move position
elmlist = [Dot, partial(Dot, open=True), DotDotDot,
Arrowhead, NoConnect]
drawElements(elmlist, dx=4, cols=3)
Switches
--------
The standard toggle switch is listed with other two-terminal elements above.
Other switch configurations are shown here.
Single-pole double-throw
^^^^^^^^^^^^^^^^^^^^^^^^
Two options for SPDT switches can be also be drawn with arrows by
adding `action='open'` or `action='close'` parameters.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchSpdt, SwitchSpdt2,
partial(SwitchSpdt, action='open'), partial(SwitchSpdt2, action='open'),
partial(SwitchSpdt, action='close'), partial(SwitchSpdt2, action='close')]
drawElements(elmlist, cols=2, dx=9, dy=3, lblofst=(.5, 0))
Double-pole
^^^^^^^^^^^
DPST and DPDT switches have a `link` parameter for disabling the dotted line
lnking the poles.
.. jupyter-execute::
:hide-code:
elmlist = [SwitchDpst, SwitchDpdt,
partial(SwitchDpst, link=False),
partial(SwitchDpdt, link=False)]
drawElements(elmlist, cols=2, dx=8, dy=4, lblofst=(.7, 0))
Rotary Switch
^^^^^^^^^^^^^
The rotary switch :py:class:`schemdraw.elements.switches.SwitchRotary` takes several parameters, with `n` being the number of contacts and other parameters defining the contact placement.
.. jupyter-execute::
:hide-code:
(SwitchRotary(n=6).label('SwitchRotary(n=6)', ofst=(0,0.5))
.label('P', loc='P', halign='right', color='blue', fontsize=9, ofst=(-.2, 0))
.label('T1', loc='T1', color='blue', fontsize=9, ofst=(0, -.2))
.label('T2', loc='T2', color='blue', fontsize=9, ofst=(0, -.5))
.label('T3', loc='T3', color='blue', fontsize=9, ofst=(.2, 0))
.label('T4', loc='T4', color='blue', fontsize=9, ofst=(.2, 0))
.label('T5', loc='T5', color='blue', fontsize=9, ofst=(0, .2))
.label('T6', loc='T6', color='blue', fontsize=9, ofst=(0, .2))
)
DIP Switch
^^^^^^^^^^
A set of switches in a dual-inline package, where can show each switch flipped up or down.
See :py:class:`schemdraw.elements.switches.SwitchDIP` for options.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (elm.SwitchDIP().label('SwitchDIP', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11))
d += (elm.SwitchDIP(pattern=(0, 0, 1)).label('SwitchDIP(pattern=(0, 0, 1))', 'right')
.label('a1', color='blue', loc='a1', valign='top', fontsize=11)
.label('a2', color='blue', loc='a2', valign='top', fontsize=11)
.label('a3', color='blue', loc='a3', valign='top', fontsize=11)
.label('b1', color='blue', loc='b1', valign='bottom', fontsize=11)
.label('b2', color='blue', loc='b2', valign='bottom', fontsize=11)
.label('b3', color='blue', loc='b3', valign='bottom', fontsize=11).at((5, 0)))
d.draw()
Audio Elements
--------------
Speakers, Microphones, Jacks
.. jupyter-execute::
:hide-code:
elmlist = [Speaker, Mic]
drawElements(elmlist, cols=2, dy=5, dx=5, lblofst=[.7, 0])
.. jupyter-execute::
:hide-code:
elmlist = [AudioJack, partial(AudioJack, ring=True),
partial(AudioJack, switch=True),
partial(AudioJack, switch=True, ring=True, ringswitch=True)]
drawElements(elmlist, cols=1, dy=3, lblofst=[1.7, 0])
Labels
------
The `Label` element can be used to add a label anywhere.
The `Gap` is like an "invisible" element, useful for marking the voltage between output terminals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += elm.Line().right().length(1)
d += elm.Dot(open=True)
d += elm.Gap().down().label(['+','Gap','–'])
d += elm.Dot(open=True)
d += elm.Line().left().length(1)
d += elm.Label(label='Label').at([3.5, -.5])
d += elm.Tag().right().at([5, -.5]).label('Tag')
d.draw()
Operational Amplifiers
----------------------
The :py:class:`schemdraw.elements.opamp.Opamp` element defines several anchors for various inputs, including voltage supplies and offset nulls. Optional leads can be added using the `leads` parameter, with anchors exteded to the ends of the leads.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (op := elm.Opamp().label('Opamp', ofst=.6))
d += elm.Dot().at(op.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op.n1a).color('blue').label('n1a', loc='bottom')
d += (op2 := elm.Opamp(sign=False).at([5, 0]).right().label('Opamp(sign=False)', ofst=.6))
d += elm.Dot().at(op2.in1).color('blue').label('in1', loc='left', valign='center')
d += elm.Dot().at(op2.in2).color('blue').label('in2', loc='left', valign='center')
d += elm.Dot().at(op2.out).color('blue').label('out', loc='right', valign='center')
d += elm.Dot().at(op2.vd).color('blue').label('vd', loc='top')
d += elm.Dot().at(op2.vs).color('blue').label('vs', loc='bottom')
d += elm.Dot().at(op2.n1).color('blue').label('n1', loc='bottom')
d += elm.Dot().at(op2.n2).color('blue').label('n2', loc='top')
d += elm.Dot().at(op2.n2a).color('blue').label('n2a', loc='top')
d += elm.Dot().at(op2.n1a).color('blue').label('n1a', loc='bottom')
d += (op:=elm.Opamp(leads=True).at([10, 0]).right().label('Opamp(leads=True)', ofst=.6)
.label('in1', loc='in1', halign='right', color='blue')
.label('in2', loc='in2', halign='right', color='blue')
.label('out', loc='out', halign='left', color='blue'))
d += elm.Dot().at(op.in1).color('blue')
d += elm.Dot().at(op.in2).color('blue')
d += elm.Dot().at(op.out).color('blue')
d.draw()
Transistors
-----------
Bipolar Junction Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Bjt, BjtNpn, BjtPnp,
partial(Bjt, circle=True),
partial(BjtNpn, circle=True), partial(BjtPnp, circle=True),
BjtPnp2c, partial(BjtPnp2c, circle=True),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=(0, .2))
Field-Effect Transistors
^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [NFet, PFet, partial(NFet, bulk=True), partial(PFet, bulk=True),
JFet, JFetN, JFetP, partial(JFetN, circle=True), partial(JFetP, circle=True),
AnalogNFet, AnalogPFet, AnalogBiasedFet, partial(AnalogNFet, bulk=True),
partial(AnalogPFet, bulk=True), partial(AnalogBiasedFet, bulk=True),
partial(AnalogNFet, arrow=False), partial(AnalogPFet, arrow=False),
partial(AnalogBiasedFet, arrow=False), partial(AnalogNFet, offset_gate=False),
partial(AnalogPFet, offset_gate=False), partial(AnalogBiasedFet, offset_gate=False),]
drawElements(elmlist, dx=6.5, dy=3, lblofst=[0, -.8])
"Two-Terminal" Transistors
^^^^^^^^^^^^^^^^^^^^^^^^^^
Another set of transistor elements subclass :py:class:`schemdraw.elements.Element2Term` so they
have emitter and collector (or source and drain) leads extended to the desired length.
These can be easier to place centered between endpoints, for example.
.. jupyter-execute::
:hide-code:
elmlist = [BjtNpn2, BjtPnp2, BjtPnp2c2, NFet2, PFet2, JFetN2, JFetP2]
drawElements(elmlist, dx=6.5, dy=3)
Two-ports
-----------
Twoport elements share the interface defined by :py:class:`schemdraw.elements.twoports.ElementTwoport`, providing a set of anchors and various styling options. The terminals and box can be enabled or disabled using the `terminals` and `box` arguments. In addition, the `boxfill`, `boxlw`, and `boxls` provide the option to style the outline separately from other elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d += (tp := elm.TwoPort().label('TwoPort', ofst=.6)).anchor('center')
d += elm.Dot().at(tp.in_p).color('blue').label('in_p', loc='left', valign='center')
d += elm.Dot().at(tp.in_n).color('blue').label('in_n', loc='left', valign='center')
d += elm.Dot().at(tp.out_p).color('blue').label('out_p', loc='right', valign='center')
d += elm.Dot().at(tp.out_n).color('blue').label('in_n', loc='right', valign='center')
d += elm.Dot().at(tp.center).color('blue').label('center', loc='top')
d += (tp := elm.TwoPort(terminals=False, boxlw=3).label('TwoPort(terminals=False, boxlw=3)', ofst=.6)).anchor('center').at([7,0])
d.draw()
Generic
^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [TwoPort, partial(TwoPort, reverse_output=True), partial(TwoPort, arrow=False),
partial(TwoPort, sign=False)]
drawElements(elmlist, dy=3, cols=2)
Transactors (ideal amplifiers)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like the generic twoport, the transactors provide the option to reverse the direction of the output or current using the `reverse_output` argument.
.. jupyter-execute::
:hide-code:
elmlist = [VoltageTransactor, TransimpedanceTransactor,TransadmittanceTransactor, CurrentTransactor]
drawElements(elmlist, dy=3, cols=2)
Pathological
^^^^^^^^^^^^
.. jupyter-execute::
:hide-code:
elmlist = [Nullor, VMCMPair]
drawElements(elmlist, dy=3, cols=2)
Custom
^^^^^^
The :py:class:`schemdraw.elements.twoports.ElementTwoport` class can be used to define custom twoports by specifying an `input_element` and `output_element`. The `bpadx`, `bpady`, `minw`, `unit`, `width` can be used to tune the horizontal and vertical padding, minimum width of the elements, length of components, and width of the twoport respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.ElementTwoport(input_element=elm.Inductor2(),
output_element=elm.SwitchReed(),
unit=2.5, width=2.5).anchor('center')
d += elm.ElementTwoport(input_element=elm.Lamp(),
output_element=elm.Photodiode().reverse().flip(),
width=3).anchor('center').at([7,0])
.. jupyter-execute::
:hide-code:
d.draw()
Cables
------
:py:class:`schemdraw.elements.cables.Coax` and :py:class:`schemdraw.elements.cables.Triax` cables are 2-Terminal elements that can be made with several options and anchors.
Coax parameters include length, radius, and leadlen for setting the distance between leads and the shell.
Triax parameters include length, radiusinner, radiusouter, leadlen, and shieldofststart for offseting the outer shield from the inner guard.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10)
d += elm.Coax().label('Coax')
d += elm.Coax(length=4, radius=.5).label('Coax(length=5, radius=.5)')
d += (C := elm.Coax().at([0, -3]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'lft', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'lft', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Triax().at([0, -7]).right().label('Triax')
d += elm.Triax(length=4, radiusinner=.5).label('Triax(length=5, radiusinner=.5)')
d += (C := elm.Triax().at([1, -10]).length(5))
d += elm.Line().down().at(C.shieldstart).length(.2).label('shieldstart', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldcenter).length(.6).label('shieldcenter', 'left', halign='right').color('blue')
d += elm.Line().down().at(C.shieldend).length(1).label('shieldend', 'left', halign='center').color('blue')
d += elm.Line().up().at(C.shieldstart_top).length(.2).label('shieldstart_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldcenter_top).length(.6).label('shieldcenter_top', 'rgt', halign='right').color('blue')
d += elm.Line().up().at(C.shieldend_top).length(1).label('shieldend_top', 'rgt', halign='center').color('blue')
d += elm.Line().theta(45).at(C.guardend_top).length(1).label('guardend_top', 'rgt', halign='left').color('blue')
d += elm.Line().theta(-45).at(C.guardend).length(1).label('guardend', 'rgt', halign='left').color('blue')
d += elm.Line().theta(135).at(C.guardstart_top).length(.3).label('guardstart_top', 'left', halign='right').color('blue')
d += elm.Line().theta(-145).at(C.guardstart).length(.5).label('guardstart', 'left', halign='right').color('blue')
d.draw()
.. jupyter-execute::
:hide-code:
elmlist = [CoaxConnect]
drawElements(elmlist, dx=1, dy=1, lblofst=[.5, 0])
Transformers
------------
The :py:class:`schemdraw.elements.xform.Transformer` element is used to create various transformers.
Anchors `p1`, `p2`, `s1`, and `s2` are defined for all transformers.
Other anchors can be created using the `taps` method to add tap locations to
either side.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.Transformer().label('Transformer'))
d.add(elm.Transformer(loop=True).at([5, 0]).label('Transformer(loop=True)'))
d.here = [0, -4]
d.draw()
Here is a transformers with anchor "B" added using the `tap` method. Note the tap by itself
does not draw anything, but defines a named anchor to connect to.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=12)
x = d.add(elm.Transformer(t1=4, t2=8)
.tap(name='B', pos=3, side='secondary'))
d += elm.Line().at(x.s1).length(d.unit/4).label('s1', 'rgt').color('blue')
d += elm.Line().at(x.s2).length(d.unit/4).label('s2', 'rgt').color('blue')
d += elm.Line().at(x.p1).length(d.unit/4).left().label('p1', 'lft').color('blue')
d += elm.Line().at(x.p2).length(d.unit/4).left().label('p2', 'lft').color('blue')
d += elm.Line().at(x.B).length(d.unit/4).right().label('B', 'rgt').color('blue')
| 0.875973 | 0.407805 |
Compound Elements
=================
Several compound elements defined based on other basic elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['start', 'end', 'center', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Optocoupler
-----------
:py:class:`schemdraw.elements.compound.Optocoupler` can be drawn with or without a base contact.
.. jupyter-execute::
:hide-code:
drawElements([elm.Optocoupler, partial(elm.Optocoupler, base=True)])
Relay
-----
:py:class:`schemdraw.elements.compound.Relay` can be drawn with different options for switches and inductor solenoids.
.. jupyter-execute::
:hide-code:
drawElements([elm.Relay,
partial(elm.Relay, switch='spdt'),
partial(elm.Relay, switch='dpst'),
partial(elm.Relay, switch='dpdt')],
cols=2, dy=3)
Wheatstone
----------
:py:class:`schemdraw.elements.compound.Wheatstone` can be drawn with or without the output voltage taps.
The `labels` argument specifies a list of labels for each resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Wheatstone()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Wheatstone', loc='S', ofst=(0, -.5)))
d += (W:=elm.Wheatstone(vout=True).at((7, 0))
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('vo1', loc='vo1', color='blue', fontsize=10)
.label('vo2', loc='vo2', color='blue', fontsize=10)
.label('Wheatstone(vout=True)', loc='S', ofst=(0, -.5)))
d.draw()
Rectifier
----------
:py:class:`schemdraw.elements.compound.Rectifier` draws four diodes at 45 degree angles.
The `labels` argument specifies a list of labels for each diode.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Rectifier()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Rectifier', loc='S', ofst=(0, -.5)))
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/compound-checkpoint.rst
|
compound-checkpoint.rst
|
Compound Elements
=================
Several compound elements defined based on other basic elements.
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import elements as elm
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
newelm = e().right().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
if len(newelm.anchors) > 0:
for aname, apos in newelm.anchors.items():
if aname not in ['start', 'end', 'center', 'xy']:
newelm.label(aname, loc=aname, color='blue', fontsize=10)
d += newelm
return d
Optocoupler
-----------
:py:class:`schemdraw.elements.compound.Optocoupler` can be drawn with or without a base contact.
.. jupyter-execute::
:hide-code:
drawElements([elm.Optocoupler, partial(elm.Optocoupler, base=True)])
Relay
-----
:py:class:`schemdraw.elements.compound.Relay` can be drawn with different options for switches and inductor solenoids.
.. jupyter-execute::
:hide-code:
drawElements([elm.Relay,
partial(elm.Relay, switch='spdt'),
partial(elm.Relay, switch='dpst'),
partial(elm.Relay, switch='dpdt')],
cols=2, dy=3)
Wheatstone
----------
:py:class:`schemdraw.elements.compound.Wheatstone` can be drawn with or without the output voltage taps.
The `labels` argument specifies a list of labels for each resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Wheatstone()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Wheatstone', loc='S', ofst=(0, -.5)))
d += (W:=elm.Wheatstone(vout=True).at((7, 0))
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('vo1', loc='vo1', color='blue', fontsize=10)
.label('vo2', loc='vo2', color='blue', fontsize=10)
.label('Wheatstone(vout=True)', loc='S', ofst=(0, -.5)))
d.draw()
Rectifier
----------
:py:class:`schemdraw.elements.compound.Rectifier` draws four diodes at 45 degree angles.
The `labels` argument specifies a list of labels for each diode.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (W:=elm.Rectifier()
.label('N', loc='N', color='blue', fontsize=10)
.label('S', loc='S', color='blue', fontsize=10)
.label('E', loc='E', color='blue', fontsize=10)
.label('W', loc='W', color='blue', fontsize=10)
.label('Rectifier', loc='S', ofst=(0, -.5)))
d.draw()
| 0.808181 | 0.350171 |
Connectors
==========
.. jupyter-execute::
:hide-code:
from functools import partial
import schemdraw
from schemdraw import elements as elm
All connectors are defined with a default pin spacing of 0.6, matching the default pin spacing of the :py:class:`schemdraw.elements.intcircuits.Ic` class, for easy connection of multiple signals.
Headers
^^^^^^^
A :py:class:`schemdraw.elements.connectors.Header` is a generic Header block with any number of rows and columns. It can have round, square, or screw-head connection points.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
return d
elmlist = [elm.Header,
partial(elm.Header, shownumber=True),
partial(elm.Header, rows=3, cols=2),
partial(elm.Header, style='square'),
partial(elm.Header, style='screw'),
partial(elm.Header, pinsleft=['A', 'B', 'C', 'D'], pinalignleft='center')]
drawElements(elmlist, cols=2, dy=4)
Header pins are given anchor names `pin1`, `pin2`, etc.
Pin number labels and anchor names can be ordered left-to-right (`lr`), up-to-down (`ud`), or counterclockwise (`ccw`) like a traditional IC, depending on the `numbering` argument.
The `flip` argument can be set True to put pin 1 at the bottom.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d.add(elm.Header(shownumber=True, cols=2, numbering='lr', label="lr"))
d.add(elm.Header(at=[3, 0], shownumber=True, cols=2, numbering='ud', label="ud"))
d.add(elm.Header(at=[6, 0], shownumber=True, cols=2, numbering='ccw', label="ccw"))
d.draw()
A :py:class:`schemdraw.elements.connectors.Jumper` element is also defined, as a simple rectangle, for easy placing onto a header.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
J = d.add(elm.Header(cols=2, style='square'))
d.add(elm.Jumper().at(J.pin3).fill('lightgray'))
.. jupyter-execute::
:hide-code:
d.draw()
D-Sub Connectors
^^^^^^^^^^^^^^^^
Both :py:class:`schemdraw.elements.connectors.DB9` and :py:class:`schemdraw.elements.connectors.DB25` subminiature connectors are defined, with anchors `pin1` through `pin9` or `pin25`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.DB9(label='DB9'))
d.add(elm.DB9(at=[3, 0], number=True, label='DB9(number=True)'))
d.add(elm.DB25(at=[6, 0], label='DB25'))
d.draw()
Multiple Lines
^^^^^^^^^^^^^^
The :py:class:`schemdraw.elements.connectors.RightLines` and :py:class:`schemdraw.elements.connectors.OrthoLines` elements are useful for connecting multiple pins of an integrated circuit or header all at once. Both need an `at` and `to` location specified, along with the `n` parameter for setting the number of lines to draw. Use RightLines when the Headers are perpindicular to each other.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='t', slot='1/4'),
elm.IcPin(name='B', side='t', slot='2/4'),
elm.IcPin(name='C', side='t', slot='3/4'),
elm.IcPin(name='D', side='t', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((5,4)))
d.add(elm.RightLines(n=4).at(D2.pin1).to(D1.D).label('RightLines'))
.. jupyter-execute::
:hide-code:
d.draw()
OrthoLines draw a z-shaped orthogonal connection. Use OrthoLines when the Headers are parallel but vertically offset.
Use the `xstart` parameter, between 0 and 1, to specify the position where the first OrthoLine turns vertical.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='r', slot='1/4'),
elm.IcPin(name='B', side='r', slot='2/4'),
elm.IcPin(name='C', side='r', slot='3/4'),
elm.IcPin(name='D', side='r', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((7, -3)))
d.add(elm.OrthoLines(n=4).at(D1.D).to(D2.pin1).label('OrthoLines'))
.. jupyter-execute::
:hide-code:
d.draw()
Data Busses
^^^^^^^^^^^
Sometimes, multiple I/O pins to an integrated circuit are lumped together into a data bus.
The connections to a bus can be drawn using the :py:class:`schemdraw.elements.connectors.BusConnect` element, which takes `n` the number of data lines and an argument.
:py:class:`schemdraw.elements.connectors.BusLine` is simply a wider line used to extend the full bus to its destination.
BusConnect elements define anchors `start`, `end` on the endpoints of the wide bus line, and `pin1`, `pin2`, etc. for the individual signals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 2-4
J = d.add(elm.Header(rows=6))
B = d.add(elm.BusConnect(n=6).at(J.pin1))
d.add(elm.BusLine().down().at(B.end).length(3))
B2 = d.add(elm.BusConnect(n=6).anchor('start').reverse())
d.add(elm.Header(rows=6).at(B2.pin1).anchor('pin1'))
.. jupyter-execute::
:hide-code:
d.draw()
Outlets
^^^^^^^
Power outlets and plugs are drawn using `OutletX` classes, with international styles A through L. Each has anchors
`hot`, `neutral`, and `ground` (if applicable).
The `plug` parameter fills the prongs to indicate a plug versus an outlet.
.. jupyter-execute::
:hide-code:
outlets = [elm.OutletA, elm.OutletB, elm.OutletC, elm.OutletD, elm.OutletE, elm.OutletF,
elm.OutletG, elm.OutletH, elm.OutletI, elm.OutletJ, elm.OutletK, elm.OutletL]
d = schemdraw.Drawing()
for i, outlet in enumerate(outlets):
K = outlet().label(outlet.__name__, loc='top')
d.here = (i % 4) * 4, (i//4) * -4
d += K
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/connectors-checkpoint.rst
|
connectors-checkpoint.rst
|
Connectors
==========
.. jupyter-execute::
:hide-code:
from functools import partial
import schemdraw
from schemdraw import elements as elm
All connectors are defined with a default pin spacing of 0.6, matching the default pin spacing of the :py:class:`schemdraw.elements.intcircuits.Ic` class, for easy connection of multiple signals.
Headers
^^^^^^^
A :py:class:`schemdraw.elements.connectors.Header` is a generic Header block with any number of rows and columns. It can have round, square, or screw-head connection points.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().at((x, y)).label(name, loc='rgt', halign='left', valign='center')
return d
elmlist = [elm.Header,
partial(elm.Header, shownumber=True),
partial(elm.Header, rows=3, cols=2),
partial(elm.Header, style='square'),
partial(elm.Header, style='screw'),
partial(elm.Header, pinsleft=['A', 'B', 'C', 'D'], pinalignleft='center')]
drawElements(elmlist, cols=2, dy=4)
Header pins are given anchor names `pin1`, `pin2`, etc.
Pin number labels and anchor names can be ordered left-to-right (`lr`), up-to-down (`ud`), or counterclockwise (`ccw`) like a traditional IC, depending on the `numbering` argument.
The `flip` argument can be set True to put pin 1 at the bottom.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d.add(elm.Header(shownumber=True, cols=2, numbering='lr', label="lr"))
d.add(elm.Header(at=[3, 0], shownumber=True, cols=2, numbering='ud', label="ud"))
d.add(elm.Header(at=[6, 0], shownumber=True, cols=2, numbering='ccw', label="ccw"))
d.draw()
A :py:class:`schemdraw.elements.connectors.Jumper` element is also defined, as a simple rectangle, for easy placing onto a header.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
J = d.add(elm.Header(cols=2, style='square'))
d.add(elm.Jumper().at(J.pin3).fill('lightgray'))
.. jupyter-execute::
:hide-code:
d.draw()
D-Sub Connectors
^^^^^^^^^^^^^^^^
Both :py:class:`schemdraw.elements.connectors.DB9` and :py:class:`schemdraw.elements.connectors.DB25` subminiature connectors are defined, with anchors `pin1` through `pin9` or `pin25`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
d.add(elm.DB9(label='DB9'))
d.add(elm.DB9(at=[3, 0], number=True, label='DB9(number=True)'))
d.add(elm.DB25(at=[6, 0], label='DB25'))
d.draw()
Multiple Lines
^^^^^^^^^^^^^^
The :py:class:`schemdraw.elements.connectors.RightLines` and :py:class:`schemdraw.elements.connectors.OrthoLines` elements are useful for connecting multiple pins of an integrated circuit or header all at once. Both need an `at` and `to` location specified, along with the `n` parameter for setting the number of lines to draw. Use RightLines when the Headers are perpindicular to each other.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='t', slot='1/4'),
elm.IcPin(name='B', side='t', slot='2/4'),
elm.IcPin(name='C', side='t', slot='3/4'),
elm.IcPin(name='D', side='t', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((5,4)))
d.add(elm.RightLines(n=4).at(D2.pin1).to(D1.D).label('RightLines'))
.. jupyter-execute::
:hide-code:
d.draw()
OrthoLines draw a z-shaped orthogonal connection. Use OrthoLines when the Headers are parallel but vertically offset.
Use the `xstart` parameter, between 0 and 1, to specify the position where the first OrthoLine turns vertical.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12)
.. jupyter-execute::
:hide-output:
:emphasize-lines: 6
D1 = d.add(elm.Ic(pins=[elm.IcPin(name='A', side='r', slot='1/4'),
elm.IcPin(name='B', side='r', slot='2/4'),
elm.IcPin(name='C', side='r', slot='3/4'),
elm.IcPin(name='D', side='r', slot='4/4')]))
D2 = d.add(elm.Header(rows=4).at((7, -3)))
d.add(elm.OrthoLines(n=4).at(D1.D).to(D2.pin1).label('OrthoLines'))
.. jupyter-execute::
:hide-code:
d.draw()
Data Busses
^^^^^^^^^^^
Sometimes, multiple I/O pins to an integrated circuit are lumped together into a data bus.
The connections to a bus can be drawn using the :py:class:`schemdraw.elements.connectors.BusConnect` element, which takes `n` the number of data lines and an argument.
:py:class:`schemdraw.elements.connectors.BusLine` is simply a wider line used to extend the full bus to its destination.
BusConnect elements define anchors `start`, `end` on the endpoints of the wide bus line, and `pin1`, `pin2`, etc. for the individual signals.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 2-4
J = d.add(elm.Header(rows=6))
B = d.add(elm.BusConnect(n=6).at(J.pin1))
d.add(elm.BusLine().down().at(B.end).length(3))
B2 = d.add(elm.BusConnect(n=6).anchor('start').reverse())
d.add(elm.Header(rows=6).at(B2.pin1).anchor('pin1'))
.. jupyter-execute::
:hide-code:
d.draw()
Outlets
^^^^^^^
Power outlets and plugs are drawn using `OutletX` classes, with international styles A through L. Each has anchors
`hot`, `neutral`, and `ground` (if applicable).
The `plug` parameter fills the prongs to indicate a plug versus an outlet.
.. jupyter-execute::
:hide-code:
outlets = [elm.OutletA, elm.OutletB, elm.OutletC, elm.OutletD, elm.OutletE, elm.OutletF,
elm.OutletG, elm.OutletH, elm.OutletI, elm.OutletJ, elm.OutletK, elm.OutletL]
d = schemdraw.Drawing()
for i, outlet in enumerate(outlets):
K = outlet().label(outlet.__name__, loc='top')
d.here = (i % 4) * 4, (i//4) * -4
d += K
d.draw()
| 0.881621 | 0.463809 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _integratedcircuit:
Integrated Circuits
-------------------
The :py:class:`schemdraw.elements.intcircuits.Ic` class is used to make integrated circuits, multiplexers, and other black box elements. The :py:class:`schemdraw.elements.intcircuits.IcPin` class is used to define each input/output pin before adding it to the Ic.
All pins will be given an anchor name of `inXY` where X is the side (L, R, T, B), and Y is the pin number along that side.
Pins also define anchors based on the `name` parameter.
If the `anchorname` parameter is provided for the pin, this name will be used, so that the pin `name` can be any string even if it cannot be used as a Python variable name.
Here, a J-K flip flop, as part of an HC7476 integrated circuit, is drawn with input names and pin numbers.
.. jupyter-execute::
JK = elm.Ic(pins=[elm.IcPin(name='>', pin='1', side='left'),
elm.IcPin(name='K', pin='16', side='left'),
elm.IcPin(name='J', pin='4', side='left'),
elm.IcPin(name='$\overline{Q}$', pin='14', side='right', anchorname='QBAR'),
elm.IcPin(name='Q', pin='15', side='right')],
edgepadW = .5, # Make it a bit wider
pinspacing=1).label('HC7476', 'bottom', fontsize=12)
display(JK)
Notice the use of `$\overline{Q}$` to acheive the label on the inverting output.
The anchor positions can be accessed using attributes, such as `JK.Q` for the
non-inverting output. However, inverting output is named `$\overline{Q}`, which is
not accessible using the typical dot notation. It could be accessed using
`getattr(JK, '$\overline{Q}$')`, but to avoid this an alternative anchorname of `QBAR`
was defined.
Multiplexers
^^^^^^^^^^^^
Multiplexers and demultiplexers are drawn with the :py:class:`schemdraw.elements.intcircuits.Multiplexer` class which wraps the Ic class.
.. jupyter-execute::
elm.Multiplexer(
pins=[elm.IcPin(name='C', side='L'),
elm.IcPin(name='B', side='L'),
elm.IcPin(name='A', side='L'),
elm.IcPin(name='Q', side='R'),
elm.IcPin(name='T', side='B', invert=True)],
edgepadH=-.5)
See the :ref:`gallery` for more examples.
Seven-Segment Display
^^^^^^^^^^^^^^^^^^^^^
A seven-segment display, in :py:class:`schemdraw.elements.intcircuits.SevenSegment`, provides a single digit
with several options including decimal point and common anode or common cathode mode. The :py:meth:`schemdraw.elements.intcircuits.sevensegdigit` method generates a list of Segment objects that can be used to add
a digit to another element, for example to make a multi-digit display.
.. jupyter-execute::
:hide-code:
elm.SevenSegment()
DIP Integrated Circuits
^^^^^^^^^^^^^^^^^^^^^^^
Integrated circuits can be drawn in dual-inline package style with :py:class:`schemdraw.elements.intcircuits.IcDIP`.
Anchors allow connecting elements externally to show the IC in a circuit, or interanally to show the internal
configuration of the IC (see :ref:`dip741`.)
.. jupyter-execute::
:hide-code:
elm.IcDIP()
Predefined ICs
^^^^^^^^^^^^^^
A few common integrated circuits are predefined as shown below.
.. jupyter-execute::
:hide-code:
elm.Ic555().label('Ic555()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.VoltageRegulator().label('VoltageRegulator()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.DFlipFlop().label('DFlipFlop()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.JKFlipFlop().label('JKFlipFlop()', 'bottom')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/intcircuits-checkpoint.rst
|
intcircuits-checkpoint.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _integratedcircuit:
Integrated Circuits
-------------------
The :py:class:`schemdraw.elements.intcircuits.Ic` class is used to make integrated circuits, multiplexers, and other black box elements. The :py:class:`schemdraw.elements.intcircuits.IcPin` class is used to define each input/output pin before adding it to the Ic.
All pins will be given an anchor name of `inXY` where X is the side (L, R, T, B), and Y is the pin number along that side.
Pins also define anchors based on the `name` parameter.
If the `anchorname` parameter is provided for the pin, this name will be used, so that the pin `name` can be any string even if it cannot be used as a Python variable name.
Here, a J-K flip flop, as part of an HC7476 integrated circuit, is drawn with input names and pin numbers.
.. jupyter-execute::
JK = elm.Ic(pins=[elm.IcPin(name='>', pin='1', side='left'),
elm.IcPin(name='K', pin='16', side='left'),
elm.IcPin(name='J', pin='4', side='left'),
elm.IcPin(name='$\overline{Q}$', pin='14', side='right', anchorname='QBAR'),
elm.IcPin(name='Q', pin='15', side='right')],
edgepadW = .5, # Make it a bit wider
pinspacing=1).label('HC7476', 'bottom', fontsize=12)
display(JK)
Notice the use of `$\overline{Q}$` to acheive the label on the inverting output.
The anchor positions can be accessed using attributes, such as `JK.Q` for the
non-inverting output. However, inverting output is named `$\overline{Q}`, which is
not accessible using the typical dot notation. It could be accessed using
`getattr(JK, '$\overline{Q}$')`, but to avoid this an alternative anchorname of `QBAR`
was defined.
Multiplexers
^^^^^^^^^^^^
Multiplexers and demultiplexers are drawn with the :py:class:`schemdraw.elements.intcircuits.Multiplexer` class which wraps the Ic class.
.. jupyter-execute::
elm.Multiplexer(
pins=[elm.IcPin(name='C', side='L'),
elm.IcPin(name='B', side='L'),
elm.IcPin(name='A', side='L'),
elm.IcPin(name='Q', side='R'),
elm.IcPin(name='T', side='B', invert=True)],
edgepadH=-.5)
See the :ref:`gallery` for more examples.
Seven-Segment Display
^^^^^^^^^^^^^^^^^^^^^
A seven-segment display, in :py:class:`schemdraw.elements.intcircuits.SevenSegment`, provides a single digit
with several options including decimal point and common anode or common cathode mode. The :py:meth:`schemdraw.elements.intcircuits.sevensegdigit` method generates a list of Segment objects that can be used to add
a digit to another element, for example to make a multi-digit display.
.. jupyter-execute::
:hide-code:
elm.SevenSegment()
DIP Integrated Circuits
^^^^^^^^^^^^^^^^^^^^^^^
Integrated circuits can be drawn in dual-inline package style with :py:class:`schemdraw.elements.intcircuits.IcDIP`.
Anchors allow connecting elements externally to show the IC in a circuit, or interanally to show the internal
configuration of the IC (see :ref:`dip741`.)
.. jupyter-execute::
:hide-code:
elm.IcDIP()
Predefined ICs
^^^^^^^^^^^^^^
A few common integrated circuits are predefined as shown below.
.. jupyter-execute::
:hide-code:
elm.Ic555().label('Ic555()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.VoltageRegulator().label('VoltageRegulator()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.DFlipFlop().label('DFlipFlop()', 'bottom')
.. jupyter-execute::
:hide-code:
elm.JKFlipFlop().label('JKFlipFlop()', 'bottom')
| 0.891501 | 0.58747 |
Timing Diagrams
===============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Digital timing diagrams may be drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` Element in the :py:mod:`schemdraw.logic` module.
Timing diagrams are set up using the WaveJSON syntax used by the `WaveDrom <https://wavedrom.com/>`_ JavaScript application.
.. code-block:: python
from schemdraw import logic
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}]})
The input is a dictionary containing a `signal`, which is a list of each wave to show in the diagram. Each signal is a dictionary which must contain a `name` and `wave`.
An empty dictionary leaves a blank row in the diagram.
Every character in the `wave` specifies the state of the wave for one period. A dot `.` means the previous state is repeated.
Wave characters 'n' and 'p' specify clock signals, and 'N', and 'P' draw clocks with arrows.
'1' and '0' are used to define high and low signals. '2' draws a data block, and '3' through '9' draw data filled with a color. 'x' draws a don't-care or undefined data state.
Data blocks can be labeled by adding a 'data' item to the wave's dictionary.
This example shows the different wave sections:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clock n', 'wave': 'n......'},
{'name': 'clock p', 'wave': 'p......'},
{'name': 'clock N', 'wave': 'N......'},
{'name': 'clock P', 'wave': 'P......'},
{},
{'name': '1s and 0s', 'wave': '0.1.01.'},
{'name': 'data', 'wave': '2..=.2.'}, # '=' is the same as '2'
{'name': 'data named', 'wave': '3.4.6..', 'data': ['A', 'B', 'C']},
{'name': 'dont care', 'wave': 'xx..x..'},
{},
{'name': 'high z', 'wave': 'z.10.z.'},
{'name': 'pull up/down', 'wave': '0u..d.1'},
]})
Putting them together in a more realistic example:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}]})
The `config` key, containing a dictionary with `hscale`, may be used to change the width of one period in the diagram:
.. jupyter-execute::
:emphasize-lines: 6
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}],
'config': {'hscale': 2}})
Signals may also be nested into different groups:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': ['Group',
['Set 1',
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}],
['Set 2',
{'name': 'C', 'wave': '0..1..01.'},
{'name': 'D', 'wave': '101..0...'}]
]})
Using the `node` key in a waveform, plus the `edge` key in the top-level dictionary, provides a way to show transitions between different edges.
.. jupyter-execute::
:emphasize-lines: 5
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.', 'node': '...a.....'},
{'name': 'B', 'wave': '101..0...', 'node': '.....b...'}],
'edge': ['a~>b']
})
Each string in the edge list must start and end with a node name (single character). The characters between them define the type of connecting line: '-' for straight line, '~' for curve, '-\|' for orthogonal lines, and \< or \> to include arrowheads.
For example, 'a-~>b' draws a curved line with arrowhead between nodes a and b.
Using JSON
----------
Because the examples from WaveDrom use JavaScript and JSON, they sometimes cannot be directly pasted into Python as dictionaries.
The :py:meth:`schemdraw.logic.timing.TimingDiagram.from_json` method allows input of the WaveJSON as a string pasted directly from the Javascript/JSON examples without modification.
Notice lack of quoting on the dictionary keys, requiring the `from_json` method to parse the string.
.. jupyter-execute::
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "P......" },
{ name: "bus", wave: "x.==.=x", data: ["head", "body", "tail", "data"] },
{ name: "wire", wave: "0.1..0." }
]}''')
Schemdraw's Customizations
--------------------------
Schemdraw extends the WaveJSON spcification with a few additional options.
Style Parameters
****************
Each wave dictionary accpets a `color` and `lw` parameter.
The rise/fall time for transitions can be set using the `risetime` parameter to TimingDiagram. Other colors and font sizes may be speficied using keyword arguments to :py:class:`schemdraw.logic.timing.TimingDiagram`.
Asynchronous Signals
********************
WaveDrom does not have a means for defining asynchronous signals - all waves must transition on period boundaries. Schemdraw adds asyncrhonous signals using the `async` parameter, as a list of period multiples for each transition in the wave. Note the beginning and end time of the wave must also be specified, so the length of the `async` list must be one more than the length of `wave`.
.. jupyter-execute::
:emphasize-lines: 4
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'n......'},
{'name': 'B', 'wave': '010', 'async': [0, 1.6, 4.25, 7]}]},
risetime=.03)
Extended Edge Notation
**********************
Additional "edge" string notations are allowed for more complex labeling of edge timings, including asynchronous start and end times and labels just above or below a wave.
Each edge string using this syntax takes the form
.. code-block:: python
'[WaveNum:Period]<->[WaveNum:Period]{color,ls} Label'
Everything after the first space will be drawn as the label in the center of the line.
The values in square brackets designate the start and end position of the line.
`WaveNum` is the integer row number (starting at 0) of the wave, and `Period` is the possibly fractional number of periods in time for the node. `WaveNum` may be appended by a `^` or `v` to designate notations just above, or just below, the wave, respectively.
Between the two square-bracket expressions is the standard line/arrow type designator. In optional curly braces, the line color and linestyle may be entered.
Some examples are shown here:
.. jupyter-execute::
:emphasize-lines: 5-7
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': 'x3...x'},
{'name': 'B', 'wave': 'x6.6.x'}],
'edge': ['[0^:1]+[0^:5] $t_1$',
'[1^:1]<->[1^:3] $t_o$',
'[0^:3]-[1v:3]{gray,:}',
]},
ygap=.5, grid=False)
When placing edge labels above or below the wave, it can be useful to add the `ygap` parameter to TimingDiagram to increase the spacing between waves.
See the :ref:`gallerytiming` Gallery for more examples.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/timing-checkpoint.rst
|
timing-checkpoint.rst
|
Timing Diagrams
===============
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import logic
Digital timing diagrams may be drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` Element in the :py:mod:`schemdraw.logic` module.
Timing diagrams are set up using the WaveJSON syntax used by the `WaveDrom <https://wavedrom.com/>`_ JavaScript application.
.. code-block:: python
from schemdraw import logic
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}]})
The input is a dictionary containing a `signal`, which is a list of each wave to show in the diagram. Each signal is a dictionary which must contain a `name` and `wave`.
An empty dictionary leaves a blank row in the diagram.
Every character in the `wave` specifies the state of the wave for one period. A dot `.` means the previous state is repeated.
Wave characters 'n' and 'p' specify clock signals, and 'N', and 'P' draw clocks with arrows.
'1' and '0' are used to define high and low signals. '2' draws a data block, and '3' through '9' draw data filled with a color. 'x' draws a don't-care or undefined data state.
Data blocks can be labeled by adding a 'data' item to the wave's dictionary.
This example shows the different wave sections:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clock n', 'wave': 'n......'},
{'name': 'clock p', 'wave': 'p......'},
{'name': 'clock N', 'wave': 'N......'},
{'name': 'clock P', 'wave': 'P......'},
{},
{'name': '1s and 0s', 'wave': '0.1.01.'},
{'name': 'data', 'wave': '2..=.2.'}, # '=' is the same as '2'
{'name': 'data named', 'wave': '3.4.6..', 'data': ['A', 'B', 'C']},
{'name': 'dont care', 'wave': 'xx..x..'},
{},
{'name': 'high z', 'wave': 'z.10.z.'},
{'name': 'pull up/down', 'wave': '0u..d.1'},
]})
Putting them together in a more realistic example:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}]})
The `config` key, containing a dictionary with `hscale`, may be used to change the width of one period in the diagram:
.. jupyter-execute::
:emphasize-lines: 6
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'bus', 'wave': 'x.==.=x', 'data': ['head', 'body', 'tail']},
{'name': 'wire', 'wave': '0.1..0.'}],
'config': {'hscale': 2}})
Signals may also be nested into different groups:
.. jupyter-execute::
logic.TimingDiagram(
{'signal': ['Group',
['Set 1',
{'name': 'A', 'wave': '0..1..01.'},
{'name': 'B', 'wave': '101..0...'}],
['Set 2',
{'name': 'C', 'wave': '0..1..01.'},
{'name': 'D', 'wave': '101..0...'}]
]})
Using the `node` key in a waveform, plus the `edge` key in the top-level dictionary, provides a way to show transitions between different edges.
.. jupyter-execute::
:emphasize-lines: 5
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': '0..1..01.', 'node': '...a.....'},
{'name': 'B', 'wave': '101..0...', 'node': '.....b...'}],
'edge': ['a~>b']
})
Each string in the edge list must start and end with a node name (single character). The characters between them define the type of connecting line: '-' for straight line, '~' for curve, '-\|' for orthogonal lines, and \< or \> to include arrowheads.
For example, 'a-~>b' draws a curved line with arrowhead between nodes a and b.
Using JSON
----------
Because the examples from WaveDrom use JavaScript and JSON, they sometimes cannot be directly pasted into Python as dictionaries.
The :py:meth:`schemdraw.logic.timing.TimingDiagram.from_json` method allows input of the WaveJSON as a string pasted directly from the Javascript/JSON examples without modification.
Notice lack of quoting on the dictionary keys, requiring the `from_json` method to parse the string.
.. jupyter-execute::
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "P......" },
{ name: "bus", wave: "x.==.=x", data: ["head", "body", "tail", "data"] },
{ name: "wire", wave: "0.1..0." }
]}''')
Schemdraw's Customizations
--------------------------
Schemdraw extends the WaveJSON spcification with a few additional options.
Style Parameters
****************
Each wave dictionary accpets a `color` and `lw` parameter.
The rise/fall time for transitions can be set using the `risetime` parameter to TimingDiagram. Other colors and font sizes may be speficied using keyword arguments to :py:class:`schemdraw.logic.timing.TimingDiagram`.
Asynchronous Signals
********************
WaveDrom does not have a means for defining asynchronous signals - all waves must transition on period boundaries. Schemdraw adds asyncrhonous signals using the `async` parameter, as a list of period multiples for each transition in the wave. Note the beginning and end time of the wave must also be specified, so the length of the `async` list must be one more than the length of `wave`.
.. jupyter-execute::
:emphasize-lines: 4
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'n......'},
{'name': 'B', 'wave': '010', 'async': [0, 1.6, 4.25, 7]}]},
risetime=.03)
Extended Edge Notation
**********************
Additional "edge" string notations are allowed for more complex labeling of edge timings, including asynchronous start and end times and labels just above or below a wave.
Each edge string using this syntax takes the form
.. code-block:: python
'[WaveNum:Period]<->[WaveNum:Period]{color,ls} Label'
Everything after the first space will be drawn as the label in the center of the line.
The values in square brackets designate the start and end position of the line.
`WaveNum` is the integer row number (starting at 0) of the wave, and `Period` is the possibly fractional number of periods in time for the node. `WaveNum` may be appended by a `^` or `v` to designate notations just above, or just below, the wave, respectively.
Between the two square-bracket expressions is the standard line/arrow type designator. In optional curly braces, the line color and linestyle may be entered.
Some examples are shown here:
.. jupyter-execute::
:emphasize-lines: 5-7
logic.TimingDiagram(
{'signal': [
{'name': 'A', 'wave': 'x3...x'},
{'name': 'B', 'wave': 'x6.6.x'}],
'edge': ['[0^:1]+[0^:5] $t_1$',
'[1^:1]<->[1^:3] $t_o$',
'[0^:3]-[1v:3]{gray,:}',
]},
ygap=.5, grid=False)
When placing edge labels above or below the wave, it can be useful to add the `ygap` parameter to TimingDiagram to increase the spacing between waves.
See the :ref:`gallerytiming` Gallery for more examples.
| 0.880682 | 0.617599 |
Flowcharts and Diagrams
=======================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import flow
Schemdraw provides basic symbols for flowcharting and state diagrams.
The :py:mod:`schemdraw.flow.flow` module contains a set of functions for defining
flowchart blocks and connecting lines that can be added to schemdraw Drawings.
.. code-block:: python
from schemdraw import flow
Flowchart blocks:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Start().label('Start').drop('E'))
d.add(flow.Arrow())
d.add(flow.Ellipse().label('Ellipse'))
d.add(flow.Arrow())
d.add(flow.Box(label='Box'))
d.add(flow.Arrow())
d.add(flow.RoundBox(label='RoundBox').drop('S'))
d.add(flow.Arrow().down())
d.add(flow.Subroutine(label='Subroutine').drop('W'))
d.add(flow.Arrow().left())
d.add(flow.Data(label='Data'))
d.add(flow.Arrow())
d.add(flow.Decision(label='Decision'))
d.add(flow.Arrow())
d.add(flow.Connect(label='Connect'))
d.draw()
Some elements have been defined with multiple names, which can be used depending on the context or user preference:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Terminal().label('Terminal').drop('E'))
d.add(flow.Arrow())
d.add(flow.Process().label('Process'))
d.add(flow.Arrow())
d.add(flow.RoundProcess().label('RoundProcess'))
d.add(flow.Arrow())
d.add(flow.Circle(label='Circle'))
d.add(flow.Arrow())
d.add(flow.State(label='State'))
d.add(flow.Arrow())
d.add(flow.StateEnd(label='StateEnd'))
d.draw()
All flowchart symbols have 16 anchor positions named for the compass directions: 'N', 'S', 'E', 'W', 'NE', 'SE, 'NNE', etc., plus a 'center' anchor.
The :py:class:`schemdraw.elements.intcircuits.Ic` element can be used with the flowchart elements to create blocks with other inputs/outputs per side if needed.
The size of each block must be specified manually using `w` and `h` or `r` parameters to size each block to fit any labels.
Connecting Lines
----------------
Typical flowcharts will use `Line` or `Arrow` elements to connect the boxes. The line and arrow elements have been included in the `flow` module for convenience.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Do something').drop('E')
d += flow.Arrow().right()
d += flow.Process().label('Do something\nelse')
Some flow diagrams, such as State Machine diagrams, often use curved connectors between states. Several Arc connectors are available.
Each Arc element takes an `arrow` parameter, which may be '->', '<-', or '<->', to define the end(s) on which to draw arrowheads.
Arc2
^^^^
`Arc2` draws a symmetric quadratic Bezier curve between the endpoints, with curvature controlled by parameter `k`. Endpoints of the arc should be specified using `at()` and `to()` methods.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State(arrow='->').label('B').at((4, 0)))
d += flow.Arc2(arrow='->').at(a.NE).to(b.NW).color('deeppink').label('Arc2')
d += flow.Arc2(k=.2, arrow='<->').at(b.SW).to(a.SE).color('mediumblue').label('Arc2')
.. jupyter-execute::
:hide-code:
d.draw()
ArcZ and ArcN
^^^^^^^^^^^^^
These draw symmetric cubic Bezier curves between the endpoints. The `ArcZ` curve approaches the endpoints horizontally, and `ArcN` approaches them vertically.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((4, 4)))
d += (c := flow.State().label('C').at((8, 0)))
d += flow.ArcN(arrow='<->').at(a.N).to(b.S).color('deeppink').label('ArcN')
d += flow.ArcZ(arrow='<->').at(b.E).to(c.W).color('mediumblue').label('ArcZ')
.. jupyter-execute::
:hide-code:
d.draw()
Arc3
^^^^
The `Arc3` curve is an arbitrary cubic Bezier curve, defined by endpoints and angle of approach to each endpoint. `ArcZ` and `ArcN` are simply `Arc3` defined with the angles as 0 and 180, or 90 and 270, respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((3, 3)))
d += flow.Arc3(th1=75, th2=-45, arrow='<->').at(a.N).to(b.SE).color('deeppink').label('Arc3')
.. jupyter-execute::
:hide-code:
d.draw()
ArcLoop
^^^^^^^
The `ArcLoop` curve draws a partial circle that intersects the two endpoints, with the given radius. Often used in state machine diagrams to indicate cases where the state does not change.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += flow.ArcLoop(arrow='<-').at(a.NW).to(a.NNE).color('mediumblue').label('ArcLoop', halign='center')
.. jupyter-execute::
:hide-code:
d.draw()
Decisions
---------
To label the decision branches, the :py:class:`schemdraw.flow.flow.Decision` element takes keyword
arguments for each cardinal direction. For example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
decision = flow.Decision(W='Yes', E='No', S='Maybe').label('Question?')
.. jupyter-execute::
:hide-code:
dec = d.add(decision)
d.add(flow.Line().at(dec.W).left())
d.add(flow.Line().at(dec.E).right())
d.add(flow.Line().at(dec.S).down())
d.draw()
Layout and Flow
---------------
Without any directions specified, boxes flow top to bottom (see left image).
If a direction is specified (right image), the flow will continue in that direction, starting the next arrow at an appropriate anchor.
Otherwise, the `drop` method is useful for specifing where to begin the next arrow.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
d += flow.Terminal().label('Start').at((4, 0))
d += flow.Arrow().theta(-45)
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
See the :ref:`galleryflow` Gallery for more examples.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/flow-checkpoint.rst
|
flow-checkpoint.rst
|
Flowcharts and Diagrams
=======================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import flow
Schemdraw provides basic symbols for flowcharting and state diagrams.
The :py:mod:`schemdraw.flow.flow` module contains a set of functions for defining
flowchart blocks and connecting lines that can be added to schemdraw Drawings.
.. code-block:: python
from schemdraw import flow
Flowchart blocks:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Start().label('Start').drop('E'))
d.add(flow.Arrow())
d.add(flow.Ellipse().label('Ellipse'))
d.add(flow.Arrow())
d.add(flow.Box(label='Box'))
d.add(flow.Arrow())
d.add(flow.RoundBox(label='RoundBox').drop('S'))
d.add(flow.Arrow().down())
d.add(flow.Subroutine(label='Subroutine').drop('W'))
d.add(flow.Arrow().left())
d.add(flow.Data(label='Data'))
d.add(flow.Arrow())
d.add(flow.Decision(label='Decision'))
d.add(flow.Arrow())
d.add(flow.Connect(label='Connect'))
d.draw()
Some elements have been defined with multiple names, which can be used depending on the context or user preference:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=10, unit=.5)
d.add(flow.Terminal().label('Terminal').drop('E'))
d.add(flow.Arrow())
d.add(flow.Process().label('Process'))
d.add(flow.Arrow())
d.add(flow.RoundProcess().label('RoundProcess'))
d.add(flow.Arrow())
d.add(flow.Circle(label='Circle'))
d.add(flow.Arrow())
d.add(flow.State(label='State'))
d.add(flow.Arrow())
d.add(flow.StateEnd(label='StateEnd'))
d.draw()
All flowchart symbols have 16 anchor positions named for the compass directions: 'N', 'S', 'E', 'W', 'NE', 'SE, 'NNE', etc., plus a 'center' anchor.
The :py:class:`schemdraw.elements.intcircuits.Ic` element can be used with the flowchart elements to create blocks with other inputs/outputs per side if needed.
The size of each block must be specified manually using `w` and `h` or `r` parameters to size each block to fit any labels.
Connecting Lines
----------------
Typical flowcharts will use `Line` or `Arrow` elements to connect the boxes. The line and arrow elements have been included in the `flow` module for convenience.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Do something').drop('E')
d += flow.Arrow().right()
d += flow.Process().label('Do something\nelse')
Some flow diagrams, such as State Machine diagrams, often use curved connectors between states. Several Arc connectors are available.
Each Arc element takes an `arrow` parameter, which may be '->', '<-', or '<->', to define the end(s) on which to draw arrowheads.
Arc2
^^^^
`Arc2` draws a symmetric quadratic Bezier curve between the endpoints, with curvature controlled by parameter `k`. Endpoints of the arc should be specified using `at()` and `to()` methods.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State(arrow='->').label('B').at((4, 0)))
d += flow.Arc2(arrow='->').at(a.NE).to(b.NW).color('deeppink').label('Arc2')
d += flow.Arc2(k=.2, arrow='<->').at(b.SW).to(a.SE).color('mediumblue').label('Arc2')
.. jupyter-execute::
:hide-code:
d.draw()
ArcZ and ArcN
^^^^^^^^^^^^^
These draw symmetric cubic Bezier curves between the endpoints. The `ArcZ` curve approaches the endpoints horizontally, and `ArcN` approaches them vertically.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((4, 4)))
d += (c := flow.State().label('C').at((8, 0)))
d += flow.ArcN(arrow='<->').at(a.N).to(b.S).color('deeppink').label('ArcN')
d += flow.ArcZ(arrow='<->').at(b.E).to(c.W).color('mediumblue').label('ArcZ')
.. jupyter-execute::
:hide-code:
d.draw()
Arc3
^^^^
The `Arc3` curve is an arbitrary cubic Bezier curve, defined by endpoints and angle of approach to each endpoint. `ArcZ` and `ArcN` are simply `Arc3` defined with the angles as 0 and 180, or 90 and 270, respectively.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += (b := flow.State().label('B').at((3, 3)))
d += flow.Arc3(th1=75, th2=-45, arrow='<->').at(a.N).to(b.SE).color('deeppink').label('Arc3')
.. jupyter-execute::
:hide-code:
d.draw()
ArcLoop
^^^^^^^
The `ArcLoop` curve draws a partial circle that intersects the two endpoints, with the given radius. Often used in state machine diagrams to indicate cases where the state does not change.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
d += (a := flow.State().label('A'))
d += flow.ArcLoop(arrow='<-').at(a.NW).to(a.NNE).color('mediumblue').label('ArcLoop', halign='center')
.. jupyter-execute::
:hide-code:
d.draw()
Decisions
---------
To label the decision branches, the :py:class:`schemdraw.flow.flow.Decision` element takes keyword
arguments for each cardinal direction. For example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(fontsize=12, unit=1)
.. jupyter-execute::
decision = flow.Decision(W='Yes', E='No', S='Maybe').label('Question?')
.. jupyter-execute::
:hide-code:
dec = d.add(decision)
d.add(flow.Line().at(dec.W).left())
d.add(flow.Line().at(dec.E).right())
d.add(flow.Line().at(dec.S).down())
d.draw()
Layout and Flow
---------------
Without any directions specified, boxes flow top to bottom (see left image).
If a direction is specified (right image), the flow will continue in that direction, starting the next arrow at an appropriate anchor.
Otherwise, the `drop` method is useful for specifing where to begin the next arrow.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.config(fontsize=10, unit=.5)
d += flow.Terminal().label('Start')
d += flow.Arrow()
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
d += flow.Terminal().label('Start').at((4, 0))
d += flow.Arrow().theta(-45)
d += flow.Process().label('Step 1')
d += flow.Arrow()
d += flow.Process().label('Step 2').drop('E')
d += flow.Arrow().right()
d += flow.Connect().label('Next')
See the :ref:`galleryflow` Gallery for more examples.
| 0.886482 | 0.667792 |
Signal Processing
=================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import dsp
Signal processing elements can be drawn by importing the :py:mod:`schemdraw.dsp.dsp` module:
.. code-block:: python
from schemdraw import dsp
Because each element may have multiple connections in and out, these elements
are not 2-terminal elements that extend "leads", so they must be manually connected with
`Line` or `Arrow` elements. The square elements define anchors 'N', 'S', 'E', and 'W' for
the four directions. Circle-based elements also includ 'NE', 'NW', 'SE', and 'SW'
anchors.
Directional elements, such as `Amp`, `Adc`, and `Dac` define anchors `input` and `out`.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().right().at((x,y)).label(name, loc='rgt', ofst=.2, halign='left', valign='center')
return d
elms = [dsp.Square, dsp.Circle, dsp.Sum, dsp.SumSigma, dsp.Mixer, dsp.Speaker,
dsp.Amp, dsp.OscillatorBox, dsp.Oscillator, dsp.Filter,
partial(dsp.Filter, response='lp'), partial(dsp.Filter, response='bp'),
partial(dsp.Filter, response='hp'), dsp.Adc, dsp.Dac, dsp.Demod,
dsp.Circulator, dsp.Isolator, dsp.VGA
]
drawElements(elms, dx=6)
Labels are placed in the center of the element. The generic `Square` and `Circle` elements can be used with a label to define other operations. For example, an integrator
may be created using:
.. jupyter-execute::
dsp.Square().label('$\int$')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/elements/.ipynb_checkpoints/dsp-checkpoint.rst
|
dsp-checkpoint.rst
|
Signal Processing
=================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
from functools import partial
import schemdraw
from schemdraw import dsp
Signal processing elements can be drawn by importing the :py:mod:`schemdraw.dsp.dsp` module:
.. code-block:: python
from schemdraw import dsp
Because each element may have multiple connections in and out, these elements
are not 2-terminal elements that extend "leads", so they must be manually connected with
`Line` or `Arrow` elements. The square elements define anchors 'N', 'S', 'E', and 'W' for
the four directions. Circle-based elements also includ 'NE', 'NW', 'SE', and 'SW'
anchors.
Directional elements, such as `Amp`, `Adc`, and `Dac` define anchors `input` and `out`.
.. jupyter-execute::
:hide-code:
def drawElements(elmlist, cols=3, dx=8, dy=2):
d = schemdraw.Drawing(fontsize=12)
for i, e in enumerate(elmlist):
y = i//cols*-dy
x = (i%cols) * dx
name = type(e()).__name__
if hasattr(e, 'keywords'): # partials have keywords attribute
args = ', '.join(['{}={}'.format(k, v) for k, v in e.keywords.items()])
name = '{}({})'.format(name, args)
d += e().right().at((x,y)).label(name, loc='rgt', ofst=.2, halign='left', valign='center')
return d
elms = [dsp.Square, dsp.Circle, dsp.Sum, dsp.SumSigma, dsp.Mixer, dsp.Speaker,
dsp.Amp, dsp.OscillatorBox, dsp.Oscillator, dsp.Filter,
partial(dsp.Filter, response='lp'), partial(dsp.Filter, response='bp'),
partial(dsp.Filter, response='hp'), dsp.Adc, dsp.Dac, dsp.Demod,
dsp.Circulator, dsp.Isolator, dsp.VGA
]
drawElements(elms, dx=6)
Labels are placed in the center of the element. The generic `Square` and `Circle` elements can be used with a label to define other operations. For example, an integrator
may be created using:
.. jupyter-execute::
dsp.Square().label('$\int$')
| 0.826327 | 0.500061 |
Customizing Elements
====================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
from schemdraw.segments import *
Grouping Elements
-----------------
If a set of circuit elements are to be reused multiple times, they can be grouped into a single element.
Create and populate a drawing, but set `show=False`.
Instead, use the Drawing to create a new :py:class:`schemdraw.elements.ElementDrawing`, which converts the drawing into an element instance
to add to other drawings.
.. jupyter-execute::
:emphasize-lines: 8-10
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2: # Add a second drawing
for i in range(3):
d2 += elm.ElementDrawing(d1) # Add the first drawing to it 3 times
.. _customelements:
Defining custom elements
------------------------
All elements are subclasses of :py:class:`schemdraw.elements.Element` or :py:class:`schemdraw.elements.Element2Term`.
For elements consisting of several other already-defined elements (like a relay), :py:class:`schemdraw.elements.compound.ElementCompound` can be used for easy combining of multiple elements.
Subclasses only need to define the `__init__` method in order to add lines, shapes, and text to the new element, all of which are defined using :py:class:`schemdraw.segments.Segment` classes. New Segments should be appended to the `Element.segments` attribute list.
Coordinates are all defined in element cooridnates, where the element begins
at (0, 0) and is drawn from left to right.
The drawing engine will rotate and translate the element to its final position, and for two-terminal
elements deriving from Element2Term, will add lead extensions to the correct length depending
on the element's placement parameters.
Therefore elements deriving from Element2Term should not define the lead extensions
(e.g. a Resistor only defines the zig-zag portion).
A standard resistor is 1 drawing unit long, and with default lead extension will become 3 units long.
Segments include :py:class:`schemdraw.segments.Segment`, :py:class:`schemdraw.segments.SegmentPoly`,
:py:class:`schemdraw.segments.SegmentCircle`, :py:class:`schemdraw.segments.SegmentArc`, :py:class:`schemdraw.segments.SegmentText`, and :py:class:`schemdraw.segments.SegmentBezier`.
The subclassed `Element.__init__` method can be defined with extra parameters
to help define the element options.
In addition to the list of Segments, any named anchors and other parameters should be specified.
Anchors should be added to the `Element.anchors` dictionary as {name: (x, y)} key/value pairs.
The Element instance maintains its own parameters dictionary in `Element.params` that override the default drawing parameters.
Parameters are resolved by a ChainMap of user arguments to the `Element` instance, the `Element.params` attribute, then the `schemdraw.Drawing` parameters, in that order.
A common use of setting `Element.params` in the setup function is to change the default position of text labels, for example Transistor elements apply labels on the right side of the element by default, so they add to the setup:
.. code-block::
self.params['lblloc'] = 'rgt'
The user can still override this label position by creating, for example, `Transistor().label('Q1', loc='top')`.
As an example, here's the definition of our favorite element, the resistor:
.. code-block:: python
class Resistor(Element2Term):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
self.segments.append(Segment([(0, 0),
(0.5*reswidth, resheight),
(1.5*reswidth, -resheight),
(2.5*reswidth, resheight),
(3.5*reswidth, -resheight),
(4.5*reswidth, resheight),
(5.5*reswidth, -resheight),
(6*reswidth, 0)]))
The resistor is made of one path.
`reswidth` and `resheight` are constants that define the height and width of the resistor zigzag (and are referenced by several other elements too).
Browse the source code in the `Schemdraw.elements` submodule to see the definitions of the other built-in elements.
Flux Capacitor Example
^^^^^^^^^^^^^^^^^^^^^^
For an example, let's make a flux capacitor circuit element.
Since everyone knows a flux-capacitor has three branches, we should subclass the standard :py:class:`schemdraw.elements.Element` class instead of :py:class:`schemdraw.elements.Element2Term`.
Start by importing the Segments and define the class name and `__init__` function:
.. code-block:: python
from schemdraw.segments import *
class FluxCapacitor(Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
The `d` and `kwargs` are passed to `super` to initialize the Element.
We want a dot in the center of our flux capacitor, so start by adding a `SegmentCircle`. The `fclen` and `radius` variables could be set as arguments to the __init__ for the user to adjust, if desired, but here they are defined as constants in the __init__.
.. code-block:: python
fclen = 0.5
radius = 0.075
self.segments.append(SegmentCircle((0, 0), radius))
Next, add the paths as Segment instances, which are drawn as lines. The flux capacitor will have three paths, all extending from the center dot:
.. code-block:: python
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
And at the end of each path is an open circle. Append three more `SegmentCircle` instances.
By specifying `fill=None` the SegmentCircle will always remain unfilled regardless of any `fill` arguments provided to `Drawing` or `FluxCapacitor`.
.. code-block:: python
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
Finally, we need to define anchor points so that other elements can be connected to the right places.
Here, they're called `p1`, `p2`, and `p3` for lack of better names (what do you call the inputs to a flux capacitor?)
Add these to the `self.anchors` dictionary.
.. code-block:: python
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Here's the Flux Capacitor class all in one:
.. jupyter-execute::
class FluxCapacitor(elm.Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
radius = 0.075
fclen = 0.5
self.segments.append(SegmentCircle((0, 0), radius))
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Try it out:
.. jupyter-execute::
FluxCapacitor()
Segment objects
---------------
After an element is added to a drawing, the :py:class:`schemdraw.segments.Segment` objects defining it are accessible in the `segments` attribute list of the Element.
For even more control over customizing individual pieces of an element, the parameters of a Segment can be changed.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (n := logic.Nand())
n.segments[1].color = 'red'
n.segments[1].zorder = 5 # Put the bubble on top
.. jupyter-execute::
:hide-code:
d.draw()
Matplotlib axis
---------------
When using the Matplotlib backend (the default), a final customization option is to use the Matplotlib figure and add to it.
A :py:class:`schemdraw.Figure` is returned from the `draw` method, which contains `fig` and `ax` attributes holding the Matplotlib figure.
.. jupyter-execute::
:emphasize-lines: 4-5
schemdraw.use('matplotlib')
d = schemdraw.Drawing()
d.add(elm.Resistor())
schemfig = d.draw()
schemfig.ax.axvline(.5, color='purple', ls='--')
schemfig.ax.axvline(2.5, color='orange', ls='-', lw=3);
display(schemfig)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/customizing.rst
|
customizing.rst
|
Customizing Elements
====================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
from schemdraw.segments import *
Grouping Elements
-----------------
If a set of circuit elements are to be reused multiple times, they can be grouped into a single element.
Create and populate a drawing, but set `show=False`.
Instead, use the Drawing to create a new :py:class:`schemdraw.elements.ElementDrawing`, which converts the drawing into an element instance
to add to other drawings.
.. jupyter-execute::
:emphasize-lines: 8-10
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2: # Add a second drawing
for i in range(3):
d2 += elm.ElementDrawing(d1) # Add the first drawing to it 3 times
.. _customelements:
Defining custom elements
------------------------
All elements are subclasses of :py:class:`schemdraw.elements.Element` or :py:class:`schemdraw.elements.Element2Term`.
For elements consisting of several other already-defined elements (like a relay), :py:class:`schemdraw.elements.compound.ElementCompound` can be used for easy combining of multiple elements.
Subclasses only need to define the `__init__` method in order to add lines, shapes, and text to the new element, all of which are defined using :py:class:`schemdraw.segments.Segment` classes. New Segments should be appended to the `Element.segments` attribute list.
Coordinates are all defined in element cooridnates, where the element begins
at (0, 0) and is drawn from left to right.
The drawing engine will rotate and translate the element to its final position, and for two-terminal
elements deriving from Element2Term, will add lead extensions to the correct length depending
on the element's placement parameters.
Therefore elements deriving from Element2Term should not define the lead extensions
(e.g. a Resistor only defines the zig-zag portion).
A standard resistor is 1 drawing unit long, and with default lead extension will become 3 units long.
Segments include :py:class:`schemdraw.segments.Segment`, :py:class:`schemdraw.segments.SegmentPoly`,
:py:class:`schemdraw.segments.SegmentCircle`, :py:class:`schemdraw.segments.SegmentArc`, :py:class:`schemdraw.segments.SegmentText`, and :py:class:`schemdraw.segments.SegmentBezier`.
The subclassed `Element.__init__` method can be defined with extra parameters
to help define the element options.
In addition to the list of Segments, any named anchors and other parameters should be specified.
Anchors should be added to the `Element.anchors` dictionary as {name: (x, y)} key/value pairs.
The Element instance maintains its own parameters dictionary in `Element.params` that override the default drawing parameters.
Parameters are resolved by a ChainMap of user arguments to the `Element` instance, the `Element.params` attribute, then the `schemdraw.Drawing` parameters, in that order.
A common use of setting `Element.params` in the setup function is to change the default position of text labels, for example Transistor elements apply labels on the right side of the element by default, so they add to the setup:
.. code-block::
self.params['lblloc'] = 'rgt'
The user can still override this label position by creating, for example, `Transistor().label('Q1', loc='top')`.
As an example, here's the definition of our favorite element, the resistor:
.. code-block:: python
class Resistor(Element2Term):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
self.segments.append(Segment([(0, 0),
(0.5*reswidth, resheight),
(1.5*reswidth, -resheight),
(2.5*reswidth, resheight),
(3.5*reswidth, -resheight),
(4.5*reswidth, resheight),
(5.5*reswidth, -resheight),
(6*reswidth, 0)]))
The resistor is made of one path.
`reswidth` and `resheight` are constants that define the height and width of the resistor zigzag (and are referenced by several other elements too).
Browse the source code in the `Schemdraw.elements` submodule to see the definitions of the other built-in elements.
Flux Capacitor Example
^^^^^^^^^^^^^^^^^^^^^^
For an example, let's make a flux capacitor circuit element.
Since everyone knows a flux-capacitor has three branches, we should subclass the standard :py:class:`schemdraw.elements.Element` class instead of :py:class:`schemdraw.elements.Element2Term`.
Start by importing the Segments and define the class name and `__init__` function:
.. code-block:: python
from schemdraw.segments import *
class FluxCapacitor(Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
The `d` and `kwargs` are passed to `super` to initialize the Element.
We want a dot in the center of our flux capacitor, so start by adding a `SegmentCircle`. The `fclen` and `radius` variables could be set as arguments to the __init__ for the user to adjust, if desired, but here they are defined as constants in the __init__.
.. code-block:: python
fclen = 0.5
radius = 0.075
self.segments.append(SegmentCircle((0, 0), radius))
Next, add the paths as Segment instances, which are drawn as lines. The flux capacitor will have three paths, all extending from the center dot:
.. code-block:: python
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
And at the end of each path is an open circle. Append three more `SegmentCircle` instances.
By specifying `fill=None` the SegmentCircle will always remain unfilled regardless of any `fill` arguments provided to `Drawing` or `FluxCapacitor`.
.. code-block:: python
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
Finally, we need to define anchor points so that other elements can be connected to the right places.
Here, they're called `p1`, `p2`, and `p3` for lack of better names (what do you call the inputs to a flux capacitor?)
Add these to the `self.anchors` dictionary.
.. code-block:: python
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Here's the Flux Capacitor class all in one:
.. jupyter-execute::
class FluxCapacitor(elm.Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
radius = 0.075
fclen = 0.5
self.segments.append(SegmentCircle((0, 0), radius))
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Try it out:
.. jupyter-execute::
FluxCapacitor()
Segment objects
---------------
After an element is added to a drawing, the :py:class:`schemdraw.segments.Segment` objects defining it are accessible in the `segments` attribute list of the Element.
For even more control over customizing individual pieces of an element, the parameters of a Segment can be changed.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (n := logic.Nand())
n.segments[1].color = 'red'
n.segments[1].zorder = 5 # Put the bubble on top
.. jupyter-execute::
:hide-code:
d.draw()
Matplotlib axis
---------------
When using the Matplotlib backend (the default), a final customization option is to use the Matplotlib figure and add to it.
A :py:class:`schemdraw.Figure` is returned from the `draw` method, which contains `fig` and `ax` attributes holding the Matplotlib figure.
.. jupyter-execute::
:emphasize-lines: 4-5
schemdraw.use('matplotlib')
d = schemdraw.Drawing()
d.add(elm.Resistor())
schemfig = d.draw()
schemfig.ax.axvline(.5, color='purple', ls='--')
schemfig.ax.axvline(2.5, color='orange', ls='-', lw=3);
display(schemfig)
| 0.897803 | 0.693447 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _placement:
Placing Elements
================
Elements are added to a Drawing using the `add` method or `+=` shortcut.
The Drawing maintains a current position and direction, such that the default placement of the next element
will start at the end of the previous element, going in the same direction.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor()
d += elm.Diode()
If a direction method (`up`, `down`, `left`, `right`) is added to an element, the element is rotated in that direction, and future elements take the same direction:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor().up()
d += elm.Diode()
The `theta` method can be used to specify any rotation angle in degrees.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().theta(20).label('R1')
d += elm.Resistor().label('R2') # Takes position and direction from R1
.. jupyter-execute::
:hide-code:
d.draw()
Anchors
-------
All elements have a set of predefined "anchor" positions within the element.
For example, a bipolar transistor has `base`, `emitter`, and `collector` anchors.
All two-terminal elements have anchors named `start`, `center`, and `end`.
The docstring for each element lists the available anchors.
Once an element is added to the drawing, all its anchor positions will be added as attributes to the element object, so the base position of transistor assigned to variable `Q` may be accessed via `Q.base`.
Rather than working in absolute (x, y) coordinates, anchors can be used to set the position of new elements.
Using the `at` method, one element can be placed starting on the anchor of another element.
For example, to draw an opamp and place a resistor on the output, store the Opamp instance to a variable. Then call the `at` method of the new element passing the `Opamp.out` anchor. After the resistor is drawn, the current drawing position is moved to the endpoint of the resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
opamp = d.add(elm.Opamp())
d.add(elm.Resistor().right().at(opamp.out))
.. jupyter-execute::
:hide-code:
d.draw()
Python's walrus operator provides a convenient shorthand notation for adding an element using `+=` and storing it at the same time.
The above code can be written equivalently as:
.. code-block:: python
d += (opamp := elm.Opamp())
d += elm.Resistor().right().at(opamp.out)
The second purpose for anchors is aligning new elements with respect to existing elements.
Suppose a resistor has just been placed, and now an Opamp should be connected to the resistor.
The `anchor` method tells the Drawing which input on the Opamp should align with resistor.
Here, an Opamp is placed at the end of a resistor, connected to the opamp's `in1` anchor (the inverting input).
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R1')
d += elm.Opamp().anchor('in1')
.. jupyter-execute::
:hide-code:
d.draw()
Compared to anchoring the opamp at `in2` (the noninverting input):
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R2')
d += elm.Opamp().anchor('in2')
.. jupyter-execute::
:hide-code:
d.draw()
Dimensions
----------
The inner zig-zag portion of a resistor has length of 1 unit, while the default lead extensions are 1 unit on each side,
making the default total resistor length 3 units.
Placement methods such as `at` and `to` accept a tuple of (x, y) position in these units.
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((1, .7)).to((2, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((3, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
This default 2-terminal length can be changed using the `unit` parameter to the :py:meth:`schemdraw.Drawing.config` method:
.. code-block:: python
with schemdraw.Drawing() as d:
d.config(unit=2)
...
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d.config(unit=2)
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((.5, .7)).to((1.5, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((2, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
Two-Terminal Elements
---------------------
In Schemdraw, a "Two-Terminal Element" is any element that can grow to fill a given length (this includes elements such as the Potentiometer, even though it electrically has three terminals).
All two-terminal elements subclass :py:class:`schemdraw.elements.Element2Term`.
They have some additional methods for setting placement and length.
The `length` method sets an exact length for a two-terminal element. Alternatively, the `up`, `down`, `left`, and `right` methods on two-terminal elements take a length parameter.
.. jupyter-execute::
:emphasize-lines: 5
with schemdraw.Drawing() as d:
d += elm.Dot()
d += elm.Resistor()
d += elm.Dot()
d += elm.Diode().length(6)
d += elm.Dot()
The `to` method will set an exact endpoint for a 2-terminal element.
The starting point is still the ending location of the previous element.
Notice the Diode is stretched longer than the standard element length in order to fill the diagonal distance.
.. jupyter-execute::
:emphasize-lines: 4
with schemdraw.Drawing() as d:
R = d.add(elm.Resistor())
C = d.add(elm.Capacitor().up())
Q = d.add(elm.Diode().to(R.start))
The `tox` and `toy` methods are useful for placing 2-terminal elements to "close the loop", without requiring an exact length.
They extend the element horizontally or vertically to the x- or y- coordinate of the anchor given as the argument.
These methods automatically change the drawing direction.
Here, the Line element does not need to specify an exact length to fill the space and connect back with the Source.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 9
d += (C := elm.Capacitor())
d += elm.Diode()
d += elm.Line().down()
# Now we want to close the loop, but can use `tox`
# to avoid having to know exactly how far to go.
# The Line will extend horizontally to the same x-position
# as the Capacitor's `start` anchor.
d += elm.Line().tox(C.start)
# Now close the loop by relying on the fact that all
# two-terminal elements (including Source and Line)
# are the same length by default
d += elm.Source().up()
.. jupyter-execute::
:hide-code:
d.draw()
Finally, exact endpoints can also be specified using the `endpoints` method.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 5
d += (R := elm.Resistor())
d += (Q := elm.Diode().down(6))
d += elm.Line().tox(R.start)
d += elm.Capacitor().toy(R.start)
d += elm.SourceV().endpoints(Q.end, R.start)
.. jupyter-execute::
:hide-code:
d.draw()
Orientation
-----------
The `flip` and `reverse` methods are useful for changing orientation of directional elements such as Diodes,
but they do not affect the drawing direction.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Zener().label('Normal')
d += elm.Zener().flip().label('Flip')
d += elm.Zener().reverse().label('Reverse')
.. jupyter-execute::
:hide-code:
d.draw()
Drawing State
-------------
The :py:class:`schemdraw.Drawing` maintains a drawing state that includes the current x, y position, stored in the `Drawing.here` attribute as a (x, y) tuple, and drawing direction stored in the `Drawing.theta` attribute.
A LIFO stack of drawing states can be used, via the :py:meth:`schemdraw.Drawing.push` and :py:meth:`schemdraw.Drawing.pop` method,
for situations when it's useful to save the drawing state and come back to it later.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 4,10
d += elm.Inductor()
d += elm.Dot()
print('d.here:', d.here)
d.push() # Save this drawing position/direction for later
d += elm.Capacitor().down() # Go off in another direction temporarily
d += elm.Ground(lead=False)
print('d.here:', d.here)
d.pop() # Return to the pushed position/direction
print('d.here:', d.here)
d += elm.Diode()
d.draw()
Changing the drawing position can be accomplished by calling :py:meth:`schemdraw.Drawing.move` or :py:meth:`schemdraw.Drawing.move_from`.
Drop and Hold Methods
*********************
To place an element without moving the drawing position, use the :py:meth:`schemdraw.elements.Element.hold` method. The element will be placed without changing the drawing state.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.Diode() # Normal placement: drawing position moves to end of element
d += elm.Dot().color('red')
d.here = (0, -1)
d += elm.Diode().hold() # Hold method prevents position from changing
d += elm.Dot().color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
Three-terminal elements do not necessarily leave the drawing position where desired, so after drawing an element, the current drawing position can be set using the :py:meth:`schemdraw.elements.Element.drop` method to specify an anchor at which to place the cursor.
This reduces the need to assign every element to a variable name.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.BjtNpn()
d += elm.Resistor().label('R1')
d.here = (5, 0)
d += elm.BjtNpn().drop('emitter')
d += elm.Resistor().label('R2')
.. jupyter-execute::
:hide-code:
d.draw()
Connecting Elements
-------------------
Typically, the :py:class:`schemdraw.elements.lines.Line` element is used to connect elements together.
More complex line routing requires multiple Line elements.
The :py:class:`schemdraw.elements.lines.Wire` element is used as a shortcut for placing multiple connecting lines at once.
The Wire element connects the start and end points based on its `shape` parameter.
The `k` parameter is used to set the distance before the wire first changes direction.
.. list-table:: Wire Shape Parameters
:widths: 25 50
:header-rows: 1
* - Shape Parameter
- Description
* - `-`
- Direct Line
* - `-\|`
- Horizontal then vertical
* - `\|-`
- Vertical then horizontal
* - `n`
- Vertical-horizontal-vertical (like an n or u)
* - `c`
- Horizontal-vertical-horizontal (like a c or ↄ)
* - `z`
- Horizontal-diagonal-horizontal
* - `N`
- Vertical-diagonal-vertical
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (A := elm.Dot().label('A', halign='right', ofst=(-.1, 0)))
d += (B := elm.Dot().label('B').at((4, 4)))
d += (C := elm.Dot().label('C', ofst=(-.2, 0)).at((7, 4)))
d += (D := elm.Dot().label('D', ofst=(-.2, 0)).at((9, 0)))
d += (E := elm.Dot().label('E', ofst=(-.2, 0)).at((11, 4)))
d += (F := elm.Dot().label('F', ofst=(-.2, 0)).at((13, 0)))
.. jupyter-execute::
d += elm.Wire('-', arrow='->').at(A.center).to(B.center).color('deeppink').label('"-"')
d += elm.Wire('|-', arrow='->').at(A.center).to(B.center).color('mediumblue').label('"|-"')
d += elm.Wire('-|', arrow='->').at(A.center).to(B.center).color('darkseagreen').label('"-|"')
d += elm.Wire('c', k=-1, arrow='->').at(C.center).to(D.center).color('darkorange').label('"c"', halign='left')
d += elm.Wire('n', arrow='->').at(C.center).to(D.center).color('orchid').label('"n"')
d += elm.Wire('N', arrow='->').at(E.center).to(F.center).color('darkred').label('"N"', 'start', ofst=(-.1, -.75))
d += elm.Wire('z', k=.5, arrow='->').at(E.center).to(F.center).color('teal').label('"z"', halign='left', ofst=(0, .5))
.. jupyter-execute::
:hide-code:
d.draw()
Both `Line` and `Wire` elements take an `arrow` parameter, a string specification of arrowhead types at the start and end of the wire. The arrow string may contain "<", ">", for arrowheads, "\|" for an endcap, and "o" for a dot. Some examples are shown below:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Line(arrow='->').label('"->"', 'right')
d += elm.Line(arrow='<-').at((0, -.75)).label('"<-"', 'right')
d += elm.Line(arrow='<->').at((0, -1.5)).label('"<->"', 'right')
d += elm.Line(arrow='|->').at((0, -2.25)).label('"|->"', 'right')
d += elm.Line(arrow='|-o').at((0, -3.0)).label('"|-o"', 'right')
.. jupyter-execute::
:hide-code:
d.draw()
Because dots are used to show connected wires, all two-terminal elements have `dot` and `idot` methods for quickly adding a dot at the end or beginning of the element, respectively.
.. jupyter-execute::
elm.Resistor().dot()
Keyword Arguments
-----------------
All :py:class:`schemdraw.elements.Element` types take keyword arguments that can also be used to set
element properties, partly for historical reasons but also for easy element setup via dictionary unpacking.
The keyword arguments are equivalent to calling the Element setup methods.
The keyword arguments are not validated or type checked, so the chained method interface
described above is recommended for configuring elements.
+--------------------+-------------------------------+
| Keyword Argument | Method Equivalent |
+====================+===============================+
| `d='up'` | `.up()` |
+--------------------+-------------------------------+
| `d='down'` | `.down()` |
+--------------------+-------------------------------+
| `d='left'` | `.left()` |
+--------------------+-------------------------------+
| `d='right'` | `.right()` |
+--------------------+-------------------------------+
| `theta=X` | `.theta(X)` |
+--------------------+-------------------------------+
| `at=X` or `xy=X` | `.at(X)` |
+--------------------+-------------------------------+
| `flip=True` | `.flip()` |
+--------------------+-------------------------------+
| `reverse=True` | `.reverse()` |
+--------------------+-------------------------------+
| `anchor=X` | `.anchor(X)` |
+--------------------+-------------------------------+
| `zoom=X` | `.scale(X)` |
+--------------------+-------------------------------+
| `color=X` | `.color(X)` |
+--------------------+-------------------------------+
| `fill=X` | `.fill(X)` |
+--------------------+-------------------------------+
| `ls=X` | `.linestyle(X)` |
+--------------------+-------------------------------+
| `lw=X` | `.linewidth(X)` |
+--------------------+-------------------------------+
| `zorder=X` | `.zorder(X)` |
+--------------------+-------------------------------+
| `move_cur=False` | `.hold()` |
+--------------------+-------------------------------+
| `label=X` | `.label(X)` |
+--------------------+-------------------------------+
| `botlabel=X` | `.label(X, loc='bottom')` |
+--------------------+-------------------------------+
| `lftlabel=X` | `.label(X, loc='left')` |
+--------------------+-------------------------------+
| `rgtlabel=X` | `.label(X, loc='right')` |
+--------------------+-------------------------------+
| `toplabel=X` | `.label(X, loc='top')` |
+--------------------+-------------------------------+
| `lblloc=X` | `.label(..., loc=X)` |
+--------------------+-------------------------------+
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/placement.rst
|
placement.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _placement:
Placing Elements
================
Elements are added to a Drawing using the `add` method or `+=` shortcut.
The Drawing maintains a current position and direction, such that the default placement of the next element
will start at the end of the previous element, going in the same direction.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor()
d += elm.Diode()
If a direction method (`up`, `down`, `left`, `right`) is added to an element, the element is rotated in that direction, and future elements take the same direction:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor().up()
d += elm.Diode()
The `theta` method can be used to specify any rotation angle in degrees.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().theta(20).label('R1')
d += elm.Resistor().label('R2') # Takes position and direction from R1
.. jupyter-execute::
:hide-code:
d.draw()
Anchors
-------
All elements have a set of predefined "anchor" positions within the element.
For example, a bipolar transistor has `base`, `emitter`, and `collector` anchors.
All two-terminal elements have anchors named `start`, `center`, and `end`.
The docstring for each element lists the available anchors.
Once an element is added to the drawing, all its anchor positions will be added as attributes to the element object, so the base position of transistor assigned to variable `Q` may be accessed via `Q.base`.
Rather than working in absolute (x, y) coordinates, anchors can be used to set the position of new elements.
Using the `at` method, one element can be placed starting on the anchor of another element.
For example, to draw an opamp and place a resistor on the output, store the Opamp instance to a variable. Then call the `at` method of the new element passing the `Opamp.out` anchor. After the resistor is drawn, the current drawing position is moved to the endpoint of the resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
opamp = d.add(elm.Opamp())
d.add(elm.Resistor().right().at(opamp.out))
.. jupyter-execute::
:hide-code:
d.draw()
Python's walrus operator provides a convenient shorthand notation for adding an element using `+=` and storing it at the same time.
The above code can be written equivalently as:
.. code-block:: python
d += (opamp := elm.Opamp())
d += elm.Resistor().right().at(opamp.out)
The second purpose for anchors is aligning new elements with respect to existing elements.
Suppose a resistor has just been placed, and now an Opamp should be connected to the resistor.
The `anchor` method tells the Drawing which input on the Opamp should align with resistor.
Here, an Opamp is placed at the end of a resistor, connected to the opamp's `in1` anchor (the inverting input).
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R1')
d += elm.Opamp().anchor('in1')
.. jupyter-execute::
:hide-code:
d.draw()
Compared to anchoring the opamp at `in2` (the noninverting input):
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R2')
d += elm.Opamp().anchor('in2')
.. jupyter-execute::
:hide-code:
d.draw()
Dimensions
----------
The inner zig-zag portion of a resistor has length of 1 unit, while the default lead extensions are 1 unit on each side,
making the default total resistor length 3 units.
Placement methods such as `at` and `to` accept a tuple of (x, y) position in these units.
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((1, .7)).to((2, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((3, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
This default 2-terminal length can be changed using the `unit` parameter to the :py:meth:`schemdraw.Drawing.config` method:
.. code-block:: python
with schemdraw.Drawing() as d:
d.config(unit=2)
...
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d.config(unit=2)
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((.5, .7)).to((1.5, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((2, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
Two-Terminal Elements
---------------------
In Schemdraw, a "Two-Terminal Element" is any element that can grow to fill a given length (this includes elements such as the Potentiometer, even though it electrically has three terminals).
All two-terminal elements subclass :py:class:`schemdraw.elements.Element2Term`.
They have some additional methods for setting placement and length.
The `length` method sets an exact length for a two-terminal element. Alternatively, the `up`, `down`, `left`, and `right` methods on two-terminal elements take a length parameter.
.. jupyter-execute::
:emphasize-lines: 5
with schemdraw.Drawing() as d:
d += elm.Dot()
d += elm.Resistor()
d += elm.Dot()
d += elm.Diode().length(6)
d += elm.Dot()
The `to` method will set an exact endpoint for a 2-terminal element.
The starting point is still the ending location of the previous element.
Notice the Diode is stretched longer than the standard element length in order to fill the diagonal distance.
.. jupyter-execute::
:emphasize-lines: 4
with schemdraw.Drawing() as d:
R = d.add(elm.Resistor())
C = d.add(elm.Capacitor().up())
Q = d.add(elm.Diode().to(R.start))
The `tox` and `toy` methods are useful for placing 2-terminal elements to "close the loop", without requiring an exact length.
They extend the element horizontally or vertically to the x- or y- coordinate of the anchor given as the argument.
These methods automatically change the drawing direction.
Here, the Line element does not need to specify an exact length to fill the space and connect back with the Source.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 9
d += (C := elm.Capacitor())
d += elm.Diode()
d += elm.Line().down()
# Now we want to close the loop, but can use `tox`
# to avoid having to know exactly how far to go.
# The Line will extend horizontally to the same x-position
# as the Capacitor's `start` anchor.
d += elm.Line().tox(C.start)
# Now close the loop by relying on the fact that all
# two-terminal elements (including Source and Line)
# are the same length by default
d += elm.Source().up()
.. jupyter-execute::
:hide-code:
d.draw()
Finally, exact endpoints can also be specified using the `endpoints` method.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 5
d += (R := elm.Resistor())
d += (Q := elm.Diode().down(6))
d += elm.Line().tox(R.start)
d += elm.Capacitor().toy(R.start)
d += elm.SourceV().endpoints(Q.end, R.start)
.. jupyter-execute::
:hide-code:
d.draw()
Orientation
-----------
The `flip` and `reverse` methods are useful for changing orientation of directional elements such as Diodes,
but they do not affect the drawing direction.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Zener().label('Normal')
d += elm.Zener().flip().label('Flip')
d += elm.Zener().reverse().label('Reverse')
.. jupyter-execute::
:hide-code:
d.draw()
Drawing State
-------------
The :py:class:`schemdraw.Drawing` maintains a drawing state that includes the current x, y position, stored in the `Drawing.here` attribute as a (x, y) tuple, and drawing direction stored in the `Drawing.theta` attribute.
A LIFO stack of drawing states can be used, via the :py:meth:`schemdraw.Drawing.push` and :py:meth:`schemdraw.Drawing.pop` method,
for situations when it's useful to save the drawing state and come back to it later.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 4,10
d += elm.Inductor()
d += elm.Dot()
print('d.here:', d.here)
d.push() # Save this drawing position/direction for later
d += elm.Capacitor().down() # Go off in another direction temporarily
d += elm.Ground(lead=False)
print('d.here:', d.here)
d.pop() # Return to the pushed position/direction
print('d.here:', d.here)
d += elm.Diode()
d.draw()
Changing the drawing position can be accomplished by calling :py:meth:`schemdraw.Drawing.move` or :py:meth:`schemdraw.Drawing.move_from`.
Drop and Hold Methods
*********************
To place an element without moving the drawing position, use the :py:meth:`schemdraw.elements.Element.hold` method. The element will be placed without changing the drawing state.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.Diode() # Normal placement: drawing position moves to end of element
d += elm.Dot().color('red')
d.here = (0, -1)
d += elm.Diode().hold() # Hold method prevents position from changing
d += elm.Dot().color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
Three-terminal elements do not necessarily leave the drawing position where desired, so after drawing an element, the current drawing position can be set using the :py:meth:`schemdraw.elements.Element.drop` method to specify an anchor at which to place the cursor.
This reduces the need to assign every element to a variable name.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.BjtNpn()
d += elm.Resistor().label('R1')
d.here = (5, 0)
d += elm.BjtNpn().drop('emitter')
d += elm.Resistor().label('R2')
.. jupyter-execute::
:hide-code:
d.draw()
Connecting Elements
-------------------
Typically, the :py:class:`schemdraw.elements.lines.Line` element is used to connect elements together.
More complex line routing requires multiple Line elements.
The :py:class:`schemdraw.elements.lines.Wire` element is used as a shortcut for placing multiple connecting lines at once.
The Wire element connects the start and end points based on its `shape` parameter.
The `k` parameter is used to set the distance before the wire first changes direction.
.. list-table:: Wire Shape Parameters
:widths: 25 50
:header-rows: 1
* - Shape Parameter
- Description
* - `-`
- Direct Line
* - `-\|`
- Horizontal then vertical
* - `\|-`
- Vertical then horizontal
* - `n`
- Vertical-horizontal-vertical (like an n or u)
* - `c`
- Horizontal-vertical-horizontal (like a c or ↄ)
* - `z`
- Horizontal-diagonal-horizontal
* - `N`
- Vertical-diagonal-vertical
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (A := elm.Dot().label('A', halign='right', ofst=(-.1, 0)))
d += (B := elm.Dot().label('B').at((4, 4)))
d += (C := elm.Dot().label('C', ofst=(-.2, 0)).at((7, 4)))
d += (D := elm.Dot().label('D', ofst=(-.2, 0)).at((9, 0)))
d += (E := elm.Dot().label('E', ofst=(-.2, 0)).at((11, 4)))
d += (F := elm.Dot().label('F', ofst=(-.2, 0)).at((13, 0)))
.. jupyter-execute::
d += elm.Wire('-', arrow='->').at(A.center).to(B.center).color('deeppink').label('"-"')
d += elm.Wire('|-', arrow='->').at(A.center).to(B.center).color('mediumblue').label('"|-"')
d += elm.Wire('-|', arrow='->').at(A.center).to(B.center).color('darkseagreen').label('"-|"')
d += elm.Wire('c', k=-1, arrow='->').at(C.center).to(D.center).color('darkorange').label('"c"', halign='left')
d += elm.Wire('n', arrow='->').at(C.center).to(D.center).color('orchid').label('"n"')
d += elm.Wire('N', arrow='->').at(E.center).to(F.center).color('darkred').label('"N"', 'start', ofst=(-.1, -.75))
d += elm.Wire('z', k=.5, arrow='->').at(E.center).to(F.center).color('teal').label('"z"', halign='left', ofst=(0, .5))
.. jupyter-execute::
:hide-code:
d.draw()
Both `Line` and `Wire` elements take an `arrow` parameter, a string specification of arrowhead types at the start and end of the wire. The arrow string may contain "<", ">", for arrowheads, "\|" for an endcap, and "o" for a dot. Some examples are shown below:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Line(arrow='->').label('"->"', 'right')
d += elm.Line(arrow='<-').at((0, -.75)).label('"<-"', 'right')
d += elm.Line(arrow='<->').at((0, -1.5)).label('"<->"', 'right')
d += elm.Line(arrow='|->').at((0, -2.25)).label('"|->"', 'right')
d += elm.Line(arrow='|-o').at((0, -3.0)).label('"|-o"', 'right')
.. jupyter-execute::
:hide-code:
d.draw()
Because dots are used to show connected wires, all two-terminal elements have `dot` and `idot` methods for quickly adding a dot at the end or beginning of the element, respectively.
.. jupyter-execute::
elm.Resistor().dot()
Keyword Arguments
-----------------
All :py:class:`schemdraw.elements.Element` types take keyword arguments that can also be used to set
element properties, partly for historical reasons but also for easy element setup via dictionary unpacking.
The keyword arguments are equivalent to calling the Element setup methods.
The keyword arguments are not validated or type checked, so the chained method interface
described above is recommended for configuring elements.
+--------------------+-------------------------------+
| Keyword Argument | Method Equivalent |
+====================+===============================+
| `d='up'` | `.up()` |
+--------------------+-------------------------------+
| `d='down'` | `.down()` |
+--------------------+-------------------------------+
| `d='left'` | `.left()` |
+--------------------+-------------------------------+
| `d='right'` | `.right()` |
+--------------------+-------------------------------+
| `theta=X` | `.theta(X)` |
+--------------------+-------------------------------+
| `at=X` or `xy=X` | `.at(X)` |
+--------------------+-------------------------------+
| `flip=True` | `.flip()` |
+--------------------+-------------------------------+
| `reverse=True` | `.reverse()` |
+--------------------+-------------------------------+
| `anchor=X` | `.anchor(X)` |
+--------------------+-------------------------------+
| `zoom=X` | `.scale(X)` |
+--------------------+-------------------------------+
| `color=X` | `.color(X)` |
+--------------------+-------------------------------+
| `fill=X` | `.fill(X)` |
+--------------------+-------------------------------+
| `ls=X` | `.linestyle(X)` |
+--------------------+-------------------------------+
| `lw=X` | `.linewidth(X)` |
+--------------------+-------------------------------+
| `zorder=X` | `.zorder(X)` |
+--------------------+-------------------------------+
| `move_cur=False` | `.hold()` |
+--------------------+-------------------------------+
| `label=X` | `.label(X)` |
+--------------------+-------------------------------+
| `botlabel=X` | `.label(X, loc='bottom')` |
+--------------------+-------------------------------+
| `lftlabel=X` | `.label(X, loc='left')` |
+--------------------+-------------------------------+
| `rgtlabel=X` | `.label(X, loc='right')` |
+--------------------+-------------------------------+
| `toplabel=X` | `.label(X, loc='top')` |
+--------------------+-------------------------------+
| `lblloc=X` | `.label(..., loc=X)` |
+--------------------+-------------------------------+
| 0.887552 | 0.699857 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _labels:
Labels
------
Labels are added to elements using the :py:meth:`schemdraw.elements.Element.label` method.
Some unicode utf-8 characters are allowed, such as :code:`'1μF'` and :code:`'1MΩ'` if the character is included in your font set.
Alternatively, full LaTeX math expressions can be rendered when enclosed in `$..$`
For a description of supported math expressions, in the Matplotlib backend see `Matplotlib Mathtext <https://matplotlib.org/stable/tutorials/text/mathtext.html>`_, and the SVG backend refer to the `Ziamath <https://ziamath.readthedocs.io>`_ package.
Subscripts and superscripts are also added using LaTeX math mode, enclosed in `$..$`:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Resistor().label('1MΩ')
d += elm.Capacitor().label('1μF')
d += elm.Capacitor().label(r'$v = \frac{1}{C} \int i dt$')
d += elm.Resistor().at((0, -2)).label('$R_0$')
d += elm.Capacitor().label('$x^2$')
.. jupyter-execute::
:hide-code:
d.draw()
Location
********
The label location is specified with the `loc` parameter to the `label` method.
It can be `left`, `right`, `top`, `bottom`, or the name of a defined anchor within the element.
These directions do not depend on rotation. A label with `loc='left'` is always on the leftmost terminal of the element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.Resistor()
.label('Label') # 'top' is default
.label('Bottom', loc='bottom')
.label('Right', loc='right')
.label('Left', loc='left'))
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be placed near an element anchor by giving the anchor name as the `loc` parameter.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.BjtNpn()
.label('b', loc='base')
.label('c', loc='collector')
.label('e', loc='emitter'))
.. jupyter-execute::
:hide-code:
d.draw()
The :py:meth:`schemdraw.elements.Element.label` method also takes parameters that control the label's rotation, offset, font, alignment, and color.
Label text stays horizontal by default, but may be rotated to the same angle as the element using `rotate=True`, or any angle `X` in degrees with `rotate=X`.
Offsets apply vertically if a float value is given, or in both x and y if a tuple is given.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('no offset')
d += elm.Resistor().label('offset', ofst=1)
d += elm.Resistor().label('offset (x, y)', ofst=(-.6, .2))
d += elm.Resistor().theta(-45).label('no rotate')
d += elm.Resistor().theta(-45).label('rotate', rotate=True)
d += elm.Resistor().theta(45).label('90°', rotate=90)
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be added anywhere using the :py:class:`schemdraw.elements.lines.Label` element. The element itself draws nothing, but labels can be added to it:
.. code-block:: python
elm.Label().label('Hello')
Voltage Labels
**************
A label may also be a list/tuple of strings, which will be evenly-spaced along the length of the element.
This allows for labeling positive and negative along with a component name, for example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label(('–','$V_1$','+')) # Note: using endash U+2013 character
.. jupyter-execute::
:hide-code:
d.draw()
Use the `Gap` element to label voltage across a terminal:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Line().dot(open=True)
d += elm.Gap().label(('–','$V_o$','+'))
d += elm.Line().idot(open=True)
.. jupyter-execute::
:hide-code:
d.draw()
Current Arrow Labels
********************
Current Arrow
^^^^^^^^^^^^^
To label the current through an element, the :py:class:`schemdraw.elements.lines.CurrentLabel` element can be added.
The `at` method of this element can take an Element instance to label, and the
arrow will be placed over the center of that Element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (R1 := elm.Resistor())
d += elm.CurrentLabel().at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
For transistors, the label will follow sensible bias currents by default.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (Q1 := elm.AnalogNFet())
d += elm.CurrentLabel().at(Q1).label('10 µA')
d += (Q2 := elm.AnalogNFet()).at([4,0]).flip().reverse()
d += elm.CurrentLabel().at(Q2).label('10 µA')
.. jupyter-execute::
:hide-code:
d.draw()
Inline Current Arrow
^^^^^^^^^^^^^^^^^^^^
Alternatively, current labels can be drawn inline as arrowheads on the leads of 2-terminal elements using :py:class:`schemdraw.elements.lines.CurrentLabelInline`. Parameters `direction` and `start` control whether the arrow
is shown pointing into or out of the element, and which end to place the arrowhead on.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += elm.CurrentLabelInline(direction='in').at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
Loop Current
^^^^^^^^^^^^
Loop currents can be added using :py:class:`schemdraw.elements.lines.LoopCurrent`, given a list of 4 existing elements surrounding the loop.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += (C1 := elm.Capacitor().down())
d += (D1 := elm.Diode().fill(True).left())
d += (L1 := elm.Inductor().up())
d += elm.LoopCurrent([R1, C1, D1, L1], direction='cw').label('$I_1$')
.. jupyter-execute::
:hide-code:
d.draw()
Alternatively, loop current arrows can be added anywhere with any size using :py:class:`schemdraw.elements.lines.LoopArrow`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (a:=elm.Line().dot())
d += elm.LoopArrow(width=.75, height=.75).at(a.end)
.. jupyter-execute::
:hide-code:
d.draw()
Impedance Arrow Label
^^^^^^^^^^^^^^^^^^^^^
A right-angle arrow label, often used to indicate impedance looking into a node, is added using :py:class:`schemdraw.elements.lines.ZLabel`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R:=elm.RBox().right())
d += elm.ZLabel().at(R).label('$Z_{in}$')
.. jupyter-execute::
:hide-code:
d.draw()
Annotations
***********
To make text and arrow annotations to a schematic, the :py:class:`schemdraw.elements.lines.Annotate` element draws a curvy arrow with label placed at it's end. It is based on the :py:class:`schemdraw.elements.lines.Arc3` element.
The :py:class:`schemdraw.elements.lines.Encircle` and :py:class:`schemdraw.elements.lines.EncircleBox` elements draw an ellipse, or rounded rectangle, surrounding a list of elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(unit=2)
d += (R1 := elm.Resistor().down().label('R1'))
d += (c := elm.Line().right().length(1))
d += (R2 := elm.Resistor().up().label('R2', loc='bottom'))
d += elm.Line().left().length(1)
d += elm.Line().down().at(c.center).length(.75).idot()
d += (R3 := elm.Resistor().down().label('R3'))
d += (R4 := elm.Resistor().down().label('R4'))
.. jupyter-execute::
d += (parallel := elm.Encircle([R1, R2], padx=.8).linestyle('--').linewidth(1).color('red'))
d += (series := elm.Encircle([R3, R4], padx=.8).linestyle('--').linewidth(1).color('blue'))
d += elm.Annotate().at(parallel.NNE).delta(dx=1, dy=1).label('Parallel').color('red')
d += elm.Annotate(th1=0).at(series.ENE).delta(dx=1.5, dy=1).label('Series').color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/labels.rst
|
labels.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _labels:
Labels
------
Labels are added to elements using the :py:meth:`schemdraw.elements.Element.label` method.
Some unicode utf-8 characters are allowed, such as :code:`'1μF'` and :code:`'1MΩ'` if the character is included in your font set.
Alternatively, full LaTeX math expressions can be rendered when enclosed in `$..$`
For a description of supported math expressions, in the Matplotlib backend see `Matplotlib Mathtext <https://matplotlib.org/stable/tutorials/text/mathtext.html>`_, and the SVG backend refer to the `Ziamath <https://ziamath.readthedocs.io>`_ package.
Subscripts and superscripts are also added using LaTeX math mode, enclosed in `$..$`:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Resistor().label('1MΩ')
d += elm.Capacitor().label('1μF')
d += elm.Capacitor().label(r'$v = \frac{1}{C} \int i dt$')
d += elm.Resistor().at((0, -2)).label('$R_0$')
d += elm.Capacitor().label('$x^2$')
.. jupyter-execute::
:hide-code:
d.draw()
Location
********
The label location is specified with the `loc` parameter to the `label` method.
It can be `left`, `right`, `top`, `bottom`, or the name of a defined anchor within the element.
These directions do not depend on rotation. A label with `loc='left'` is always on the leftmost terminal of the element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.Resistor()
.label('Label') # 'top' is default
.label('Bottom', loc='bottom')
.label('Right', loc='right')
.label('Left', loc='left'))
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be placed near an element anchor by giving the anchor name as the `loc` parameter.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.BjtNpn()
.label('b', loc='base')
.label('c', loc='collector')
.label('e', loc='emitter'))
.. jupyter-execute::
:hide-code:
d.draw()
The :py:meth:`schemdraw.elements.Element.label` method also takes parameters that control the label's rotation, offset, font, alignment, and color.
Label text stays horizontal by default, but may be rotated to the same angle as the element using `rotate=True`, or any angle `X` in degrees with `rotate=X`.
Offsets apply vertically if a float value is given, or in both x and y if a tuple is given.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('no offset')
d += elm.Resistor().label('offset', ofst=1)
d += elm.Resistor().label('offset (x, y)', ofst=(-.6, .2))
d += elm.Resistor().theta(-45).label('no rotate')
d += elm.Resistor().theta(-45).label('rotate', rotate=True)
d += elm.Resistor().theta(45).label('90°', rotate=90)
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be added anywhere using the :py:class:`schemdraw.elements.lines.Label` element. The element itself draws nothing, but labels can be added to it:
.. code-block:: python
elm.Label().label('Hello')
Voltage Labels
**************
A label may also be a list/tuple of strings, which will be evenly-spaced along the length of the element.
This allows for labeling positive and negative along with a component name, for example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label(('–','$V_1$','+')) # Note: using endash U+2013 character
.. jupyter-execute::
:hide-code:
d.draw()
Use the `Gap` element to label voltage across a terminal:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Line().dot(open=True)
d += elm.Gap().label(('–','$V_o$','+'))
d += elm.Line().idot(open=True)
.. jupyter-execute::
:hide-code:
d.draw()
Current Arrow Labels
********************
Current Arrow
^^^^^^^^^^^^^
To label the current through an element, the :py:class:`schemdraw.elements.lines.CurrentLabel` element can be added.
The `at` method of this element can take an Element instance to label, and the
arrow will be placed over the center of that Element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (R1 := elm.Resistor())
d += elm.CurrentLabel().at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
For transistors, the label will follow sensible bias currents by default.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (Q1 := elm.AnalogNFet())
d += elm.CurrentLabel().at(Q1).label('10 µA')
d += (Q2 := elm.AnalogNFet()).at([4,0]).flip().reverse()
d += elm.CurrentLabel().at(Q2).label('10 µA')
.. jupyter-execute::
:hide-code:
d.draw()
Inline Current Arrow
^^^^^^^^^^^^^^^^^^^^
Alternatively, current labels can be drawn inline as arrowheads on the leads of 2-terminal elements using :py:class:`schemdraw.elements.lines.CurrentLabelInline`. Parameters `direction` and `start` control whether the arrow
is shown pointing into or out of the element, and which end to place the arrowhead on.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += elm.CurrentLabelInline(direction='in').at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
Loop Current
^^^^^^^^^^^^
Loop currents can be added using :py:class:`schemdraw.elements.lines.LoopCurrent`, given a list of 4 existing elements surrounding the loop.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += (C1 := elm.Capacitor().down())
d += (D1 := elm.Diode().fill(True).left())
d += (L1 := elm.Inductor().up())
d += elm.LoopCurrent([R1, C1, D1, L1], direction='cw').label('$I_1$')
.. jupyter-execute::
:hide-code:
d.draw()
Alternatively, loop current arrows can be added anywhere with any size using :py:class:`schemdraw.elements.lines.LoopArrow`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (a:=elm.Line().dot())
d += elm.LoopArrow(width=.75, height=.75).at(a.end)
.. jupyter-execute::
:hide-code:
d.draw()
Impedance Arrow Label
^^^^^^^^^^^^^^^^^^^^^
A right-angle arrow label, often used to indicate impedance looking into a node, is added using :py:class:`schemdraw.elements.lines.ZLabel`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R:=elm.RBox().right())
d += elm.ZLabel().at(R).label('$Z_{in}$')
.. jupyter-execute::
:hide-code:
d.draw()
Annotations
***********
To make text and arrow annotations to a schematic, the :py:class:`schemdraw.elements.lines.Annotate` element draws a curvy arrow with label placed at it's end. It is based on the :py:class:`schemdraw.elements.lines.Arc3` element.
The :py:class:`schemdraw.elements.lines.Encircle` and :py:class:`schemdraw.elements.lines.EncircleBox` elements draw an ellipse, or rounded rectangle, surrounding a list of elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(unit=2)
d += (R1 := elm.Resistor().down().label('R1'))
d += (c := elm.Line().right().length(1))
d += (R2 := elm.Resistor().up().label('R2', loc='bottom'))
d += elm.Line().left().length(1)
d += elm.Line().down().at(c.center).length(.75).idot()
d += (R3 := elm.Resistor().down().label('R3'))
d += (R4 := elm.Resistor().down().label('R4'))
.. jupyter-execute::
d += (parallel := elm.Encircle([R1, R2], padx=.8).linestyle('--').linewidth(1).color('red'))
d += (series := elm.Encircle([R3, R4], padx=.8).linestyle('--').linewidth(1).color('blue'))
d += elm.Annotate().at(parallel.NNE).delta(dx=1, dy=1).label('Parallel').color('red')
d += elm.Annotate(th1=0).at(series.ENE).delta(dx=1.5, dy=1).label('Series').color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
| 0.884763 | 0.571468 |
.. _backends:
Backends
--------
The backend is the "canvas" on which a schematic is drawn. Schemdraw supports two backends: Matplotlib, and SVG.
Matplotlib Backend
******************
By default, all schematics are drawn on a Matplotlib axis.
A new Matplotlib Figure and Axis will be created, with no frame or borders.
A schematic may be added to an existing Axis by using the :py:meth:`schemdraw.Drawing.draw` method and setting
the `canvas` parameter to an existing Axis instance.
The Matplotlib backend renders text labels as primative lines and arcs rather than text elements by default.
This has the downside that SVG editors, such as Inkscape, cannot perform textual searches on the SVGs.
The upside is that there is no dependence on installed fonts on the hosts that open the SVGs.
To configure Matplotlib to render labels as SVG text elements:
.. code-block:: python
import matplotlib
matplotlib.rcParams['svg.fonttype'] = 'none'
SVG Backend
***********
Schematics can also be drawn on directly to an SVG image backend.
The SVG backend can be enabled for all drawings by calling:
.. code-block:: python
schemdraw.use('svg')
The backend can be changed at any time. Alternatively, the backend can be set individually on each Drawing using the `canvas` parameter:
.. code-block::
with schemdraw.Drawing(canvas='svg') as d:
...
Use additional Python libraries, such as `pycairo <https://cairosvg.org/>`_, to convert the SVG output into other image formats.
Math Text
^^^^^^^^^
The SVG backend has basic math text support, including greek symbols, subscripts, and superscripts.
However, if `ziamath <https://ziamath.readthedocs.io>`_ and `latex2mathml <https://pypi.org/project/latex2mathml/>`_ packages are installed, they will be used for full Latex math support.
The SVG backend can produce searchable-text SVGs by setting:
.. code-block:: python
schemdraw.svgconfig.text = 'text'
However, text mode does not support full Latex compatibility.
To switch back to rendering text as SVG paths:
.. code-block:: python
schemdraw.svgconfig.text = 'path'
Some SVG renderers are not fully compatible with SVG2.0. For better compatibility with SVG1.x, use
.. code-block:: python
schemdraw.svgconfig.svg2 = False
The decimal precision of SVG elements can be set using
.. code-block:: python
schemdraw.svgconfig.precision = 2
Backend Comparison
******************
Reasons to choose the SVG backend include:
- No Matplotlib/Numpy dependency required (huge file size savings if bundling an executable).
- Speed. The SVG backend draws 4-10x faster than Matplotlib, depending on the circuit complexity.
Reasons to use Matplotlib backend:
- To customize the schematic after drawing it by using other Matplotlib functionality.
- To render directly in other, non-SVG, image formats, with no additional code.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/backends.rst
|
backends.rst
|
.. _backends:
Backends
--------
The backend is the "canvas" on which a schematic is drawn. Schemdraw supports two backends: Matplotlib, and SVG.
Matplotlib Backend
******************
By default, all schematics are drawn on a Matplotlib axis.
A new Matplotlib Figure and Axis will be created, with no frame or borders.
A schematic may be added to an existing Axis by using the :py:meth:`schemdraw.Drawing.draw` method and setting
the `canvas` parameter to an existing Axis instance.
The Matplotlib backend renders text labels as primative lines and arcs rather than text elements by default.
This has the downside that SVG editors, such as Inkscape, cannot perform textual searches on the SVGs.
The upside is that there is no dependence on installed fonts on the hosts that open the SVGs.
To configure Matplotlib to render labels as SVG text elements:
.. code-block:: python
import matplotlib
matplotlib.rcParams['svg.fonttype'] = 'none'
SVG Backend
***********
Schematics can also be drawn on directly to an SVG image backend.
The SVG backend can be enabled for all drawings by calling:
.. code-block:: python
schemdraw.use('svg')
The backend can be changed at any time. Alternatively, the backend can be set individually on each Drawing using the `canvas` parameter:
.. code-block::
with schemdraw.Drawing(canvas='svg') as d:
...
Use additional Python libraries, such as `pycairo <https://cairosvg.org/>`_, to convert the SVG output into other image formats.
Math Text
^^^^^^^^^
The SVG backend has basic math text support, including greek symbols, subscripts, and superscripts.
However, if `ziamath <https://ziamath.readthedocs.io>`_ and `latex2mathml <https://pypi.org/project/latex2mathml/>`_ packages are installed, they will be used for full Latex math support.
The SVG backend can produce searchable-text SVGs by setting:
.. code-block:: python
schemdraw.svgconfig.text = 'text'
However, text mode does not support full Latex compatibility.
To switch back to rendering text as SVG paths:
.. code-block:: python
schemdraw.svgconfig.text = 'path'
Some SVG renderers are not fully compatible with SVG2.0. For better compatibility with SVG1.x, use
.. code-block:: python
schemdraw.svgconfig.svg2 = False
The decimal precision of SVG elements can be set using
.. code-block:: python
schemdraw.svgconfig.precision = 2
Backend Comparison
******************
Reasons to choose the SVG backend include:
- No Matplotlib/Numpy dependency required (huge file size savings if bundling an executable).
- Speed. The SVG backend draws 4-10x faster than Matplotlib, depending on the circuit complexity.
Reasons to use Matplotlib backend:
- To customize the schematic after drawing it by using other Matplotlib functionality.
- To render directly in other, non-SVG, image formats, with no additional code.
| 0.902785 | 0.630145 |
Getting Started
===============
Installation
------------
schemdraw can be installed from pip using
.. code-block:: bash
pip install schemdraw
or to include optional ``matplotlib`` backend dependencies:
.. code-block:: bash
pip install schemdraw[matplotlib]
To allow the SVG drawing :ref:`backends` to render math expressions,
install the optional `ziamath <https://ziamath.readthedocs.io>`_ dependency with:
.. code-block:: bash
pip install schemdraw[svgmath]
Alternatively, schemdraw can be installed directly by downloading the source and running
.. code-block:: bash
pip install ./
Schemdraw requires Python 3.8 or higher.
Overview
---------
The :py:mod:`schemdraw` module allows for drawing circuit elements.
:py:mod:`schemdraw.elements` contains :ref:`electrical` pre-defined for
use in a drawing. A common import structure is:
.. jupyter-execute::
import schemdraw
import schemdraw.elements as elm
To make a circuit diagram, a :py:class:`schemdraw.Drawing` is created and :py:class:`schemdraw.elements.Element` instances are added to it:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.add(elm.Resistor())
d.add(elm.Capacitor())
d.add(elm.Diode())
The `+=` operator may be used as shorthand notation to add elements to the drawing.
This code is equivalent to the above:
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Capacitor()
d += elm.Diode()
Element placement and other properties and are set using a chained method interface, for example:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
Methods `up`, `down`, `left`, `right` specify the drawing direction, and `label` adds text to the element.
If not specified, elements reuse the same direction from the previous element, and begin where
the previous element ended.
Using the `with` context manager is a convenience, letting the drawing be displayed and saved upon exiting the `with` block. Schematics may also be created simply by assinging a new Drawing instance, but this requires calling `draw()` and/or `save()` explicitly:
.. code-block:: python
d = schemdraw.Drawing()
d += elm.Resistor()
...
d.draw()
d.save('my_circuit.svg')
For full details of placing and stylizing elements, see :ref:`placement`.
and :py:class:`schemdraw.elements.Element`.
In general, parameters that control **what** is drawn are passed to the element itself, and parameters that control **how** things are drawn are set using chained Element methods. For example, to make a polarized Capacitor, pass `polar=True` as an argument to `Capacitor`, but to change the Capacitor's color, use the `.color()` method: `elm.Capacitor(polar=True).color('red')`.
Viewing the Drawing
-------------------
Jupyter
*******
When run in a Jupyter notebook, the schematic will be drawn to the cell output after the `with` block is exited.
If your schematics pop up in an external window, and you are using the Matplotlib backend, set Matplotlib to inline mode before importing schemdraw:
.. code-block:: python
%matplotlib inline
For best results when viewing circuits in the notebook, use a vector figure format, such as svg before importing schemdraw:
.. code-block:: python
%config InlineBackend.figure_format = 'svg'
Python Scripts and GUI/Web apps
*******************************
If run as a Python script, the schematic will be opened in a pop-up window after the `with` block exits.
Add the `show=False` option when creating the Drawing to suppress the window from appearing.
.. code-block:: python
with schemdraw.Drawing(show=False) as d:
...
The raw image data as a bytes array can be obtained by calling `.get_imagedata()` with the after the `with` block exits.
This can be useful for integrating schemdraw into an existing GUI or web application.
.. code-block:: python
with schemdraw.Drawing() as drawing:
...
image_bytes = drawing.get_imagedata('svg')
Headless Servers
****************
When running on a server, sometimes there is no display available.
The code may attempt to open the GUI preview window and fail.
In these cases, try setting the Matplotlib backend to a non-GUI option.
Before importing schemdraw, add these lines to use the Agg backend which does not have a GUI.
Then get the drawing using `d.get_imagedata()`, or `d.save()` to get the image.
.. code-block:: python
import matplotlib
matplotlib.use('Agg') # Set Matplotlib's backend here
Alternatively, use Schemdraw's SVG backend (see :ref:`backends`).
Saving Drawings
---------------
To save the schematic to a file, add the `file` parameter when setting up the Drawing.
The image type is determined from the file extension.
Options include `svg`, `eps`, `png`, `pdf`, and `jpg` when using the Matplotlib backend, and `svg` when using the SVG backend.
A vector format such as `svg` is recommended for best image quality.
.. code-block:: python
with schemdraw.Drawing(file='my_circuit.svg') as d:
...
The Drawing may also be saved using with the :py:meth:`schemdraw.Drawing.save` method.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/start.rst
|
start.rst
|
Getting Started
===============
Installation
------------
schemdraw can be installed from pip using
.. code-block:: bash
pip install schemdraw
or to include optional ``matplotlib`` backend dependencies:
.. code-block:: bash
pip install schemdraw[matplotlib]
To allow the SVG drawing :ref:`backends` to render math expressions,
install the optional `ziamath <https://ziamath.readthedocs.io>`_ dependency with:
.. code-block:: bash
pip install schemdraw[svgmath]
Alternatively, schemdraw can be installed directly by downloading the source and running
.. code-block:: bash
pip install ./
Schemdraw requires Python 3.8 or higher.
Overview
---------
The :py:mod:`schemdraw` module allows for drawing circuit elements.
:py:mod:`schemdraw.elements` contains :ref:`electrical` pre-defined for
use in a drawing. A common import structure is:
.. jupyter-execute::
import schemdraw
import schemdraw.elements as elm
To make a circuit diagram, a :py:class:`schemdraw.Drawing` is created and :py:class:`schemdraw.elements.Element` instances are added to it:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.add(elm.Resistor())
d.add(elm.Capacitor())
d.add(elm.Diode())
The `+=` operator may be used as shorthand notation to add elements to the drawing.
This code is equivalent to the above:
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Capacitor()
d += elm.Diode()
Element placement and other properties and are set using a chained method interface, for example:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
Methods `up`, `down`, `left`, `right` specify the drawing direction, and `label` adds text to the element.
If not specified, elements reuse the same direction from the previous element, and begin where
the previous element ended.
Using the `with` context manager is a convenience, letting the drawing be displayed and saved upon exiting the `with` block. Schematics may also be created simply by assinging a new Drawing instance, but this requires calling `draw()` and/or `save()` explicitly:
.. code-block:: python
d = schemdraw.Drawing()
d += elm.Resistor()
...
d.draw()
d.save('my_circuit.svg')
For full details of placing and stylizing elements, see :ref:`placement`.
and :py:class:`schemdraw.elements.Element`.
In general, parameters that control **what** is drawn are passed to the element itself, and parameters that control **how** things are drawn are set using chained Element methods. For example, to make a polarized Capacitor, pass `polar=True` as an argument to `Capacitor`, but to change the Capacitor's color, use the `.color()` method: `elm.Capacitor(polar=True).color('red')`.
Viewing the Drawing
-------------------
Jupyter
*******
When run in a Jupyter notebook, the schematic will be drawn to the cell output after the `with` block is exited.
If your schematics pop up in an external window, and you are using the Matplotlib backend, set Matplotlib to inline mode before importing schemdraw:
.. code-block:: python
%matplotlib inline
For best results when viewing circuits in the notebook, use a vector figure format, such as svg before importing schemdraw:
.. code-block:: python
%config InlineBackend.figure_format = 'svg'
Python Scripts and GUI/Web apps
*******************************
If run as a Python script, the schematic will be opened in a pop-up window after the `with` block exits.
Add the `show=False` option when creating the Drawing to suppress the window from appearing.
.. code-block:: python
with schemdraw.Drawing(show=False) as d:
...
The raw image data as a bytes array can be obtained by calling `.get_imagedata()` with the after the `with` block exits.
This can be useful for integrating schemdraw into an existing GUI or web application.
.. code-block:: python
with schemdraw.Drawing() as drawing:
...
image_bytes = drawing.get_imagedata('svg')
Headless Servers
****************
When running on a server, sometimes there is no display available.
The code may attempt to open the GUI preview window and fail.
In these cases, try setting the Matplotlib backend to a non-GUI option.
Before importing schemdraw, add these lines to use the Agg backend which does not have a GUI.
Then get the drawing using `d.get_imagedata()`, or `d.save()` to get the image.
.. code-block:: python
import matplotlib
matplotlib.use('Agg') # Set Matplotlib's backend here
Alternatively, use Schemdraw's SVG backend (see :ref:`backends`).
Saving Drawings
---------------
To save the schematic to a file, add the `file` parameter when setting up the Drawing.
The image type is determined from the file extension.
Options include `svg`, `eps`, `png`, `pdf`, and `jpg` when using the Matplotlib backend, and `svg` when using the SVG backend.
A vector format such as `svg` is recommended for best image quality.
.. code-block:: python
with schemdraw.Drawing(file='my_circuit.svg') as d:
...
The Drawing may also be saved using with the :py:meth:`schemdraw.Drawing.save` method.
| 0.953221 | 0.68635 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _styles:
Styling
-------
Style options, such as color, line thickness, and fonts, may be set at the global level (all Schemdraw Drawings), at the Drawing level, or on individual Elements.
Individual Elements
*******************
Element styling methods include `color`, `fill`, `linewidth`, and `linestyle`.
If a style method is not called when creating an Element, its value is obtained from from the drawing or global defaults.
Color and fill parameters accept any named `SVG color <https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg>`_ or a hex color string such as '#6A5ACD'. Linestyle parameters may be '-', '--', ':', or '-.'.
.. jupyter-execute::
:hide-output:
# All elements are blue with lightgray fill unless specified otherwise
d = schemdraw.Drawing(color='blue', fill='lightgray')
d += elm.Diode()
d += elm.Diode().fill('red') # Fill overrides drawing color here
d += elm.Resistor().fill('purple') # Fill has no effect on non-closed elements
d += elm.RBox().linestyle('--').color('orange')
d += elm.Resistor().linewidth(5)
.. jupyter-execute::
:hide-code:
d.draw()
The `label` method also accepts color, font, and fontsize parameters, allowing labels with different style as their elements.
Drawing style
*************
Styles may be applied to an entire drawing using the :py:meth:`schemdraw.Drawing.config` method.
These parameters include color, linewidth, font, fontsize, linestyle, fill, and background color.
Additionally, the `config` method allows specification of the default 2-Terminal element length.
Global style
************
Styles may be applied to every new drawing created by Schemdraw (during the Python session) using :py:meth:`schemdraw.config`, using the same arguments as the Drawing config method.
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.config(lw=1, font='serif')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.config()
Global Element Configuration
****************************
The :py:meth:`schemdraw.elements.Element.style` can be used to configure styles on individual element classes that apply to all Drawings.
It may be used, for example, to fill all Diode elements by default, without requiring the `fill()` method on every Diode instance.
Its argument is a dictionary of {name: Element} class pairs.
Combined with `functools.partial <https://docs.python.org/3/library/functools.html#functools.partial>`_ from the standard library, parameters to elements can be set globally.
For example, the following code fills all Diode elements:
.. jupyter-execute::
:emphasize-lines: 3
from functools import partial
elm.style({'Diode': partial(elm.Diode, fill=True)})
with schemdraw.Drawing() as d:
d += elm.Diode()
d += elm.Diode()
Be careful, though, because the `style` method can overwrite existing elements in the namespace.
U.S. versus European Style
**************************
The main use of :py:meth:`schemdraw.elements.Element.style` is to reconfigure elements in IEEE/U.S. style or IEC/European style.
The `schemdraw.elements.STYLE_IEC` and `schemdraw.elements.STYLE_IEEE` are dictionaries for use in the `style` method to change configuration of various elements that use different standard symbols (resistor, variable resistor, photo resistor, etc.)
To configure IEC/European style, use the `style` method with the `elm.STYLE_IEC` dictionary.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEC)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEEE)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
To see all the elements that change between IEEE and IEC, see :ref:`styledelements`.
Fonts
*****
The font for label text may be set using the `font` parameter, either in the :py:meth:`schemdraw.elements.Element.label` method for a single label, or in :py:meth:`schemdraw.Drawing.config` to set the font for the entire drawing.
The font parameter may be a string containing the name of a font installed in the system fonts path, a path to a TTF font file, or the name of a font family such as "serif" or "sans".
These font options apply whether working in the Matplotlib or SVG backends.
.. code-block:: python
with schemdraw.Drawing() as d:
# Default font
d += elm.RBox().label('R1\n500K')
# Named font in system fonts path
d += elm.RBox().label('R1\n500K', font='Comic Sans MS')
# Path to a TTF file
d += elm.RBox().label('R1\n500K', font='Peralta-Regular.ttf')
# Font family
d += elm.RBox().label('R1\n500K', font='serif')
.. image:: fonts.svg
:alt: Font examples
For typesetting math expressions, the `mathfont` parameter is used.
In the Matplotlib backend, a limited `selection of math fonts <https://matplotlib.org/stable/tutorials/text/mathtext.html#fonts>`_ are available.
With the SVG backend in the `path` text mode, the mathfont parameter may be the path to any TTF file that contains a MATH table (requires `Ziamath <https://ziamath.readthedocs.io>`_).
.. code-block:: python
with schemdraw.Drawing(canvas='svg') as d:
# Default math font
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$').at((0, -2))
# Path to a TTF file with MATH font table (SVG backend only)
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$', mathfont='Asana-Math.ttf')
.. image:: mathfonts.svg
:alt: Math font examples
Themes
******
Schemdraw also supports themeing, to enable dark mode, for example.
The defined themes match those in the `Jupyter Themes <https://github.com/dunovank/jupyter-themes>`_ package:
* default (black on white)
* dark (white on black)
* solarizedd
* solarizedl
* onedork
* oceans16
* monokai
* gruvboxl
* gruvboxd
* grade3
* chesterish
They are enabled using :py:meth:`schemdraw.theme`:
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.theme('monokai')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.theme('default')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/styles.rst
|
styles.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _styles:
Styling
-------
Style options, such as color, line thickness, and fonts, may be set at the global level (all Schemdraw Drawings), at the Drawing level, or on individual Elements.
Individual Elements
*******************
Element styling methods include `color`, `fill`, `linewidth`, and `linestyle`.
If a style method is not called when creating an Element, its value is obtained from from the drawing or global defaults.
Color and fill parameters accept any named `SVG color <https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg>`_ or a hex color string such as '#6A5ACD'. Linestyle parameters may be '-', '--', ':', or '-.'.
.. jupyter-execute::
:hide-output:
# All elements are blue with lightgray fill unless specified otherwise
d = schemdraw.Drawing(color='blue', fill='lightgray')
d += elm.Diode()
d += elm.Diode().fill('red') # Fill overrides drawing color here
d += elm.Resistor().fill('purple') # Fill has no effect on non-closed elements
d += elm.RBox().linestyle('--').color('orange')
d += elm.Resistor().linewidth(5)
.. jupyter-execute::
:hide-code:
d.draw()
The `label` method also accepts color, font, and fontsize parameters, allowing labels with different style as their elements.
Drawing style
*************
Styles may be applied to an entire drawing using the :py:meth:`schemdraw.Drawing.config` method.
These parameters include color, linewidth, font, fontsize, linestyle, fill, and background color.
Additionally, the `config` method allows specification of the default 2-Terminal element length.
Global style
************
Styles may be applied to every new drawing created by Schemdraw (during the Python session) using :py:meth:`schemdraw.config`, using the same arguments as the Drawing config method.
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.config(lw=1, font='serif')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.config()
Global Element Configuration
****************************
The :py:meth:`schemdraw.elements.Element.style` can be used to configure styles on individual element classes that apply to all Drawings.
It may be used, for example, to fill all Diode elements by default, without requiring the `fill()` method on every Diode instance.
Its argument is a dictionary of {name: Element} class pairs.
Combined with `functools.partial <https://docs.python.org/3/library/functools.html#functools.partial>`_ from the standard library, parameters to elements can be set globally.
For example, the following code fills all Diode elements:
.. jupyter-execute::
:emphasize-lines: 3
from functools import partial
elm.style({'Diode': partial(elm.Diode, fill=True)})
with schemdraw.Drawing() as d:
d += elm.Diode()
d += elm.Diode()
Be careful, though, because the `style` method can overwrite existing elements in the namespace.
U.S. versus European Style
**************************
The main use of :py:meth:`schemdraw.elements.Element.style` is to reconfigure elements in IEEE/U.S. style or IEC/European style.
The `schemdraw.elements.STYLE_IEC` and `schemdraw.elements.STYLE_IEEE` are dictionaries for use in the `style` method to change configuration of various elements that use different standard symbols (resistor, variable resistor, photo resistor, etc.)
To configure IEC/European style, use the `style` method with the `elm.STYLE_IEC` dictionary.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEC)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEEE)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
To see all the elements that change between IEEE and IEC, see :ref:`styledelements`.
Fonts
*****
The font for label text may be set using the `font` parameter, either in the :py:meth:`schemdraw.elements.Element.label` method for a single label, or in :py:meth:`schemdraw.Drawing.config` to set the font for the entire drawing.
The font parameter may be a string containing the name of a font installed in the system fonts path, a path to a TTF font file, or the name of a font family such as "serif" or "sans".
These font options apply whether working in the Matplotlib or SVG backends.
.. code-block:: python
with schemdraw.Drawing() as d:
# Default font
d += elm.RBox().label('R1\n500K')
# Named font in system fonts path
d += elm.RBox().label('R1\n500K', font='Comic Sans MS')
# Path to a TTF file
d += elm.RBox().label('R1\n500K', font='Peralta-Regular.ttf')
# Font family
d += elm.RBox().label('R1\n500K', font='serif')
.. image:: fonts.svg
:alt: Font examples
For typesetting math expressions, the `mathfont` parameter is used.
In the Matplotlib backend, a limited `selection of math fonts <https://matplotlib.org/stable/tutorials/text/mathtext.html#fonts>`_ are available.
With the SVG backend in the `path` text mode, the mathfont parameter may be the path to any TTF file that contains a MATH table (requires `Ziamath <https://ziamath.readthedocs.io>`_).
.. code-block:: python
with schemdraw.Drawing(canvas='svg') as d:
# Default math font
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$').at((0, -2))
# Path to a TTF file with MATH font table (SVG backend only)
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$', mathfont='Asana-Math.ttf')
.. image:: mathfonts.svg
:alt: Math font examples
Themes
******
Schemdraw also supports themeing, to enable dark mode, for example.
The defined themes match those in the `Jupyter Themes <https://github.com/dunovank/jupyter-themes>`_ package:
* default (black on white)
* dark (white on black)
* solarizedd
* solarizedl
* onedork
* oceans16
* monokai
* gruvboxl
* gruvboxd
* grade3
* chesterish
They are enabled using :py:meth:`schemdraw.theme`:
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.theme('monokai')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.theme('default')
| 0.900814 | 0.545467 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _placement:
Placing Elements
================
Elements are added to a Drawing using the `add` method or `+=` shortcut.
The Drawing maintains a current position and direction, such that the default placement of the next element
will start at the end of the previous element, going in the same direction.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor()
d += elm.Diode()
If a direction method (`up`, `down`, `left`, `right`) is added to an element, the element is rotated in that direction, and future elements take the same direction:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor().up()
d += elm.Diode()
The `theta` method can be used to specify any rotation angle in degrees.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().theta(20).label('R1')
d += elm.Resistor().label('R2') # Takes position and direction from R1
.. jupyter-execute::
:hide-code:
d.draw()
Anchors
-------
All elements have a set of predefined "anchor" positions within the element.
For example, a bipolar transistor has `base`, `emitter`, and `collector` anchors.
All two-terminal elements have anchors named `start`, `center`, and `end`.
The docstring for each element lists the available anchors.
Once an element is added to the drawing, all its anchor positions will be added as attributes to the element object, so the base position of transistor assigned to variable `Q` may be accessed via `Q.base`.
Rather than working in absolute (x, y) coordinates, anchors can be used to set the position of new elements.
Using the `at` method, one element can be placed starting on the anchor of another element.
For example, to draw an opamp and place a resistor on the output, store the Opamp instance to a variable. Then call the `at` method of the new element passing the `Opamp.out` anchor. After the resistor is drawn, the current drawing position is moved to the endpoint of the resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
opamp = d.add(elm.Opamp())
d.add(elm.Resistor().right().at(opamp.out))
.. jupyter-execute::
:hide-code:
d.draw()
Python's walrus operator provides a convenient shorthand notation for adding an element using `+=` and storing it at the same time.
The above code can be written equivalently as:
.. code-block:: python
d += (opamp := elm.Opamp())
d += elm.Resistor().right().at(opamp.out)
The second purpose for anchors is aligning new elements with respect to existing elements.
Suppose a resistor has just been placed, and now an Opamp should be connected to the resistor.
The `anchor` method tells the Drawing which input on the Opamp should align with resistor.
Here, an Opamp is placed at the end of a resistor, connected to the opamp's `in1` anchor (the inverting input).
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R1')
d += elm.Opamp().anchor('in1')
.. jupyter-execute::
:hide-code:
d.draw()
Compared to anchoring the opamp at `in2` (the noninverting input):
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R2')
d += elm.Opamp().anchor('in2')
.. jupyter-execute::
:hide-code:
d.draw()
Dimensions
----------
The inner zig-zag portion of a resistor has length of 1 unit, while the default lead extensions are 1 unit on each side,
making the default total resistor length 3 units.
Placement methods such as `at` and `to` accept a tuple of (x, y) position in these units.
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((1, .7)).to((2, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((3, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
This default 2-terminal length can be changed using the `unit` parameter to the :py:meth:`schemdraw.Drawing.config` method:
.. code-block:: python
with schemdraw.Drawing() as d:
d.config(unit=2)
...
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d.config(unit=2)
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((.5, .7)).to((1.5, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((2, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
Two-Terminal Elements
---------------------
In Schemdraw, a "Two-Terminal Element" is any element that can grow to fill a given length (this includes elements such as the Potentiometer, even though it electrically has three terminals).
All two-terminal elements subclass :py:class:`schemdraw.elements.Element2Term`.
They have some additional methods for setting placement and length.
The `length` method sets an exact length for a two-terminal element. Alternatively, the `up`, `down`, `left`, and `right` methods on two-terminal elements take a length parameter.
.. jupyter-execute::
:emphasize-lines: 5
with schemdraw.Drawing() as d:
d += elm.Dot()
d += elm.Resistor()
d += elm.Dot()
d += elm.Diode().length(6)
d += elm.Dot()
The `to` method will set an exact endpoint for a 2-terminal element.
The starting point is still the ending location of the previous element.
Notice the Diode is stretched longer than the standard element length in order to fill the diagonal distance.
.. jupyter-execute::
:emphasize-lines: 4
with schemdraw.Drawing() as d:
R = d.add(elm.Resistor())
C = d.add(elm.Capacitor().up())
Q = d.add(elm.Diode().to(R.start))
The `tox` and `toy` methods are useful for placing 2-terminal elements to "close the loop", without requiring an exact length.
They extend the element horizontally or vertically to the x- or y- coordinate of the anchor given as the argument.
These methods automatically change the drawing direction.
Here, the Line element does not need to specify an exact length to fill the space and connect back with the Source.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 9
d += (C := elm.Capacitor())
d += elm.Diode()
d += elm.Line().down()
# Now we want to close the loop, but can use `tox`
# to avoid having to know exactly how far to go.
# The Line will extend horizontally to the same x-position
# as the Capacitor's `start` anchor.
d += elm.Line().tox(C.start)
# Now close the loop by relying on the fact that all
# two-terminal elements (including Source and Line)
# are the same length by default
d += elm.Source().up()
.. jupyter-execute::
:hide-code:
d.draw()
Finally, exact endpoints can also be specified using the `endpoints` method.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 5
d += (R := elm.Resistor())
d += (Q := elm.Diode().down(6))
d += elm.Line().tox(R.start)
d += elm.Capacitor().toy(R.start)
d += elm.SourceV().endpoints(Q.end, R.start)
.. jupyter-execute::
:hide-code:
d.draw()
Orientation
-----------
The `flip` and `reverse` methods are useful for changing orientation of directional elements such as Diodes,
but they do not affect the drawing direction.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Zener().label('Normal')
d += elm.Zener().flip().label('Flip')
d += elm.Zener().reverse().label('Reverse')
.. jupyter-execute::
:hide-code:
d.draw()
Drawing State
-------------
The :py:class:`schemdraw.Drawing` maintains a drawing state that includes the current x, y position, stored in the `Drawing.here` attribute as a (x, y) tuple, and drawing direction stored in the `Drawing.theta` attribute.
A LIFO stack of drawing states can be used, via the :py:meth:`schemdraw.Drawing.push` and :py:meth:`schemdraw.Drawing.pop` method,
for situations when it's useful to save the drawing state and come back to it later.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 4,10
d += elm.Inductor()
d += elm.Dot()
print('d.here:', d.here)
d.push() # Save this drawing position/direction for later
d += elm.Capacitor().down() # Go off in another direction temporarily
d += elm.Ground(lead=False)
print('d.here:', d.here)
d.pop() # Return to the pushed position/direction
print('d.here:', d.here)
d += elm.Diode()
d.draw()
Changing the drawing position can be accomplished by calling :py:meth:`schemdraw.Drawing.move` or :py:meth:`schemdraw.Drawing.move_from`.
Drop and Hold Methods
*********************
To place an element without moving the drawing position, use the :py:meth:`schemdraw.elements.Element.hold` method. The element will be placed without changing the drawing state.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.Diode() # Normal placement: drawing position moves to end of element
d += elm.Dot().color('red')
d.here = (0, -1)
d += elm.Diode().hold() # Hold method prevents position from changing
d += elm.Dot().color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
Three-terminal elements do not necessarily leave the drawing position where desired, so after drawing an element, the current drawing position can be set using the :py:meth:`schemdraw.elements.Element.drop` method to specify an anchor at which to place the cursor.
This reduces the need to assign every element to a variable name.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.BjtNpn()
d += elm.Resistor().label('R1')
d.here = (5, 0)
d += elm.BjtNpn().drop('emitter')
d += elm.Resistor().label('R2')
.. jupyter-execute::
:hide-code:
d.draw()
Connecting Elements
-------------------
Typically, the :py:class:`schemdraw.elements.lines.Line` element is used to connect elements together.
More complex line routing requires multiple Line elements.
The :py:class:`schemdraw.elements.lines.Wire` element is used as a shortcut for placing multiple connecting lines at once.
The Wire element connects the start and end points based on its `shape` parameter.
The `k` parameter is used to set the distance before the wire first changes direction.
.. list-table:: Wire Shape Parameters
:widths: 25 50
:header-rows: 1
* - Shape Parameter
- Description
* - `-`
- Direct Line
* - `-\|`
- Horizontal then vertical
* - `\|-`
- Vertical then horizontal
* - `n`
- Vertical-horizontal-vertical (like an n or u)
* - `c`
- Horizontal-vertical-horizontal (like a c or ↄ)
* - `z`
- Horizontal-diagonal-horizontal
* - `N`
- Vertical-diagonal-vertical
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (A := elm.Dot().label('A', halign='right', ofst=(-.1, 0)))
d += (B := elm.Dot().label('B').at((4, 4)))
d += (C := elm.Dot().label('C', ofst=(-.2, 0)).at((7, 4)))
d += (D := elm.Dot().label('D', ofst=(-.2, 0)).at((9, 0)))
d += (E := elm.Dot().label('E', ofst=(-.2, 0)).at((11, 4)))
d += (F := elm.Dot().label('F', ofst=(-.2, 0)).at((13, 0)))
.. jupyter-execute::
d += elm.Wire('-', arrow='->').at(A.center).to(B.center).color('deeppink').label('"-"')
d += elm.Wire('|-', arrow='->').at(A.center).to(B.center).color('mediumblue').label('"|-"')
d += elm.Wire('-|', arrow='->').at(A.center).to(B.center).color('darkseagreen').label('"-|"')
d += elm.Wire('c', k=-1, arrow='->').at(C.center).to(D.center).color('darkorange').label('"c"', halign='left')
d += elm.Wire('n', arrow='->').at(C.center).to(D.center).color('orchid').label('"n"')
d += elm.Wire('N', arrow='->').at(E.center).to(F.center).color('darkred').label('"N"', 'start', ofst=(-.1, -.75))
d += elm.Wire('z', k=.5, arrow='->').at(E.center).to(F.center).color('teal').label('"z"', halign='left', ofst=(0, .5))
.. jupyter-execute::
:hide-code:
d.draw()
Both `Line` and `Wire` elements take an `arrow` parameter, a string specification of arrowhead types at the start and end of the wire. The arrow string may contain "<", ">", for arrowheads, "\|" for an endcap, and "o" for a dot. Some examples are shown below:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Line(arrow='->').label('"->"', 'right')
d += elm.Line(arrow='<-').at((0, -.75)).label('"<-"', 'right')
d += elm.Line(arrow='<->').at((0, -1.5)).label('"<->"', 'right')
d += elm.Line(arrow='|->').at((0, -2.25)).label('"|->"', 'right')
d += elm.Line(arrow='|-o').at((0, -3.0)).label('"|-o"', 'right')
.. jupyter-execute::
:hide-code:
d.draw()
Because dots are used to show connected wires, all two-terminal elements have `dot` and `idot` methods for quickly adding a dot at the end or beginning of the element, respectively.
.. jupyter-execute::
elm.Resistor().dot()
Keyword Arguments
-----------------
All :py:class:`schemdraw.elements.Element` types take keyword arguments that can also be used to set
element properties, partly for historical reasons but also for easy element setup via dictionary unpacking.
The keyword arguments are equivalent to calling the Element setup methods.
The keyword arguments are not validated or type checked, so the chained method interface
described above is recommended for configuring elements.
+--------------------+-------------------------------+
| Keyword Argument | Method Equivalent |
+====================+===============================+
| `d='up'` | `.up()` |
+--------------------+-------------------------------+
| `d='down'` | `.down()` |
+--------------------+-------------------------------+
| `d='left'` | `.left()` |
+--------------------+-------------------------------+
| `d='right'` | `.right()` |
+--------------------+-------------------------------+
| `theta=X` | `.theta(X)` |
+--------------------+-------------------------------+
| `at=X` or `xy=X` | `.at(X)` |
+--------------------+-------------------------------+
| `flip=True` | `.flip()` |
+--------------------+-------------------------------+
| `reverse=True` | `.reverse()` |
+--------------------+-------------------------------+
| `anchor=X` | `.anchor(X)` |
+--------------------+-------------------------------+
| `zoom=X` | `.scale(X)` |
+--------------------+-------------------------------+
| `color=X` | `.color(X)` |
+--------------------+-------------------------------+
| `fill=X` | `.fill(X)` |
+--------------------+-------------------------------+
| `ls=X` | `.linestyle(X)` |
+--------------------+-------------------------------+
| `lw=X` | `.linewidth(X)` |
+--------------------+-------------------------------+
| `zorder=X` | `.zorder(X)` |
+--------------------+-------------------------------+
| `move_cur=False` | `.hold()` |
+--------------------+-------------------------------+
| `label=X` | `.label(X)` |
+--------------------+-------------------------------+
| `botlabel=X` | `.label(X, loc='bottom')` |
+--------------------+-------------------------------+
| `lftlabel=X` | `.label(X, loc='left')` |
+--------------------+-------------------------------+
| `rgtlabel=X` | `.label(X, loc='right')` |
+--------------------+-------------------------------+
| `toplabel=X` | `.label(X, loc='top')` |
+--------------------+-------------------------------+
| `lblloc=X` | `.label(..., loc=X)` |
+--------------------+-------------------------------+
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/placement-checkpoint.rst
|
placement-checkpoint.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _placement:
Placing Elements
================
Elements are added to a Drawing using the `add` method or `+=` shortcut.
The Drawing maintains a current position and direction, such that the default placement of the next element
will start at the end of the previous element, going in the same direction.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor()
d += elm.Diode()
If a direction method (`up`, `down`, `left`, `right`) is added to an element, the element is rotated in that direction, and future elements take the same direction:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Capacitor()
d += elm.Resistor().up()
d += elm.Diode()
The `theta` method can be used to specify any rotation angle in degrees.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().theta(20).label('R1')
d += elm.Resistor().label('R2') # Takes position and direction from R1
.. jupyter-execute::
:hide-code:
d.draw()
Anchors
-------
All elements have a set of predefined "anchor" positions within the element.
For example, a bipolar transistor has `base`, `emitter`, and `collector` anchors.
All two-terminal elements have anchors named `start`, `center`, and `end`.
The docstring for each element lists the available anchors.
Once an element is added to the drawing, all its anchor positions will be added as attributes to the element object, so the base position of transistor assigned to variable `Q` may be accessed via `Q.base`.
Rather than working in absolute (x, y) coordinates, anchors can be used to set the position of new elements.
Using the `at` method, one element can be placed starting on the anchor of another element.
For example, to draw an opamp and place a resistor on the output, store the Opamp instance to a variable. Then call the `at` method of the new element passing the `Opamp.out` anchor. After the resistor is drawn, the current drawing position is moved to the endpoint of the resistor.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
opamp = d.add(elm.Opamp())
d.add(elm.Resistor().right().at(opamp.out))
.. jupyter-execute::
:hide-code:
d.draw()
Python's walrus operator provides a convenient shorthand notation for adding an element using `+=` and storing it at the same time.
The above code can be written equivalently as:
.. code-block:: python
d += (opamp := elm.Opamp())
d += elm.Resistor().right().at(opamp.out)
The second purpose for anchors is aligning new elements with respect to existing elements.
Suppose a resistor has just been placed, and now an Opamp should be connected to the resistor.
The `anchor` method tells the Drawing which input on the Opamp should align with resistor.
Here, an Opamp is placed at the end of a resistor, connected to the opamp's `in1` anchor (the inverting input).
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R1')
d += elm.Opamp().anchor('in1')
.. jupyter-execute::
:hide-code:
d.draw()
Compared to anchoring the opamp at `in2` (the noninverting input):
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('R2')
d += elm.Opamp().anchor('in2')
.. jupyter-execute::
:hide-code:
d.draw()
Dimensions
----------
The inner zig-zag portion of a resistor has length of 1 unit, while the default lead extensions are 1 unit on each side,
making the default total resistor length 3 units.
Placement methods such as `at` and `to` accept a tuple of (x, y) position in these units.
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((1, .7)).to((2, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((3, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
This default 2-terminal length can be changed using the `unit` parameter to the :py:meth:`schemdraw.Drawing.config` method:
.. code-block:: python
with schemdraw.Drawing() as d:
d.config(unit=2)
...
.. jupyter-execute::
:hide-code:
with schemdraw.Drawing() as d:
d.config(unit=2)
d += elm.Resistor()
d += elm.Line(arrow='|-|').at((.5, .7)).to((1.5, .7)).label('1.0').color('royalblue')
d += elm.Line(arrow='|-|').at((0, -.7)).to((2, -.7)).label('Drawing.unit', 'bottom').color('royalblue')
Two-Terminal Elements
---------------------
In Schemdraw, a "Two-Terminal Element" is any element that can grow to fill a given length (this includes elements such as the Potentiometer, even though it electrically has three terminals).
All two-terminal elements subclass :py:class:`schemdraw.elements.Element2Term`.
They have some additional methods for setting placement and length.
The `length` method sets an exact length for a two-terminal element. Alternatively, the `up`, `down`, `left`, and `right` methods on two-terminal elements take a length parameter.
.. jupyter-execute::
:emphasize-lines: 5
with schemdraw.Drawing() as d:
d += elm.Dot()
d += elm.Resistor()
d += elm.Dot()
d += elm.Diode().length(6)
d += elm.Dot()
The `to` method will set an exact endpoint for a 2-terminal element.
The starting point is still the ending location of the previous element.
Notice the Diode is stretched longer than the standard element length in order to fill the diagonal distance.
.. jupyter-execute::
:emphasize-lines: 4
with schemdraw.Drawing() as d:
R = d.add(elm.Resistor())
C = d.add(elm.Capacitor().up())
Q = d.add(elm.Diode().to(R.start))
The `tox` and `toy` methods are useful for placing 2-terminal elements to "close the loop", without requiring an exact length.
They extend the element horizontally or vertically to the x- or y- coordinate of the anchor given as the argument.
These methods automatically change the drawing direction.
Here, the Line element does not need to specify an exact length to fill the space and connect back with the Source.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 9
d += (C := elm.Capacitor())
d += elm.Diode()
d += elm.Line().down()
# Now we want to close the loop, but can use `tox`
# to avoid having to know exactly how far to go.
# The Line will extend horizontally to the same x-position
# as the Capacitor's `start` anchor.
d += elm.Line().tox(C.start)
# Now close the loop by relying on the fact that all
# two-terminal elements (including Source and Line)
# are the same length by default
d += elm.Source().up()
.. jupyter-execute::
:hide-code:
d.draw()
Finally, exact endpoints can also be specified using the `endpoints` method.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
:emphasize-lines: 5
d += (R := elm.Resistor())
d += (Q := elm.Diode().down(6))
d += elm.Line().tox(R.start)
d += elm.Capacitor().toy(R.start)
d += elm.SourceV().endpoints(Q.end, R.start)
.. jupyter-execute::
:hide-code:
d.draw()
Orientation
-----------
The `flip` and `reverse` methods are useful for changing orientation of directional elements such as Diodes,
but they do not affect the drawing direction.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Zener().label('Normal')
d += elm.Zener().flip().label('Flip')
d += elm.Zener().reverse().label('Reverse')
.. jupyter-execute::
:hide-code:
d.draw()
Drawing State
-------------
The :py:class:`schemdraw.Drawing` maintains a drawing state that includes the current x, y position, stored in the `Drawing.here` attribute as a (x, y) tuple, and drawing direction stored in the `Drawing.theta` attribute.
A LIFO stack of drawing states can be used, via the :py:meth:`schemdraw.Drawing.push` and :py:meth:`schemdraw.Drawing.pop` method,
for situations when it's useful to save the drawing state and come back to it later.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 4,10
d += elm.Inductor()
d += elm.Dot()
print('d.here:', d.here)
d.push() # Save this drawing position/direction for later
d += elm.Capacitor().down() # Go off in another direction temporarily
d += elm.Ground(lead=False)
print('d.here:', d.here)
d.pop() # Return to the pushed position/direction
print('d.here:', d.here)
d += elm.Diode()
d.draw()
Changing the drawing position can be accomplished by calling :py:meth:`schemdraw.Drawing.move` or :py:meth:`schemdraw.Drawing.move_from`.
Drop and Hold Methods
*********************
To place an element without moving the drawing position, use the :py:meth:`schemdraw.elements.Element.hold` method. The element will be placed without changing the drawing state.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.Diode() # Normal placement: drawing position moves to end of element
d += elm.Dot().color('red')
d.here = (0, -1)
d += elm.Diode().hold() # Hold method prevents position from changing
d += elm.Dot().color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
Three-terminal elements do not necessarily leave the drawing position where desired, so after drawing an element, the current drawing position can be set using the :py:meth:`schemdraw.elements.Element.drop` method to specify an anchor at which to place the cursor.
This reduces the need to assign every element to a variable name.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 5
d += elm.BjtNpn()
d += elm.Resistor().label('R1')
d.here = (5, 0)
d += elm.BjtNpn().drop('emitter')
d += elm.Resistor().label('R2')
.. jupyter-execute::
:hide-code:
d.draw()
Connecting Elements
-------------------
Typically, the :py:class:`schemdraw.elements.lines.Line` element is used to connect elements together.
More complex line routing requires multiple Line elements.
The :py:class:`schemdraw.elements.lines.Wire` element is used as a shortcut for placing multiple connecting lines at once.
The Wire element connects the start and end points based on its `shape` parameter.
The `k` parameter is used to set the distance before the wire first changes direction.
.. list-table:: Wire Shape Parameters
:widths: 25 50
:header-rows: 1
* - Shape Parameter
- Description
* - `-`
- Direct Line
* - `-\|`
- Horizontal then vertical
* - `\|-`
- Vertical then horizontal
* - `n`
- Vertical-horizontal-vertical (like an n or u)
* - `c`
- Horizontal-vertical-horizontal (like a c or ↄ)
* - `z`
- Horizontal-diagonal-horizontal
* - `N`
- Vertical-diagonal-vertical
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
d += (A := elm.Dot().label('A', halign='right', ofst=(-.1, 0)))
d += (B := elm.Dot().label('B').at((4, 4)))
d += (C := elm.Dot().label('C', ofst=(-.2, 0)).at((7, 4)))
d += (D := elm.Dot().label('D', ofst=(-.2, 0)).at((9, 0)))
d += (E := elm.Dot().label('E', ofst=(-.2, 0)).at((11, 4)))
d += (F := elm.Dot().label('F', ofst=(-.2, 0)).at((13, 0)))
.. jupyter-execute::
d += elm.Wire('-', arrow='->').at(A.center).to(B.center).color('deeppink').label('"-"')
d += elm.Wire('|-', arrow='->').at(A.center).to(B.center).color('mediumblue').label('"|-"')
d += elm.Wire('-|', arrow='->').at(A.center).to(B.center).color('darkseagreen').label('"-|"')
d += elm.Wire('c', k=-1, arrow='->').at(C.center).to(D.center).color('darkorange').label('"c"', halign='left')
d += elm.Wire('n', arrow='->').at(C.center).to(D.center).color('orchid').label('"n"')
d += elm.Wire('N', arrow='->').at(E.center).to(F.center).color('darkred').label('"N"', 'start', ofst=(-.1, -.75))
d += elm.Wire('z', k=.5, arrow='->').at(E.center).to(F.center).color('teal').label('"z"', halign='left', ofst=(0, .5))
.. jupyter-execute::
:hide-code:
d.draw()
Both `Line` and `Wire` elements take an `arrow` parameter, a string specification of arrowhead types at the start and end of the wire. The arrow string may contain "<", ">", for arrowheads, "\|" for an endcap, and "o" for a dot. Some examples are shown below:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Line(arrow='->').label('"->"', 'right')
d += elm.Line(arrow='<-').at((0, -.75)).label('"<-"', 'right')
d += elm.Line(arrow='<->').at((0, -1.5)).label('"<->"', 'right')
d += elm.Line(arrow='|->').at((0, -2.25)).label('"|->"', 'right')
d += elm.Line(arrow='|-o').at((0, -3.0)).label('"|-o"', 'right')
.. jupyter-execute::
:hide-code:
d.draw()
Because dots are used to show connected wires, all two-terminal elements have `dot` and `idot` methods for quickly adding a dot at the end or beginning of the element, respectively.
.. jupyter-execute::
elm.Resistor().dot()
Keyword Arguments
-----------------
All :py:class:`schemdraw.elements.Element` types take keyword arguments that can also be used to set
element properties, partly for historical reasons but also for easy element setup via dictionary unpacking.
The keyword arguments are equivalent to calling the Element setup methods.
The keyword arguments are not validated or type checked, so the chained method interface
described above is recommended for configuring elements.
+--------------------+-------------------------------+
| Keyword Argument | Method Equivalent |
+====================+===============================+
| `d='up'` | `.up()` |
+--------------------+-------------------------------+
| `d='down'` | `.down()` |
+--------------------+-------------------------------+
| `d='left'` | `.left()` |
+--------------------+-------------------------------+
| `d='right'` | `.right()` |
+--------------------+-------------------------------+
| `theta=X` | `.theta(X)` |
+--------------------+-------------------------------+
| `at=X` or `xy=X` | `.at(X)` |
+--------------------+-------------------------------+
| `flip=True` | `.flip()` |
+--------------------+-------------------------------+
| `reverse=True` | `.reverse()` |
+--------------------+-------------------------------+
| `anchor=X` | `.anchor(X)` |
+--------------------+-------------------------------+
| `zoom=X` | `.scale(X)` |
+--------------------+-------------------------------+
| `color=X` | `.color(X)` |
+--------------------+-------------------------------+
| `fill=X` | `.fill(X)` |
+--------------------+-------------------------------+
| `ls=X` | `.linestyle(X)` |
+--------------------+-------------------------------+
| `lw=X` | `.linewidth(X)` |
+--------------------+-------------------------------+
| `zorder=X` | `.zorder(X)` |
+--------------------+-------------------------------+
| `move_cur=False` | `.hold()` |
+--------------------+-------------------------------+
| `label=X` | `.label(X)` |
+--------------------+-------------------------------+
| `botlabel=X` | `.label(X, loc='bottom')` |
+--------------------+-------------------------------+
| `lftlabel=X` | `.label(X, loc='left')` |
+--------------------+-------------------------------+
| `rgtlabel=X` | `.label(X, loc='right')` |
+--------------------+-------------------------------+
| `toplabel=X` | `.label(X, loc='top')` |
+--------------------+-------------------------------+
| `lblloc=X` | `.label(..., loc=X)` |
+--------------------+-------------------------------+
| 0.887552 | 0.699857 |
Customizing Elements
====================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
from schemdraw.segments import *
Grouping Elements
-----------------
If a set of circuit elements are to be reused multiple times, they can be grouped into a single element.
Create and populate a drawing, but set `show=False`.
Instead, use the Drawing to create a new :py:class:`schemdraw.elements.ElementDrawing`, which converts the drawing into an element instance
to add to other drawings.
.. jupyter-execute::
:emphasize-lines: 8-10
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2: # Add a second drawing
for i in range(3):
d2 += elm.ElementDrawing(d1) # Add the first drawing to it 3 times
.. _customelements:
Defining custom elements
------------------------
All elements are subclasses of :py:class:`schemdraw.elements.Element` or :py:class:`schemdraw.elements.Element2Term`.
For elements consisting of several other already-defined elements (like a relay), :py:class:`schemdraw.elements.compound.ElementCompound` can be used for easy combining of multiple elements.
Subclasses only need to define the `__init__` method in order to add lines, shapes, and text to the new element, all of which are defined using :py:class:`schemdraw.segments.Segment` classes. New Segments should be appended to the `Element.segments` attribute list.
Coordinates are all defined in element cooridnates, where the element begins
at (0, 0) and is drawn from left to right.
The drawing engine will rotate and translate the element to its final position, and for two-terminal
elements deriving from Element2Term, will add lead extensions to the correct length depending
on the element's placement parameters.
Therefore elements deriving from Element2Term should not define the lead extensions
(e.g. a Resistor only defines the zig-zag portion).
A standard resistor is 1 drawing unit long, and with default lead extension will become 3 units long.
Segments include :py:class:`schemdraw.segments.Segment`, :py:class:`schemdraw.segments.SegmentPoly`,
:py:class:`schemdraw.segments.SegmentCircle`, :py:class:`schemdraw.segments.SegmentArc`, :py:class:`schemdraw.segments.SegmentText`, and :py:class:`schemdraw.segments.SegmentBezier`.
The subclassed `Element.__init__` method can be defined with extra parameters
to help define the element options.
In addition to the list of Segments, any named anchors and other parameters should be specified.
Anchors should be added to the `Element.anchors` dictionary as {name: (x, y)} key/value pairs.
The Element instance maintains its own parameters dictionary in `Element.params` that override the default drawing parameters.
Parameters are resolved by a ChainMap of user arguments to the `Element` instance, the `Element.params` attribute, then the `schemdraw.Drawing` parameters, in that order.
A common use of setting `Element.params` in the setup function is to change the default position of text labels, for example Transistor elements apply labels on the right side of the element by default, so they add to the setup:
.. code-block::
self.params['lblloc'] = 'rgt'
The user can still override this label position by creating, for example, `Transistor().label('Q1', loc='top')`.
As an example, here's the definition of our favorite element, the resistor:
.. code-block:: python
class Resistor(Element2Term):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
self.segments.append(Segment([(0, 0),
(0.5*reswidth, resheight),
(1.5*reswidth, -resheight),
(2.5*reswidth, resheight),
(3.5*reswidth, -resheight),
(4.5*reswidth, resheight),
(5.5*reswidth, -resheight),
(6*reswidth, 0)]))
The resistor is made of one path.
`reswidth` and `resheight` are constants that define the height and width of the resistor zigzag (and are referenced by several other elements too).
Browse the source code in the `Schemdraw.elements` submodule to see the definitions of the other built-in elements.
Flux Capacitor Example
^^^^^^^^^^^^^^^^^^^^^^
For an example, let's make a flux capacitor circuit element.
Since everyone knows a flux-capacitor has three branches, we should subclass the standard :py:class:`schemdraw.elements.Element` class instead of :py:class:`schemdraw.elements.Element2Term`.
Start by importing the Segments and define the class name and `__init__` function:
.. code-block:: python
from schemdraw.segments import *
class FluxCapacitor(Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
The `d` and `kwargs` are passed to `super` to initialize the Element.
We want a dot in the center of our flux capacitor, so start by adding a `SegmentCircle`. The `fclen` and `radius` variables could be set as arguments to the __init__ for the user to adjust, if desired, but here they are defined as constants in the __init__.
.. code-block:: python
fclen = 0.5
radius = 0.075
self.segments.append(SegmentCircle((0, 0), radius))
Next, add the paths as Segment instances, which are drawn as lines. The flux capacitor will have three paths, all extending from the center dot:
.. code-block:: python
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
And at the end of each path is an open circle. Append three more `SegmentCircle` instances.
By specifying `fill=None` the SegmentCircle will always remain unfilled regardless of any `fill` arguments provided to `Drawing` or `FluxCapacitor`.
.. code-block:: python
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
Finally, we need to define anchor points so that other elements can be connected to the right places.
Here, they're called `p1`, `p2`, and `p3` for lack of better names (what do you call the inputs to a flux capacitor?)
Add these to the `self.anchors` dictionary.
.. code-block:: python
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Here's the Flux Capacitor class all in one:
.. jupyter-execute::
class FluxCapacitor(elm.Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
radius = 0.075
fclen = 0.5
self.segments.append(SegmentCircle((0, 0), radius))
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Try it out:
.. jupyter-execute::
FluxCapacitor()
Segment objects
---------------
After an element is added to a drawing, the :py:class:`schemdraw.segments.Segment` objects defining it are accessible in the `segments` attribute list of the Element.
For even more control over customizing individual pieces of an element, the parameters of a Segment can be changed.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (n := logic.Nand())
n.segments[1].color = 'red'
n.segments[1].zorder = 5 # Put the bubble on top
.. jupyter-execute::
:hide-code:
d.draw()
Matplotlib axis
---------------
When using the Matplotlib backend (the default), a final customization option is to use the Matplotlib figure and add to it.
A :py:class:`schemdraw.Figure` is returned from the `draw` method, which contains `fig` and `ax` attributes holding the Matplotlib figure.
.. jupyter-execute::
:emphasize-lines: 4-5
schemdraw.use('matplotlib')
d = schemdraw.Drawing()
d.add(elm.Resistor())
schemfig = d.draw()
schemfig.ax.axvline(.5, color='purple', ls='--')
schemfig.ax.axvline(2.5, color='orange', ls='-', lw=3);
display(schemfig)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/customizing-checkpoint.rst
|
customizing-checkpoint.rst
|
Customizing Elements
====================
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
from schemdraw.segments import *
Grouping Elements
-----------------
If a set of circuit elements are to be reused multiple times, they can be grouped into a single element.
Create and populate a drawing, but set `show=False`.
Instead, use the Drawing to create a new :py:class:`schemdraw.elements.ElementDrawing`, which converts the drawing into an element instance
to add to other drawings.
.. jupyter-execute::
:emphasize-lines: 8-10
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2: # Add a second drawing
for i in range(3):
d2 += elm.ElementDrawing(d1) # Add the first drawing to it 3 times
.. _customelements:
Defining custom elements
------------------------
All elements are subclasses of :py:class:`schemdraw.elements.Element` or :py:class:`schemdraw.elements.Element2Term`.
For elements consisting of several other already-defined elements (like a relay), :py:class:`schemdraw.elements.compound.ElementCompound` can be used for easy combining of multiple elements.
Subclasses only need to define the `__init__` method in order to add lines, shapes, and text to the new element, all of which are defined using :py:class:`schemdraw.segments.Segment` classes. New Segments should be appended to the `Element.segments` attribute list.
Coordinates are all defined in element cooridnates, where the element begins
at (0, 0) and is drawn from left to right.
The drawing engine will rotate and translate the element to its final position, and for two-terminal
elements deriving from Element2Term, will add lead extensions to the correct length depending
on the element's placement parameters.
Therefore elements deriving from Element2Term should not define the lead extensions
(e.g. a Resistor only defines the zig-zag portion).
A standard resistor is 1 drawing unit long, and with default lead extension will become 3 units long.
Segments include :py:class:`schemdraw.segments.Segment`, :py:class:`schemdraw.segments.SegmentPoly`,
:py:class:`schemdraw.segments.SegmentCircle`, :py:class:`schemdraw.segments.SegmentArc`, :py:class:`schemdraw.segments.SegmentText`, and :py:class:`schemdraw.segments.SegmentBezier`.
The subclassed `Element.__init__` method can be defined with extra parameters
to help define the element options.
In addition to the list of Segments, any named anchors and other parameters should be specified.
Anchors should be added to the `Element.anchors` dictionary as {name: (x, y)} key/value pairs.
The Element instance maintains its own parameters dictionary in `Element.params` that override the default drawing parameters.
Parameters are resolved by a ChainMap of user arguments to the `Element` instance, the `Element.params` attribute, then the `schemdraw.Drawing` parameters, in that order.
A common use of setting `Element.params` in the setup function is to change the default position of text labels, for example Transistor elements apply labels on the right side of the element by default, so they add to the setup:
.. code-block::
self.params['lblloc'] = 'rgt'
The user can still override this label position by creating, for example, `Transistor().label('Q1', loc='top')`.
As an example, here's the definition of our favorite element, the resistor:
.. code-block:: python
class Resistor(Element2Term):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
self.segments.append(Segment([(0, 0),
(0.5*reswidth, resheight),
(1.5*reswidth, -resheight),
(2.5*reswidth, resheight),
(3.5*reswidth, -resheight),
(4.5*reswidth, resheight),
(5.5*reswidth, -resheight),
(6*reswidth, 0)]))
The resistor is made of one path.
`reswidth` and `resheight` are constants that define the height and width of the resistor zigzag (and are referenced by several other elements too).
Browse the source code in the `Schemdraw.elements` submodule to see the definitions of the other built-in elements.
Flux Capacitor Example
^^^^^^^^^^^^^^^^^^^^^^
For an example, let's make a flux capacitor circuit element.
Since everyone knows a flux-capacitor has three branches, we should subclass the standard :py:class:`schemdraw.elements.Element` class instead of :py:class:`schemdraw.elements.Element2Term`.
Start by importing the Segments and define the class name and `__init__` function:
.. code-block:: python
from schemdraw.segments import *
class FluxCapacitor(Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
The `d` and `kwargs` are passed to `super` to initialize the Element.
We want a dot in the center of our flux capacitor, so start by adding a `SegmentCircle`. The `fclen` and `radius` variables could be set as arguments to the __init__ for the user to adjust, if desired, but here they are defined as constants in the __init__.
.. code-block:: python
fclen = 0.5
radius = 0.075
self.segments.append(SegmentCircle((0, 0), radius))
Next, add the paths as Segment instances, which are drawn as lines. The flux capacitor will have three paths, all extending from the center dot:
.. code-block:: python
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
And at the end of each path is an open circle. Append three more `SegmentCircle` instances.
By specifying `fill=None` the SegmentCircle will always remain unfilled regardless of any `fill` arguments provided to `Drawing` or `FluxCapacitor`.
.. code-block:: python
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
Finally, we need to define anchor points so that other elements can be connected to the right places.
Here, they're called `p1`, `p2`, and `p3` for lack of better names (what do you call the inputs to a flux capacitor?)
Add these to the `self.anchors` dictionary.
.. code-block:: python
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Here's the Flux Capacitor class all in one:
.. jupyter-execute::
class FluxCapacitor(elm.Element):
def __init__(self, *d, **kwargs):
super().__init__(*d, **kwargs)
radius = 0.075
fclen = 0.5
self.segments.append(SegmentCircle((0, 0), radius))
self.segments.append(Segment([(0, 0), (0, -fclen*1.41)]))
self.segments.append(Segment([(0, 0), (fclen, fclen)]))
self.segments.append(Segment([(0, 0), (-fclen, fclen)]))
self.segments.append(SegmentCircle((0, -fclen*1.41), 0.2, fill=None))
self.segments.append(SegmentCircle((fclen, fclen), 0.2, fill=None))
self.segments.append(SegmentCircle((-fclen, fclen), 0.2, fill=None))
self.anchors['p1'] = (-fclen, fclen)
self.anchors['p2'] = (fclen, fclen)
self.anchors['p3'] = (0, -fclen*1.41)
Try it out:
.. jupyter-execute::
FluxCapacitor()
Segment objects
---------------
After an element is added to a drawing, the :py:class:`schemdraw.segments.Segment` objects defining it are accessible in the `segments` attribute list of the Element.
For even more control over customizing individual pieces of an element, the parameters of a Segment can be changed.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (n := logic.Nand())
n.segments[1].color = 'red'
n.segments[1].zorder = 5 # Put the bubble on top
.. jupyter-execute::
:hide-code:
d.draw()
Matplotlib axis
---------------
When using the Matplotlib backend (the default), a final customization option is to use the Matplotlib figure and add to it.
A :py:class:`schemdraw.Figure` is returned from the `draw` method, which contains `fig` and `ax` attributes holding the Matplotlib figure.
.. jupyter-execute::
:emphasize-lines: 4-5
schemdraw.use('matplotlib')
d = schemdraw.Drawing()
d.add(elm.Resistor())
schemfig = d.draw()
schemfig.ax.axvline(.5, color='purple', ls='--')
schemfig.ax.axvline(2.5, color='orange', ls='-', lw=3);
display(schemfig)
| 0.897803 | 0.693447 |
Getting Started
===============
Installation
------------
schemdraw can be installed from pip using
.. code-block:: bash
pip install schemdraw
or to include optional ``matplotlib`` backend dependencies:
.. code-block:: bash
pip install schemdraw[matplotlib]
To allow the SVG drawing :ref:`backends` to render math expressions,
install the optional `ziamath <https://ziamath.readthedocs.io>`_ dependency with:
.. code-block:: bash
pip install schemdraw[svgmath]
Alternatively, schemdraw can be installed directly by downloading the source and running
.. code-block:: bash
pip install ./
Schemdraw requires Python 3.8 or higher.
Overview
---------
The :py:mod:`schemdraw` module allows for drawing circuit elements.
:py:mod:`schemdraw.elements` contains :ref:`electrical` pre-defined for
use in a drawing. A common import structure is:
.. jupyter-execute::
import schemdraw
import schemdraw.elements as elm
To make a circuit diagram, a :py:class:`schemdraw.Drawing` is created and :py:class:`schemdraw.elements.Element` instances are added to it:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.add(elm.Resistor())
d.add(elm.Capacitor())
d.add(elm.Diode())
The `+=` operator may be used as shorthand notation to add elements to the drawing.
This code is equivalent to the above:
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Capacitor()
d += elm.Diode()
Element placement and other properties and are set using a chained method interface, for example:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
Methods `up`, `down`, `left`, `right` specify the drawing direction, and `label` adds text to the element.
If not specified, elements reuse the same direction from the previous element, and begin where
the previous element ended.
Using the `with` context manager is a convenience, letting the drawing be displayed and saved upon exiting the `with` block. Schematics may also be created simply by assinging a new Drawing instance, but this requires calling `draw()` and/or `save()` explicitly:
.. code-block:: python
d = schemdraw.Drawing()
d += elm.Resistor()
...
d.draw()
d.save('my_circuit.svg')
For full details of placing and stylizing elements, see :ref:`placement`.
and :py:class:`schemdraw.elements.Element`.
In general, parameters that control **what** is drawn are passed to the element itself, and parameters that control **how** things are drawn are set using chained Element methods. For example, to make a polarized Capacitor, pass `polar=True` as an argument to `Capacitor`, but to change the Capacitor's color, use the `.color()` method: `elm.Capacitor(polar=True).color('red')`.
Viewing the Drawing
-------------------
Jupyter
*******
When run in a Jupyter notebook, the schematic will be drawn to the cell output after the `with` block is exited.
If your schematics pop up in an external window, and you are using the Matplotlib backend, set Matplotlib to inline mode before importing schemdraw:
.. code-block:: python
%matplotlib inline
For best results when viewing circuits in the notebook, use a vector figure format, such as svg before importing schemdraw:
.. code-block:: python
%config InlineBackend.figure_format = 'svg'
Python Scripts and GUI/Web apps
*******************************
If run as a Python script, the schematic will be opened in a pop-up window after the `with` block exits.
Add the `show=False` option when creating the Drawing to suppress the window from appearing.
.. code-block:: python
with schemdraw.Drawing(show=False) as d:
...
The raw image data as a bytes array can be obtained by calling `.get_imagedata()` with the after the `with` block exits.
This can be useful for integrating schemdraw into an existing GUI or web application.
.. code-block:: python
with schemdraw.Drawing() as drawing:
...
image_bytes = drawing.get_imagedata('svg')
Headless Servers
****************
When running on a server, sometimes there is no display available.
The code may attempt to open the GUI preview window and fail.
In these cases, try setting the Matplotlib backend to a non-GUI option.
Before importing schemdraw, add these lines to use the Agg backend which does not have a GUI.
Then get the drawing using `d.get_imagedata()`, or `d.save()` to get the image.
.. code-block:: python
import matplotlib
matplotlib.use('Agg') # Set Matplotlib's backend here
Alternatively, use Schemdraw's SVG backend (see :ref:`backends`).
Saving Drawings
---------------
To save the schematic to a file, add the `file` parameter when setting up the Drawing.
The image type is determined from the file extension.
Options include `svg`, `eps`, `png`, `pdf`, and `jpg` when using the Matplotlib backend, and `svg` when using the SVG backend.
A vector format such as `svg` is recommended for best image quality.
.. code-block:: python
with schemdraw.Drawing(file='my_circuit.svg') as d:
...
The Drawing may also be saved using with the :py:meth:`schemdraw.Drawing.save` method.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/start-checkpoint.rst
|
start-checkpoint.rst
|
Getting Started
===============
Installation
------------
schemdraw can be installed from pip using
.. code-block:: bash
pip install schemdraw
or to include optional ``matplotlib`` backend dependencies:
.. code-block:: bash
pip install schemdraw[matplotlib]
To allow the SVG drawing :ref:`backends` to render math expressions,
install the optional `ziamath <https://ziamath.readthedocs.io>`_ dependency with:
.. code-block:: bash
pip install schemdraw[svgmath]
Alternatively, schemdraw can be installed directly by downloading the source and running
.. code-block:: bash
pip install ./
Schemdraw requires Python 3.8 or higher.
Overview
---------
The :py:mod:`schemdraw` module allows for drawing circuit elements.
:py:mod:`schemdraw.elements` contains :ref:`electrical` pre-defined for
use in a drawing. A common import structure is:
.. jupyter-execute::
import schemdraw
import schemdraw.elements as elm
To make a circuit diagram, a :py:class:`schemdraw.Drawing` is created and :py:class:`schemdraw.elements.Element` instances are added to it:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d.add(elm.Resistor())
d.add(elm.Capacitor())
d.add(elm.Diode())
The `+=` operator may be used as shorthand notation to add elements to the drawing.
This code is equivalent to the above:
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor()
d += elm.Capacitor()
d += elm.Diode()
Element placement and other properties and are set using a chained method interface, for example:
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
Methods `up`, `down`, `left`, `right` specify the drawing direction, and `label` adds text to the element.
If not specified, elements reuse the same direction from the previous element, and begin where
the previous element ended.
Using the `with` context manager is a convenience, letting the drawing be displayed and saved upon exiting the `with` block. Schematics may also be created simply by assinging a new Drawing instance, but this requires calling `draw()` and/or `save()` explicitly:
.. code-block:: python
d = schemdraw.Drawing()
d += elm.Resistor()
...
d.draw()
d.save('my_circuit.svg')
For full details of placing and stylizing elements, see :ref:`placement`.
and :py:class:`schemdraw.elements.Element`.
In general, parameters that control **what** is drawn are passed to the element itself, and parameters that control **how** things are drawn are set using chained Element methods. For example, to make a polarized Capacitor, pass `polar=True` as an argument to `Capacitor`, but to change the Capacitor's color, use the `.color()` method: `elm.Capacitor(polar=True).color('red')`.
Viewing the Drawing
-------------------
Jupyter
*******
When run in a Jupyter notebook, the schematic will be drawn to the cell output after the `with` block is exited.
If your schematics pop up in an external window, and you are using the Matplotlib backend, set Matplotlib to inline mode before importing schemdraw:
.. code-block:: python
%matplotlib inline
For best results when viewing circuits in the notebook, use a vector figure format, such as svg before importing schemdraw:
.. code-block:: python
%config InlineBackend.figure_format = 'svg'
Python Scripts and GUI/Web apps
*******************************
If run as a Python script, the schematic will be opened in a pop-up window after the `with` block exits.
Add the `show=False` option when creating the Drawing to suppress the window from appearing.
.. code-block:: python
with schemdraw.Drawing(show=False) as d:
...
The raw image data as a bytes array can be obtained by calling `.get_imagedata()` with the after the `with` block exits.
This can be useful for integrating schemdraw into an existing GUI or web application.
.. code-block:: python
with schemdraw.Drawing() as drawing:
...
image_bytes = drawing.get_imagedata('svg')
Headless Servers
****************
When running on a server, sometimes there is no display available.
The code may attempt to open the GUI preview window and fail.
In these cases, try setting the Matplotlib backend to a non-GUI option.
Before importing schemdraw, add these lines to use the Agg backend which does not have a GUI.
Then get the drawing using `d.get_imagedata()`, or `d.save()` to get the image.
.. code-block:: python
import matplotlib
matplotlib.use('Agg') # Set Matplotlib's backend here
Alternatively, use Schemdraw's SVG backend (see :ref:`backends`).
Saving Drawings
---------------
To save the schematic to a file, add the `file` parameter when setting up the Drawing.
The image type is determined from the file extension.
Options include `svg`, `eps`, `png`, `pdf`, and `jpg` when using the Matplotlib backend, and `svg` when using the SVG backend.
A vector format such as `svg` is recommended for best image quality.
.. code-block:: python
with schemdraw.Drawing(file='my_circuit.svg') as d:
...
The Drawing may also be saved using with the :py:meth:`schemdraw.Drawing.save` method.
| 0.953221 | 0.68635 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _labels:
Labels
------
Labels are added to elements using the :py:meth:`schemdraw.elements.Element.label` method.
Some unicode utf-8 characters are allowed, such as :code:`'1μF'` and :code:`'1MΩ'` if the character is included in your font set.
Alternatively, full LaTeX math expressions can be rendered when enclosed in `$..$`
For a description of supported math expressions, in the Matplotlib backend see `Matplotlib Mathtext <https://matplotlib.org/stable/tutorials/text/mathtext.html>`_, and the SVG backend refer to the `Ziamath <https://ziamath.readthedocs.io>`_ package.
Subscripts and superscripts are also added using LaTeX math mode, enclosed in `$..$`:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Resistor().label('1MΩ')
d += elm.Capacitor().label('1μF')
d += elm.Capacitor().label(r'$v = \frac{1}{C} \int i dt$')
d += elm.Resistor().at((0, -2)).label('$R_0$')
d += elm.Capacitor().label('$x^2$')
.. jupyter-execute::
:hide-code:
d.draw()
Location
********
The label location is specified with the `loc` parameter to the `label` method.
It can be `left`, `right`, `top`, `bottom`, or the name of a defined anchor within the element.
These directions do not depend on rotation. A label with `loc='left'` is always on the leftmost terminal of the element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.Resistor()
.label('Label') # 'top' is default
.label('Bottom', loc='bottom')
.label('Right', loc='right')
.label('Left', loc='left'))
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be placed near an element anchor by giving the anchor name as the `loc` parameter.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.BjtNpn()
.label('b', loc='base')
.label('c', loc='collector')
.label('e', loc='emitter'))
.. jupyter-execute::
:hide-code:
d.draw()
The :py:meth:`schemdraw.elements.Element.label` method also takes parameters that control the label's rotation, offset, font, alignment, and color.
Label text stays horizontal by default, but may be rotated to the same angle as the element using `rotate=True`, or any angle `X` in degrees with `rotate=X`.
Offsets apply vertically if a float value is given, or in both x and y if a tuple is given.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('no offset')
d += elm.Resistor().label('offset', ofst=1)
d += elm.Resistor().label('offset (x, y)', ofst=(-.6, .2))
d += elm.Resistor().theta(-45).label('no rotate')
d += elm.Resistor().theta(-45).label('rotate', rotate=True)
d += elm.Resistor().theta(45).label('90°', rotate=90)
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be added anywhere using the :py:class:`schemdraw.elements.lines.Label` element. The element itself draws nothing, but labels can be added to it:
.. code-block:: python
elm.Label().label('Hello')
Voltage Labels
**************
A label may also be a list/tuple of strings, which will be evenly-spaced along the length of the element.
This allows for labeling positive and negative along with a component name, for example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label(('–','$V_1$','+')) # Note: using endash U+2013 character
.. jupyter-execute::
:hide-code:
d.draw()
Use the `Gap` element to label voltage across a terminal:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Line().dot(open=True)
d += elm.Gap().label(('–','$V_o$','+'))
d += elm.Line().idot(open=True)
.. jupyter-execute::
:hide-code:
d.draw()
Current Arrow Labels
********************
Current Arrow
^^^^^^^^^^^^^
To label the current through an element, the :py:class:`schemdraw.elements.lines.CurrentLabel` element can be added.
The `at` method of this element can take an Element instance to label, and the
arrow will be placed over the center of that Element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (R1 := elm.Resistor())
d += elm.CurrentLabel().at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
For transistors, the label will follow sensible bias currents by default.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (Q1 := elm.AnalogNFet())
d += elm.CurrentLabel().at(Q1).label('10 µA')
d += (Q2 := elm.AnalogNFet()).at([4,0]).flip().reverse()
d += elm.CurrentLabel().at(Q2).label('10 µA')
.. jupyter-execute::
:hide-code:
d.draw()
Inline Current Arrow
^^^^^^^^^^^^^^^^^^^^
Alternatively, current labels can be drawn inline as arrowheads on the leads of 2-terminal elements using :py:class:`schemdraw.elements.lines.CurrentLabelInline`. Parameters `direction` and `start` control whether the arrow
is shown pointing into or out of the element, and which end to place the arrowhead on.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += elm.CurrentLabelInline(direction='in').at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
Loop Current
^^^^^^^^^^^^
Loop currents can be added using :py:class:`schemdraw.elements.lines.LoopCurrent`, given a list of 4 existing elements surrounding the loop.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += (C1 := elm.Capacitor().down())
d += (D1 := elm.Diode().fill(True).left())
d += (L1 := elm.Inductor().up())
d += elm.LoopCurrent([R1, C1, D1, L1], direction='cw').label('$I_1$')
.. jupyter-execute::
:hide-code:
d.draw()
Alternatively, loop current arrows can be added anywhere with any size using :py:class:`schemdraw.elements.lines.LoopArrow`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (a:=elm.Line().dot())
d += elm.LoopArrow(width=.75, height=.75).at(a.end)
.. jupyter-execute::
:hide-code:
d.draw()
Impedance Arrow Label
^^^^^^^^^^^^^^^^^^^^^
A right-angle arrow label, often used to indicate impedance looking into a node, is added using :py:class:`schemdraw.elements.lines.ZLabel`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R:=elm.RBox().right())
d += elm.ZLabel().at(R).label('$Z_{in}$')
.. jupyter-execute::
:hide-code:
d.draw()
Annotations
***********
To make text and arrow annotations to a schematic, the :py:class:`schemdraw.elements.lines.Annotate` element draws a curvy arrow with label placed at it's end. It is based on the :py:class:`schemdraw.elements.lines.Arc3` element.
The :py:class:`schemdraw.elements.lines.Encircle` and :py:class:`schemdraw.elements.lines.EncircleBox` elements draw an ellipse, or rounded rectangle, surrounding a list of elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(unit=2)
d += (R1 := elm.Resistor().down().label('R1'))
d += (c := elm.Line().right().length(1))
d += (R2 := elm.Resistor().up().label('R2', loc='bottom'))
d += elm.Line().left().length(1)
d += elm.Line().down().at(c.center).length(.75).idot()
d += (R3 := elm.Resistor().down().label('R3'))
d += (R4 := elm.Resistor().down().label('R4'))
.. jupyter-execute::
d += (parallel := elm.Encircle([R1, R2], padx=.8).linestyle('--').linewidth(1).color('red'))
d += (series := elm.Encircle([R3, R4], padx=.8).linestyle('--').linewidth(1).color('blue'))
d += elm.Annotate().at(parallel.NNE).delta(dx=1, dy=1).label('Parallel').color('red')
d += elm.Annotate(th1=0).at(series.ENE).delta(dx=1.5, dy=1).label('Series').color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/labels-checkpoint.rst
|
labels-checkpoint.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _labels:
Labels
------
Labels are added to elements using the :py:meth:`schemdraw.elements.Element.label` method.
Some unicode utf-8 characters are allowed, such as :code:`'1μF'` and :code:`'1MΩ'` if the character is included in your font set.
Alternatively, full LaTeX math expressions can be rendered when enclosed in `$..$`
For a description of supported math expressions, in the Matplotlib backend see `Matplotlib Mathtext <https://matplotlib.org/stable/tutorials/text/mathtext.html>`_, and the SVG backend refer to the `Ziamath <https://ziamath.readthedocs.io>`_ package.
Subscripts and superscripts are also added using LaTeX math mode, enclosed in `$..$`:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += elm.Resistor().label('1MΩ')
d += elm.Capacitor().label('1μF')
d += elm.Capacitor().label(r'$v = \frac{1}{C} \int i dt$')
d += elm.Resistor().at((0, -2)).label('$R_0$')
d += elm.Capacitor().label('$x^2$')
.. jupyter-execute::
:hide-code:
d.draw()
Location
********
The label location is specified with the `loc` parameter to the `label` method.
It can be `left`, `right`, `top`, `bottom`, or the name of a defined anchor within the element.
These directions do not depend on rotation. A label with `loc='left'` is always on the leftmost terminal of the element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.Resistor()
.label('Label') # 'top' is default
.label('Bottom', loc='bottom')
.label('Right', loc='right')
.label('Left', loc='left'))
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be placed near an element anchor by giving the anchor name as the `loc` parameter.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (elm.BjtNpn()
.label('b', loc='base')
.label('c', loc='collector')
.label('e', loc='emitter'))
.. jupyter-execute::
:hide-code:
d.draw()
The :py:meth:`schemdraw.elements.Element.label` method also takes parameters that control the label's rotation, offset, font, alignment, and color.
Label text stays horizontal by default, but may be rotated to the same angle as the element using `rotate=True`, or any angle `X` in degrees with `rotate=X`.
Offsets apply vertically if a float value is given, or in both x and y if a tuple is given.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label('no offset')
d += elm.Resistor().label('offset', ofst=1)
d += elm.Resistor().label('offset (x, y)', ofst=(-.6, .2))
d += elm.Resistor().theta(-45).label('no rotate')
d += elm.Resistor().theta(-45).label('rotate', rotate=True)
d += elm.Resistor().theta(45).label('90°', rotate=90)
.. jupyter-execute::
:hide-code:
d.draw()
Labels may also be added anywhere using the :py:class:`schemdraw.elements.lines.Label` element. The element itself draws nothing, but labels can be added to it:
.. code-block:: python
elm.Label().label('Hello')
Voltage Labels
**************
A label may also be a list/tuple of strings, which will be evenly-spaced along the length of the element.
This allows for labeling positive and negative along with a component name, for example:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Resistor().label(('–','$V_1$','+')) # Note: using endash U+2013 character
.. jupyter-execute::
:hide-code:
d.draw()
Use the `Gap` element to label voltage across a terminal:
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += elm.Line().dot(open=True)
d += elm.Gap().label(('–','$V_o$','+'))
d += elm.Line().idot(open=True)
.. jupyter-execute::
:hide-code:
d.draw()
Current Arrow Labels
********************
Current Arrow
^^^^^^^^^^^^^
To label the current through an element, the :py:class:`schemdraw.elements.lines.CurrentLabel` element can be added.
The `at` method of this element can take an Element instance to label, and the
arrow will be placed over the center of that Element.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (R1 := elm.Resistor())
d += elm.CurrentLabel().at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
For transistors, the label will follow sensible bias currents by default.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
d += (Q1 := elm.AnalogNFet())
d += elm.CurrentLabel().at(Q1).label('10 µA')
d += (Q2 := elm.AnalogNFet()).at([4,0]).flip().reverse()
d += elm.CurrentLabel().at(Q2).label('10 µA')
.. jupyter-execute::
:hide-code:
d.draw()
Inline Current Arrow
^^^^^^^^^^^^^^^^^^^^
Alternatively, current labels can be drawn inline as arrowheads on the leads of 2-terminal elements using :py:class:`schemdraw.elements.lines.CurrentLabelInline`. Parameters `direction` and `start` control whether the arrow
is shown pointing into or out of the element, and which end to place the arrowhead on.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += elm.CurrentLabelInline(direction='in').at(R1).label('10 mA')
.. jupyter-execute::
:hide-code:
d.draw()
Loop Current
^^^^^^^^^^^^
Loop currents can be added using :py:class:`schemdraw.elements.lines.LoopCurrent`, given a list of 4 existing elements surrounding the loop.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R1 := elm.Resistor())
d += (C1 := elm.Capacitor().down())
d += (D1 := elm.Diode().fill(True).left())
d += (L1 := elm.Inductor().up())
d += elm.LoopCurrent([R1, C1, D1, L1], direction='cw').label('$I_1$')
.. jupyter-execute::
:hide-code:
d.draw()
Alternatively, loop current arrows can be added anywhere with any size using :py:class:`schemdraw.elements.lines.LoopArrow`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (a:=elm.Line().dot())
d += elm.LoopArrow(width=.75, height=.75).at(a.end)
.. jupyter-execute::
:hide-code:
d.draw()
Impedance Arrow Label
^^^^^^^^^^^^^^^^^^^^^
A right-angle arrow label, often used to indicate impedance looking into a node, is added using :py:class:`schemdraw.elements.lines.ZLabel`.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:hide-output:
d += (R:=elm.RBox().right())
d += elm.ZLabel().at(R).label('$Z_{in}$')
.. jupyter-execute::
:hide-code:
d.draw()
Annotations
***********
To make text and arrow annotations to a schematic, the :py:class:`schemdraw.elements.lines.Annotate` element draws a curvy arrow with label placed at it's end. It is based on the :py:class:`schemdraw.elements.lines.Arc3` element.
The :py:class:`schemdraw.elements.lines.Encircle` and :py:class:`schemdraw.elements.lines.EncircleBox` elements draw an ellipse, or rounded rectangle, surrounding a list of elements.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing(unit=2)
d += (R1 := elm.Resistor().down().label('R1'))
d += (c := elm.Line().right().length(1))
d += (R2 := elm.Resistor().up().label('R2', loc='bottom'))
d += elm.Line().left().length(1)
d += elm.Line().down().at(c.center).length(.75).idot()
d += (R3 := elm.Resistor().down().label('R3'))
d += (R4 := elm.Resistor().down().label('R4'))
.. jupyter-execute::
d += (parallel := elm.Encircle([R1, R2], padx=.8).linestyle('--').linewidth(1).color('red'))
d += (series := elm.Encircle([R3, R4], padx=.8).linestyle('--').linewidth(1).color('blue'))
d += elm.Annotate().at(parallel.NNE).delta(dx=1, dy=1).label('Parallel').color('red')
d += elm.Annotate(th1=0).at(series.ENE).delta(dx=1.5, dy=1).label('Series').color('blue')
.. jupyter-execute::
:hide-code:
d.draw()
| 0.884763 | 0.571468 |
.. _backends:
Backends
--------
The backend is the "canvas" on which a schematic is drawn. Schemdraw supports two backends: Matplotlib, and SVG.
Matplotlib Backend
******************
By default, all schematics are drawn on a Matplotlib axis.
A new Matplotlib Figure and Axis will be created, with no frame or borders.
A schematic may be added to an existing Axis by using the :py:meth:`schemdraw.Drawing.draw` method and setting
the `canvas` parameter to an existing Axis instance.
The Matplotlib backend renders text labels as primative lines and arcs rather than text elements by default.
This has the downside that SVG editors, such as Inkscape, cannot perform textual searches on the SVGs.
The upside is that there is no dependence on installed fonts on the hosts that open the SVGs.
To configure Matplotlib to render labels as SVG text elements:
.. code-block:: python
import matplotlib
matplotlib.rcParams['svg.fonttype'] = 'none'
SVG Backend
***********
Schematics can also be drawn on directly to an SVG image backend.
The SVG backend can be enabled for all drawings by calling:
.. code-block:: python
schemdraw.use('svg')
The backend can be changed at any time. Alternatively, the backend can be set individually on each Drawing using the `canvas` parameter:
.. code-block::
with schemdraw.Drawing(canvas='svg') as d:
...
Use additional Python libraries, such as `pycairo <https://cairosvg.org/>`_, to convert the SVG output into other image formats.
Math Text
^^^^^^^^^
The SVG backend has basic math text support, including greek symbols, subscripts, and superscripts.
However, if `ziamath <https://ziamath.readthedocs.io>`_ and `latex2mathml <https://pypi.org/project/latex2mathml/>`_ packages are installed, they will be used for full Latex math support.
The SVG backend can produce searchable-text SVGs by setting:
.. code-block:: python
schemdraw.svgconfig.text = 'text'
However, text mode does not support full Latex compatibility.
To switch back to rendering text as SVG paths:
.. code-block:: python
schemdraw.svgconfig.text = 'path'
Some SVG renderers are not fully compatible with SVG2.0. For better compatibility with SVG1.x, use
.. code-block:: python
schemdraw.svgconfig.svg2 = False
The decimal precision of SVG elements can be set using
.. code-block:: python
schemdraw.svgconfig.precision = 2
Backend Comparison
******************
Reasons to choose the SVG backend include:
- No Matplotlib/Numpy dependency required (huge file size savings if bundling an executable).
- Speed. The SVG backend draws 4-10x faster than Matplotlib, depending on the circuit complexity.
Reasons to use Matplotlib backend:
- To customize the schematic after drawing it by using other Matplotlib functionality.
- To render directly in other, non-SVG, image formats, with no additional code.
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/backends-checkpoint.rst
|
backends-checkpoint.rst
|
.. _backends:
Backends
--------
The backend is the "canvas" on which a schematic is drawn. Schemdraw supports two backends: Matplotlib, and SVG.
Matplotlib Backend
******************
By default, all schematics are drawn on a Matplotlib axis.
A new Matplotlib Figure and Axis will be created, with no frame or borders.
A schematic may be added to an existing Axis by using the :py:meth:`schemdraw.Drawing.draw` method and setting
the `canvas` parameter to an existing Axis instance.
The Matplotlib backend renders text labels as primative lines and arcs rather than text elements by default.
This has the downside that SVG editors, such as Inkscape, cannot perform textual searches on the SVGs.
The upside is that there is no dependence on installed fonts on the hosts that open the SVGs.
To configure Matplotlib to render labels as SVG text elements:
.. code-block:: python
import matplotlib
matplotlib.rcParams['svg.fonttype'] = 'none'
SVG Backend
***********
Schematics can also be drawn on directly to an SVG image backend.
The SVG backend can be enabled for all drawings by calling:
.. code-block:: python
schemdraw.use('svg')
The backend can be changed at any time. Alternatively, the backend can be set individually on each Drawing using the `canvas` parameter:
.. code-block::
with schemdraw.Drawing(canvas='svg') as d:
...
Use additional Python libraries, such as `pycairo <https://cairosvg.org/>`_, to convert the SVG output into other image formats.
Math Text
^^^^^^^^^
The SVG backend has basic math text support, including greek symbols, subscripts, and superscripts.
However, if `ziamath <https://ziamath.readthedocs.io>`_ and `latex2mathml <https://pypi.org/project/latex2mathml/>`_ packages are installed, they will be used for full Latex math support.
The SVG backend can produce searchable-text SVGs by setting:
.. code-block:: python
schemdraw.svgconfig.text = 'text'
However, text mode does not support full Latex compatibility.
To switch back to rendering text as SVG paths:
.. code-block:: python
schemdraw.svgconfig.text = 'path'
Some SVG renderers are not fully compatible with SVG2.0. For better compatibility with SVG1.x, use
.. code-block:: python
schemdraw.svgconfig.svg2 = False
The decimal precision of SVG elements can be set using
.. code-block:: python
schemdraw.svgconfig.precision = 2
Backend Comparison
******************
Reasons to choose the SVG backend include:
- No Matplotlib/Numpy dependency required (huge file size savings if bundling an executable).
- Speed. The SVG backend draws 4-10x faster than Matplotlib, depending on the circuit complexity.
Reasons to use Matplotlib backend:
- To customize the schematic after drawing it by using other Matplotlib functionality.
- To render directly in other, non-SVG, image formats, with no additional code.
| 0.902785 | 0.630145 |
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _styles:
Styling
-------
Style options, such as color, line thickness, and fonts, may be set at the global level (all Schemdraw Drawings), at the Drawing level, or on individual Elements.
Individual Elements
*******************
Element styling methods include `color`, `fill`, `linewidth`, and `linestyle`.
If a style method is not called when creating an Element, its value is obtained from from the drawing or global defaults.
Color and fill parameters accept any named `SVG color <https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg>`_ or a hex color string such as '#6A5ACD'. Linestyle parameters may be '-', '--', ':', or '-.'.
.. jupyter-execute::
:hide-output:
# All elements are blue with lightgray fill unless specified otherwise
d = schemdraw.Drawing(color='blue', fill='lightgray')
d += elm.Diode()
d += elm.Diode().fill('red') # Fill overrides drawing color here
d += elm.Resistor().fill('purple') # Fill has no effect on non-closed elements
d += elm.RBox().linestyle('--').color('orange')
d += elm.Resistor().linewidth(5)
.. jupyter-execute::
:hide-code:
d.draw()
The `label` method also accepts color, font, and fontsize parameters, allowing labels with different style as their elements.
Drawing style
*************
Styles may be applied to an entire drawing using the :py:meth:`schemdraw.Drawing.config` method.
These parameters include color, linewidth, font, fontsize, linestyle, fill, and background color.
Additionally, the `config` method allows specification of the default 2-Terminal element length.
Global style
************
Styles may be applied to every new drawing created by Schemdraw (during the Python session) using :py:meth:`schemdraw.config`, using the same arguments as the Drawing config method.
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.config(lw=1, font='serif')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.config()
Global Element Configuration
****************************
The :py:meth:`schemdraw.elements.Element.style` can be used to configure styles on individual element classes that apply to all Drawings.
It may be used, for example, to fill all Diode elements by default, without requiring the `fill()` method on every Diode instance.
Its argument is a dictionary of {name: Element} class pairs.
Combined with `functools.partial <https://docs.python.org/3/library/functools.html#functools.partial>`_ from the standard library, parameters to elements can be set globally.
For example, the following code fills all Diode elements:
.. jupyter-execute::
:emphasize-lines: 3
from functools import partial
elm.style({'Diode': partial(elm.Diode, fill=True)})
with schemdraw.Drawing() as d:
d += elm.Diode()
d += elm.Diode()
Be careful, though, because the `style` method can overwrite existing elements in the namespace.
U.S. versus European Style
**************************
The main use of :py:meth:`schemdraw.elements.Element.style` is to reconfigure elements in IEEE/U.S. style or IEC/European style.
The `schemdraw.elements.STYLE_IEC` and `schemdraw.elements.STYLE_IEEE` are dictionaries for use in the `style` method to change configuration of various elements that use different standard symbols (resistor, variable resistor, photo resistor, etc.)
To configure IEC/European style, use the `style` method with the `elm.STYLE_IEC` dictionary.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEC)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEEE)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
To see all the elements that change between IEEE and IEC, see :ref:`styledelements`.
Fonts
*****
The font for label text may be set using the `font` parameter, either in the :py:meth:`schemdraw.elements.Element.label` method for a single label, or in :py:meth:`schemdraw.Drawing.config` to set the font for the entire drawing.
The font parameter may be a string containing the name of a font installed in the system fonts path, a path to a TTF font file, or the name of a font family such as "serif" or "sans".
These font options apply whether working in the Matplotlib or SVG backends.
.. code-block:: python
with schemdraw.Drawing() as d:
# Default font
d += elm.RBox().label('R1\n500K')
# Named font in system fonts path
d += elm.RBox().label('R1\n500K', font='Comic Sans MS')
# Path to a TTF file
d += elm.RBox().label('R1\n500K', font='Peralta-Regular.ttf')
# Font family
d += elm.RBox().label('R1\n500K', font='serif')
.. image:: fonts.svg
:alt: Font examples
For typesetting math expressions, the `mathfont` parameter is used.
In the Matplotlib backend, a limited `selection of math fonts <https://matplotlib.org/stable/tutorials/text/mathtext.html#fonts>`_ are available.
With the SVG backend in the `path` text mode, the mathfont parameter may be the path to any TTF file that contains a MATH table (requires `Ziamath <https://ziamath.readthedocs.io>`_).
.. code-block:: python
with schemdraw.Drawing(canvas='svg') as d:
# Default math font
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$').at((0, -2))
# Path to a TTF file with MATH font table (SVG backend only)
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$', mathfont='Asana-Math.ttf')
.. image:: mathfonts.svg
:alt: Math font examples
Themes
******
Schemdraw also supports themeing, to enable dark mode, for example.
The defined themes match those in the `Jupyter Themes <https://github.com/dunovank/jupyter-themes>`_ package:
* default (black on white)
* dark (white on black)
* solarizedd
* solarizedl
* onedork
* oceans16
* monokai
* gruvboxl
* gruvboxd
* grade3
* chesterish
They are enabled using :py:meth:`schemdraw.theme`:
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.theme('monokai')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.theme('default')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/usage/.ipynb_checkpoints/styles-checkpoint.rst
|
styles-checkpoint.rst
|
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
.. _styles:
Styling
-------
Style options, such as color, line thickness, and fonts, may be set at the global level (all Schemdraw Drawings), at the Drawing level, or on individual Elements.
Individual Elements
*******************
Element styling methods include `color`, `fill`, `linewidth`, and `linestyle`.
If a style method is not called when creating an Element, its value is obtained from from the drawing or global defaults.
Color and fill parameters accept any named `SVG color <https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg>`_ or a hex color string such as '#6A5ACD'. Linestyle parameters may be '-', '--', ':', or '-.'.
.. jupyter-execute::
:hide-output:
# All elements are blue with lightgray fill unless specified otherwise
d = schemdraw.Drawing(color='blue', fill='lightgray')
d += elm.Diode()
d += elm.Diode().fill('red') # Fill overrides drawing color here
d += elm.Resistor().fill('purple') # Fill has no effect on non-closed elements
d += elm.RBox().linestyle('--').color('orange')
d += elm.Resistor().linewidth(5)
.. jupyter-execute::
:hide-code:
d.draw()
The `label` method also accepts color, font, and fontsize parameters, allowing labels with different style as their elements.
Drawing style
*************
Styles may be applied to an entire drawing using the :py:meth:`schemdraw.Drawing.config` method.
These parameters include color, linewidth, font, fontsize, linestyle, fill, and background color.
Additionally, the `config` method allows specification of the default 2-Terminal element length.
Global style
************
Styles may be applied to every new drawing created by Schemdraw (during the Python session) using :py:meth:`schemdraw.config`, using the same arguments as the Drawing config method.
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.config(lw=1, font='serif')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.config()
Global Element Configuration
****************************
The :py:meth:`schemdraw.elements.Element.style` can be used to configure styles on individual element classes that apply to all Drawings.
It may be used, for example, to fill all Diode elements by default, without requiring the `fill()` method on every Diode instance.
Its argument is a dictionary of {name: Element} class pairs.
Combined with `functools.partial <https://docs.python.org/3/library/functools.html#functools.partial>`_ from the standard library, parameters to elements can be set globally.
For example, the following code fills all Diode elements:
.. jupyter-execute::
:emphasize-lines: 3
from functools import partial
elm.style({'Diode': partial(elm.Diode, fill=True)})
with schemdraw.Drawing() as d:
d += elm.Diode()
d += elm.Diode()
Be careful, though, because the `style` method can overwrite existing elements in the namespace.
U.S. versus European Style
**************************
The main use of :py:meth:`schemdraw.elements.Element.style` is to reconfigure elements in IEEE/U.S. style or IEC/European style.
The `schemdraw.elements.STYLE_IEC` and `schemdraw.elements.STYLE_IEEE` are dictionaries for use in the `style` method to change configuration of various elements that use different standard symbols (resistor, variable resistor, photo resistor, etc.)
To configure IEC/European style, use the `style` method with the `elm.STYLE_IEC` dictionary.
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEC)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
.. jupyter-execute::
:hide-code:
d = schemdraw.Drawing()
.. jupyter-execute::
:emphasize-lines: 1
elm.style(elm.STYLE_IEEE)
d += elm.Resistor()
.. jupyter-execute::
:hide-code:
d.draw()
To see all the elements that change between IEEE and IEC, see :ref:`styledelements`.
Fonts
*****
The font for label text may be set using the `font` parameter, either in the :py:meth:`schemdraw.elements.Element.label` method for a single label, or in :py:meth:`schemdraw.Drawing.config` to set the font for the entire drawing.
The font parameter may be a string containing the name of a font installed in the system fonts path, a path to a TTF font file, or the name of a font family such as "serif" or "sans".
These font options apply whether working in the Matplotlib or SVG backends.
.. code-block:: python
with schemdraw.Drawing() as d:
# Default font
d += elm.RBox().label('R1\n500K')
# Named font in system fonts path
d += elm.RBox().label('R1\n500K', font='Comic Sans MS')
# Path to a TTF file
d += elm.RBox().label('R1\n500K', font='Peralta-Regular.ttf')
# Font family
d += elm.RBox().label('R1\n500K', font='serif')
.. image:: fonts.svg
:alt: Font examples
For typesetting math expressions, the `mathfont` parameter is used.
In the Matplotlib backend, a limited `selection of math fonts <https://matplotlib.org/stable/tutorials/text/mathtext.html#fonts>`_ are available.
With the SVG backend in the `path` text mode, the mathfont parameter may be the path to any TTF file that contains a MATH table (requires `Ziamath <https://ziamath.readthedocs.io>`_).
.. code-block:: python
with schemdraw.Drawing(canvas='svg') as d:
# Default math font
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$').at((0, -2))
# Path to a TTF file with MATH font table (SVG backend only)
d += elm.RBox().label(r'$\sqrt{a^2+b^2}$', mathfont='Asana-Math.ttf')
.. image:: mathfonts.svg
:alt: Math font examples
Themes
******
Schemdraw also supports themeing, to enable dark mode, for example.
The defined themes match those in the `Jupyter Themes <https://github.com/dunovank/jupyter-themes>`_ package:
* default (black on white)
* dark (white on black)
* solarizedd
* solarizedl
* onedork
* oceans16
* monokai
* gruvboxl
* gruvboxd
* grade3
* chesterish
They are enabled using :py:meth:`schemdraw.theme`:
.. jupyter-execute::
:emphasize-lines: 1
schemdraw.theme('monokai')
with schemdraw.Drawing() as d:
d += elm.Resistor().label('100KΩ')
d += elm.Capacitor().down().label('0.1μF', loc='bottom')
d += elm.Line().left()
d += elm.Ground()
d += elm.SourceV().up().label('10V')
.. jupyter-execute::
:hide-code:
schemdraw.theme('default')
| 0.900814 | 0.545467 |
Solid State
-----------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
S-R Latch (Transistors)
^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q1 := elm.BjtNpn(circle=True).reverse().label('Q1', 'left'))
d += (Q2 := elm.BjtNpn(circle=True).at((d.unit*2, 0)).label('Q2'))
d += elm.Line().up(d.unit/2).at(Q1.collector)
d += (R1 := elm.Resistor().up().label('R1').hold())
d += elm.Dot().label('V1', 'left')
d += elm.Resistor().right(d.unit*.75).label('R3', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Set', 'right').hold()
d += elm.Line().to(Q2.base)
d += elm.Line().up(d.unit/2).at(Q2.collector)
d += elm.Dot().label('V2', 'right')
d += (R2 := elm.Resistor().up().label('R2', 'bottom').hold())
d += elm.Resistor().left(d.unit*.75).label('R4', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Reset', 'right').hold()
d += elm.Line().to(Q1.base)
d += elm.Line().down(d.unit/4).at(Q1.emitter)
d += (BOT := elm.Line().tox(Q2.emitter))
d += elm.Line().to(Q2.emitter)
d += elm.Dot().at(BOT.center)
d += elm.Ground().at(BOT.center)
d += (TOP := elm.Line().endpoints(R1.end, R2.end))
d += elm.Dot().at(TOP.center)
d += elm.Vdd().at(TOP.center).label('+Vcc')
741 Opamp Internal Schematic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12, unit=2.5)
d += (Q1 := elm.BjtNpn().label('Q1').label('+IN', 'left'))
d += (Q3 := elm.BjtPnp().left().at(Q1.emitter).anchor('emitter').flip().label('Q3', 'left'))
d += elm.Line().down().at(Q3.collector).dot()
d.push()
d += elm.Line().right(d.unit/4)
d += (Q7 := elm.BjtNpn().anchor('base').label('Q7'))
d.pop()
d += elm.Line().down(d.unit*1.25)
d += (Q5 := elm.BjtNpn().left().flip().anchor('collector').label('Q5', 'left'))
d += elm.Line().left(d.unit/2).at(Q5.emitter).label('OFST\nNULL', 'left').flip()
d += elm.Resistor().down().at(Q5.emitter).label('R1\n1K')
d += elm.Line().right(d.unit*.75).dot()
d += (R3 := elm.Resistor().up().label('R3\n50K'))
d += elm.Line().toy(Q5.base).dot()
d.push()
d += elm.Line().left().to(Q5.base)
d += elm.Line().at(Q7.emitter).toy(Q5.base).dot()
d.pop()
d += elm.Line().right(d.unit/4)
d += (Q6 := elm.BjtNpn().anchor('base').label('Q6'))
d += elm.Line().at(Q6.emitter).length(d.unit/3).label('\nOFST\nNULL', 'right').hold()
d += elm.Resistor().down().at(Q6.emitter).label('R2\n1K').dot()
d += elm.Line().at(Q6.collector).toy(Q3.collector)
d += (Q4 := elm.BjtPnp().right().anchor('collector').label('Q4'))
d += elm.Line().at(Q4.base).tox(Q3.base)
d += elm.Line().at(Q4.emitter).toy(Q1.emitter)
d += (Q2 := elm.BjtNpn().left().flip().anchor('emitter').label('Q2', 'left').label('$-$IN', 'right'))
d += elm.Line().up(d.unit/3).at(Q2.collector).dot()
d += (Q8 := elm.BjtPnp().left().flip().anchor('base').label('Q8', 'left'))
d += elm.Line().at(Q8.collector).toy(Q2.collector).dot()
d += elm.Line().at(Q2.collector).tox(Q1.collector)
d += elm.Line().up(d.unit/4).at(Q8.emitter)
d += (top := elm.Line().tox(Q7.collector))
d += elm.Line().toy(Q7.collector)
d += elm.Line().right(d.unit*2).at(top.start)
d += elm.Line().down(d.unit/4)
d += (Q9 := elm.BjtPnp().right().anchor('emitter').label('Q9', ofst=-.1))
d += elm.Line().at(Q9.base).tox(Q8.base)
d += elm.Dot().at(Q4.base)
d += elm.Line().down(d.unit/2).at(Q4.base)
d += elm.Line().tox(Q9.collector).dot()
d += elm.Line().at(Q9.collector).toy(Q6.collector)
d += (Q10 := elm.BjtNpn().left().flip().anchor('collector').label('Q10', 'left'))
d += elm.Resistor().at(Q10.emitter).toy(R3.start).label('R4\n5K').dot()
d += (Q11 := elm.BjtNpn().right().at(Q10.base).anchor('base').label('Q11'))
d += elm.Dot().at(Q11.base)
d += elm.Line().up(d.unit/2)
d += elm.Line().tox(Q11.collector).dot()
d += elm.Line().at(Q11.emitter).toy(R3.start).dot()
d += elm.Line().up(d.unit*2).at(Q11.collector)
d += elm.Resistor().toy(Q9.collector).label('R5\n39K')
d += (Q12 := elm.BjtPnp().left().flip().anchor('collector').label('Q12', 'left', ofst=-.1))
d += elm.Line().up(d.unit/4).at(Q12.emitter).dot()
d += elm.Line().tox(Q9.emitter).dot()
d += elm.Line().right(d.unit/4).at(Q12.base).dot()
d += elm.Wire('|-').to(Q12.collector).dot().hold()
d += elm.Line().right(d.unit*1.5)
d += (Q13 := elm.BjtPnp().anchor('base').label('Q13'))
d += elm.Line().up(d.unit/4).dot()
d += elm.Line().tox(Q12.emitter)
d += (K := elm.Line().down(d.unit/5).at(Q13.collector).dot())
d += elm.Line().down()
d += (Q16 := elm.BjtNpn().right().anchor('collector').label('Q16', ofst=-.1))
d += elm.Line().left(d.unit/3).at(Q16.base).dot()
d += (R7 := elm.Resistor().up().toy(K.end).label('R7\n4.5K').dot())
d += elm.Line().tox(Q13.collector).hold()
d += (R8 := elm.Resistor().down().at(R7.start).label('R8\n7.5K').dot())
d += elm.Line().tox(Q16.emitter)
d += (J := elm.Dot())
d += elm.Line().toy(Q16.emitter)
d += (Q15 := elm.BjtNpn().right().at(R8.end).anchor('collector').label('Q15'))
d += elm.Line().left(d.unit/2).at(Q15.base).dot()
d += (C1 := elm.Capacitor().toy(R7.end).label('C1\n30pF'))
d += elm.Line().tox(Q13.collector)
d += elm.Line().at(C1.start).tox(Q6.collector).dot()
d += elm.Line().down(d.unit/2).at(J.center)
d += (Q19 := elm.BjtNpn().right().anchor('collector').label('Q19'))
d += elm.Line().at(Q19.base).tox(Q15.emitter).dot()
d += elm.Line().toy(Q15.emitter).hold()
d += elm.Line().down(d.unit/4).at(Q19.emitter).dot()
d += elm.Line().left()
d += (Q22 := elm.BjtNpn().left().anchor('base').flip().label('Q22', 'left'))
d += elm.Line().at(Q22.collector).toy(Q15.base).dot()
d += elm.Line().at(Q22.emitter).toy(R3.start).dot()
d += elm.Line().tox(R3.start).hold()
d += elm.Line().tox(Q15.emitter).dot()
d.push()
d += elm.Resistor().up().label('R12\n50K')
d += elm.Line().toy(Q19.base)
d.pop()
d += elm.Line().tox(Q19.emitter).dot()
d += (R11 := elm.Resistor().up().label('R11\n50'))
d += elm.Line().toy(Q19.emitter)
d += elm.Line().up(d.unit/4).at(Q13.emitter)
d += elm.Line().right(d.unit*1.5).dot()
d += elm.Line().length(d.unit/4).label('V+', 'right').hold()
d += elm.Line().down(d.unit*.75)
d += (Q14 := elm.BjtNpn().right().anchor('collector').label('Q14'))
d += elm.Line().left(d.unit/2).at(Q14.base)
d.push()
d += elm.Line().down(d.unit/2).idot()
d += (Q17 := elm.BjtNpn().left().anchor('collector').flip().label('Q17', 'left', ofst=-.1))
d += elm.Line().at(Q17.base).tox(Q14.emitter).dot()
d += (J := elm.Line().toy(Q14.emitter))
d.pop()
d += elm.Line().tox(Q13.collector).dot()
d += elm.Resistor().down().at(J.start).label('R9\n25').dot()
d += elm.Wire('-|').to(Q17.emitter).hold()
d += elm.Line().down(d.unit/4).dot()
d += elm.Line().right(d.unit/4).label('OUT', 'right').hold()
d += elm.Resistor().down().label('R10\n50')
d += (Q20 := elm.BjtPnp().right().anchor('emitter').label('Q20'))
d += elm.Wire('c', k=-1).at(Q20.base).to(Q15.collector)
d += elm.Line().at(Q20.collector).toy(R3.start).dot()
d += elm.Line().right(d.unit/4).label('V-', 'right').hold()
d += elm.Line().tox(R11.start)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/solidstate.rst
|
solidstate.rst
|
Solid State
-----------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
S-R Latch (Transistors)
^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q1 := elm.BjtNpn(circle=True).reverse().label('Q1', 'left'))
d += (Q2 := elm.BjtNpn(circle=True).at((d.unit*2, 0)).label('Q2'))
d += elm.Line().up(d.unit/2).at(Q1.collector)
d += (R1 := elm.Resistor().up().label('R1').hold())
d += elm.Dot().label('V1', 'left')
d += elm.Resistor().right(d.unit*.75).label('R3', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Set', 'right').hold()
d += elm.Line().to(Q2.base)
d += elm.Line().up(d.unit/2).at(Q2.collector)
d += elm.Dot().label('V2', 'right')
d += (R2 := elm.Resistor().up().label('R2', 'bottom').hold())
d += elm.Resistor().left(d.unit*.75).label('R4', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Reset', 'right').hold()
d += elm.Line().to(Q1.base)
d += elm.Line().down(d.unit/4).at(Q1.emitter)
d += (BOT := elm.Line().tox(Q2.emitter))
d += elm.Line().to(Q2.emitter)
d += elm.Dot().at(BOT.center)
d += elm.Ground().at(BOT.center)
d += (TOP := elm.Line().endpoints(R1.end, R2.end))
d += elm.Dot().at(TOP.center)
d += elm.Vdd().at(TOP.center).label('+Vcc')
741 Opamp Internal Schematic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12, unit=2.5)
d += (Q1 := elm.BjtNpn().label('Q1').label('+IN', 'left'))
d += (Q3 := elm.BjtPnp().left().at(Q1.emitter).anchor('emitter').flip().label('Q3', 'left'))
d += elm.Line().down().at(Q3.collector).dot()
d.push()
d += elm.Line().right(d.unit/4)
d += (Q7 := elm.BjtNpn().anchor('base').label('Q7'))
d.pop()
d += elm.Line().down(d.unit*1.25)
d += (Q5 := elm.BjtNpn().left().flip().anchor('collector').label('Q5', 'left'))
d += elm.Line().left(d.unit/2).at(Q5.emitter).label('OFST\nNULL', 'left').flip()
d += elm.Resistor().down().at(Q5.emitter).label('R1\n1K')
d += elm.Line().right(d.unit*.75).dot()
d += (R3 := elm.Resistor().up().label('R3\n50K'))
d += elm.Line().toy(Q5.base).dot()
d.push()
d += elm.Line().left().to(Q5.base)
d += elm.Line().at(Q7.emitter).toy(Q5.base).dot()
d.pop()
d += elm.Line().right(d.unit/4)
d += (Q6 := elm.BjtNpn().anchor('base').label('Q6'))
d += elm.Line().at(Q6.emitter).length(d.unit/3).label('\nOFST\nNULL', 'right').hold()
d += elm.Resistor().down().at(Q6.emitter).label('R2\n1K').dot()
d += elm.Line().at(Q6.collector).toy(Q3.collector)
d += (Q4 := elm.BjtPnp().right().anchor('collector').label('Q4'))
d += elm.Line().at(Q4.base).tox(Q3.base)
d += elm.Line().at(Q4.emitter).toy(Q1.emitter)
d += (Q2 := elm.BjtNpn().left().flip().anchor('emitter').label('Q2', 'left').label('$-$IN', 'right'))
d += elm.Line().up(d.unit/3).at(Q2.collector).dot()
d += (Q8 := elm.BjtPnp().left().flip().anchor('base').label('Q8', 'left'))
d += elm.Line().at(Q8.collector).toy(Q2.collector).dot()
d += elm.Line().at(Q2.collector).tox(Q1.collector)
d += elm.Line().up(d.unit/4).at(Q8.emitter)
d += (top := elm.Line().tox(Q7.collector))
d += elm.Line().toy(Q7.collector)
d += elm.Line().right(d.unit*2).at(top.start)
d += elm.Line().down(d.unit/4)
d += (Q9 := elm.BjtPnp().right().anchor('emitter').label('Q9', ofst=-.1))
d += elm.Line().at(Q9.base).tox(Q8.base)
d += elm.Dot().at(Q4.base)
d += elm.Line().down(d.unit/2).at(Q4.base)
d += elm.Line().tox(Q9.collector).dot()
d += elm.Line().at(Q9.collector).toy(Q6.collector)
d += (Q10 := elm.BjtNpn().left().flip().anchor('collector').label('Q10', 'left'))
d += elm.Resistor().at(Q10.emitter).toy(R3.start).label('R4\n5K').dot()
d += (Q11 := elm.BjtNpn().right().at(Q10.base).anchor('base').label('Q11'))
d += elm.Dot().at(Q11.base)
d += elm.Line().up(d.unit/2)
d += elm.Line().tox(Q11.collector).dot()
d += elm.Line().at(Q11.emitter).toy(R3.start).dot()
d += elm.Line().up(d.unit*2).at(Q11.collector)
d += elm.Resistor().toy(Q9.collector).label('R5\n39K')
d += (Q12 := elm.BjtPnp().left().flip().anchor('collector').label('Q12', 'left', ofst=-.1))
d += elm.Line().up(d.unit/4).at(Q12.emitter).dot()
d += elm.Line().tox(Q9.emitter).dot()
d += elm.Line().right(d.unit/4).at(Q12.base).dot()
d += elm.Wire('|-').to(Q12.collector).dot().hold()
d += elm.Line().right(d.unit*1.5)
d += (Q13 := elm.BjtPnp().anchor('base').label('Q13'))
d += elm.Line().up(d.unit/4).dot()
d += elm.Line().tox(Q12.emitter)
d += (K := elm.Line().down(d.unit/5).at(Q13.collector).dot())
d += elm.Line().down()
d += (Q16 := elm.BjtNpn().right().anchor('collector').label('Q16', ofst=-.1))
d += elm.Line().left(d.unit/3).at(Q16.base).dot()
d += (R7 := elm.Resistor().up().toy(K.end).label('R7\n4.5K').dot())
d += elm.Line().tox(Q13.collector).hold()
d += (R8 := elm.Resistor().down().at(R7.start).label('R8\n7.5K').dot())
d += elm.Line().tox(Q16.emitter)
d += (J := elm.Dot())
d += elm.Line().toy(Q16.emitter)
d += (Q15 := elm.BjtNpn().right().at(R8.end).anchor('collector').label('Q15'))
d += elm.Line().left(d.unit/2).at(Q15.base).dot()
d += (C1 := elm.Capacitor().toy(R7.end).label('C1\n30pF'))
d += elm.Line().tox(Q13.collector)
d += elm.Line().at(C1.start).tox(Q6.collector).dot()
d += elm.Line().down(d.unit/2).at(J.center)
d += (Q19 := elm.BjtNpn().right().anchor('collector').label('Q19'))
d += elm.Line().at(Q19.base).tox(Q15.emitter).dot()
d += elm.Line().toy(Q15.emitter).hold()
d += elm.Line().down(d.unit/4).at(Q19.emitter).dot()
d += elm.Line().left()
d += (Q22 := elm.BjtNpn().left().anchor('base').flip().label('Q22', 'left'))
d += elm.Line().at(Q22.collector).toy(Q15.base).dot()
d += elm.Line().at(Q22.emitter).toy(R3.start).dot()
d += elm.Line().tox(R3.start).hold()
d += elm.Line().tox(Q15.emitter).dot()
d.push()
d += elm.Resistor().up().label('R12\n50K')
d += elm.Line().toy(Q19.base)
d.pop()
d += elm.Line().tox(Q19.emitter).dot()
d += (R11 := elm.Resistor().up().label('R11\n50'))
d += elm.Line().toy(Q19.emitter)
d += elm.Line().up(d.unit/4).at(Q13.emitter)
d += elm.Line().right(d.unit*1.5).dot()
d += elm.Line().length(d.unit/4).label('V+', 'right').hold()
d += elm.Line().down(d.unit*.75)
d += (Q14 := elm.BjtNpn().right().anchor('collector').label('Q14'))
d += elm.Line().left(d.unit/2).at(Q14.base)
d.push()
d += elm.Line().down(d.unit/2).idot()
d += (Q17 := elm.BjtNpn().left().anchor('collector').flip().label('Q17', 'left', ofst=-.1))
d += elm.Line().at(Q17.base).tox(Q14.emitter).dot()
d += (J := elm.Line().toy(Q14.emitter))
d.pop()
d += elm.Line().tox(Q13.collector).dot()
d += elm.Resistor().down().at(J.start).label('R9\n25').dot()
d += elm.Wire('-|').to(Q17.emitter).hold()
d += elm.Line().down(d.unit/4).dot()
d += elm.Line().right(d.unit/4).label('OUT', 'right').hold()
d += elm.Resistor().down().label('R10\n50')
d += (Q20 := elm.BjtPnp().right().anchor('emitter').label('Q20'))
d += elm.Wire('c', k=-1).at(Q20.base).to(Q15.collector)
d += elm.Line().at(Q20.collector).toy(R3.start).dot()
d += elm.Line().right(d.unit/4).label('V-', 'right').hold()
d += elm.Line().tox(R11.start)
| 0.648466 | 0.528898 |
.. _galleryflow:
Flowcharting
------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import flow
Flowchart elements are defined in the :py:mod:`flow` module.
.. code-block:: python
from schemdraw import flow
It's a Trap!
^^^^^^^^^^^^
Recreation of `XKCD 1195 <https://xkcd.com/1195/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += flow.Start().label('START')
d += flow.Arrow().down(d.unit/3)
d += (h := flow.Decision(w=5.5, h=4, S='YES').label('Hey, wait,\nthis flowchart\nis a trap!'))
d += flow.Line().down(d.unit/4)
d += flow.Wire('c', k=3.5, arrow='->').to(h.E)
Flowchart for flowcharts
^^^^^^^^^^^^^^^^^^^^^^^^
Recreation of `XKCD 518 <https://xkcd.com/518/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=11)
d += (b := flow.Start().label('START'))
d += flow.Arrow().down(d.unit/2)
d += (d1 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('DO YOU\nUNDERSTAND\nFLOW CHARTS?'))
d += flow.Arrow().length(d.unit/2)
d += (d2 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('OKAY,\nYOU SEE THE\nLINE LABELED\n"YES"?'))
d += flow.Arrow().length(d.unit/2)
d += (d3 := flow.Decision(w=5.2, h=3.9, E='YES', S='NO').label('BUT YOU\nSEE THE ONES\nLABELED "NO".'))
d += flow.Arrow().right(d.unit/2).at(d3.E)
d += flow.Box(w=2, h=1.25).anchor('W').label('WAIT,\nWHAT?')
d += flow.Arrow().down(d.unit/2).at(d3.S)
d += (listen := flow.Box(w=2, h=1).label('LISTEN.'))
d += flow.Arrow().right(d.unit/2).at(listen.E)
d += (hate := flow.Box(w=2, h=1.25).anchor('W').label('I HATE\nYOU.'))
d += flow.Arrow().right(d.unit*3.5).at(d1.E)
d += (good := flow.Box(w=2, h=1).anchor('W').label('GOOD'))
d += flow.Arrow().right(d.unit*1.5).at(d2.E)
d += (d4 := flow.Decision(w=5.3, h=4.0, E='YES', S='NO').anchor('W').label('...AND YOU CAN\nSEE THE ONES\nLABELED "NO"?'))
d += flow.Wire('-|', arrow='->').at(d4.E).to(good.S)
d += flow.Arrow().down(d.unit/2).at(d4.S)
d += (d5 := flow.Decision(w=5, h=3.6, E='YES', S='NO').label('BUT YOU\nJUST FOLLOWED\nTHEM TWICE!'))
d += flow.Arrow().right().at(d5.E)
d += (question := flow.Box(w=3.5, h=1.75).anchor('W').label("(THAT WASN'T\nA QUESTION.)"))
d += flow.Wire('n', k=-1, arrow='->').at(d5.S).to(question.S)
d += flow.Line().at(good.E).tox(question.S)
d += flow.Arrow().down()
d += (drink := flow.Box(w=2.5, h=1.5).label("LET'S GO\nDRINK."))
d += flow.Arrow().right().at(drink.E).label('6 DRINKS')
d += flow.Box(w=3.7, h=2).anchor('W').label('HEY, I SHOULD\nTRY INSTALLING\nFREEBSD!')
d += flow.Arrow().up(d.unit*.75).at(question.N)
d += (screw := flow.Box(w=2.5, h=1).anchor('S').label('SCREW IT.'))
d += flow.Arrow().at(screw.N).toy(drink.S)
State Machine Acceptor
^^^^^^^^^^^^^^^^^^^^^^
`Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:DFAexample.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Arrow().length(1)
d += (s1 := flow.StateEnd().anchor('W').label('$S_1$'))
d += elm.Arc2(arrow='<-').at(s1.NE).label('0')
d += (s2 := flow.State().anchor('NW').label('$S_2$'))
d += elm.Arc2(arrow='<-').at(s2.SW).to(s1.SE).label('0')
d += elm.ArcLoop(arrow='<-').at(s2.NE).to(s2.E).label('1')
d += elm.ArcLoop(arrow='<-').at(s1.NW).to(s1.N).label('1')
Door Controller
^^^^^^^^^^^^^^^
`Diagram Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:Fsm_Moore_model_door_control.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
delta = 4
d += (c4 := flow.Circle(r=1).label('4\nopening'))
d += (c1 := flow.Circle(r=1).at((delta, delta)).label('1\nopened'))
d += (c2 := flow.Circle(r=1).at((2*delta, 0)).label('2\nclosing'))
d += (c3 := flow.Circle(r=1).at((delta, -delta)).label('3\nclosed'))
d += elm.Arc2(arrow='->', k=.3).at(c4.NNE).to(c1.WSW).label('sensor\nopened')
d += elm.Arc2(arrow='->', k=.3).at(c1.ESE).to(c2.NNW).label('close')
d += elm.Arc2(arrow='->', k=.3).at(c2.SSW).to(c3.ENE).label('sensor\nclosed')
d += elm.Arc2(arrow='->', k=.3).at(c3.WNW).to(c4.SSE).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c4.ENE).to(c2.WNW).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c2.WSW).to(c4.ESE).label('close')
Another State Machine
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as dwg:
dwg += (a := flow.Circle().label('a').fill('lightblue'))
dwg += (b := flow.Circle().at((4, 0)).label('b').fill('lightblue'))
dwg += (c := flow.Circle().at((8, 0)).label('c').fill('lightblue'))
dwg += (f := flow.Circle().at((0, -4)).label('f').fill('lightblue'))
dwg += (e := flow.Circle().at((4, -6)).label('e').fill('lightblue'))
dwg += (d := flow.Circle().at((8, -4)).label('d').fill('lightblue'))
dwg += elm.ArcLoop(arrow='->').at(a.NW).to(a.NNE).label('00/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(b.NNW).to(b.NE).label('01/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(c.NNW).to(c.NE).label('11/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(d.E).to(d.SE).label('10/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(e.SSE).to(e.SW).label('11/1', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(f.S).to(f.SW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ENE).to(b.WNW).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.W).to(a.E).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.ENE).to(c.WNW).label('11/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.W).to(b.E).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ESE).to(d.NW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(d.WNW).to(a.SE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.ENE).to(e.NW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(e.WNW).to(f.ESE).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(e.NE).to(d.WSW).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(d.SSW).to(e.ENE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.NNW).to(a.SSW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.SSE).to(d.NNE).label('10/0', fontsize=10)
Logical Flow Diagram
^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(unit=1) as dwg:
dwg += (a := flow.Circle(r=.5).label('a'))
dwg += (x := flow.Decision(w=1.5, h=1.5).label('$X$').at(a.S).anchor('N'))
dwg += elm.RightLines(arrow='->').at(x.E).label('$\overline{X}$')
dwg += (y1 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg.move_from(y1.N, dx=-5)
dwg += (y2 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg += elm.RightLines(arrow='->').at(x.W).to(y2.N).label('$X$')
dwg += elm.Arrow().at(y2.S).label('$Y$')
dwg += (b := flow.Circle(r=.5).label('b'))
dwg.move_from(b.N, dx=2)
dwg += (c := flow.Circle(r=.5).label('c'))
dwg += elm.RightLines(arrow='->').at(y2.E).to(c.N).label('$\overline{Y}$')
dwg += elm.Arrow().at(y1.S).label('$Y$')
dwg += (d := flow.Circle(r=.5).label('d'))
dwg.move_from(d.N, dx=2)
dwg += (e := flow.Circle(r=.5).label('e'))
dwg += elm.RightLines(arrow='->').at(y1.E).to(e.N).label('$\overline{Y}$')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/flowcharting.rst
|
flowcharting.rst
|
.. _galleryflow:
Flowcharting
------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import flow
Flowchart elements are defined in the :py:mod:`flow` module.
.. code-block:: python
from schemdraw import flow
It's a Trap!
^^^^^^^^^^^^
Recreation of `XKCD 1195 <https://xkcd.com/1195/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += flow.Start().label('START')
d += flow.Arrow().down(d.unit/3)
d += (h := flow.Decision(w=5.5, h=4, S='YES').label('Hey, wait,\nthis flowchart\nis a trap!'))
d += flow.Line().down(d.unit/4)
d += flow.Wire('c', k=3.5, arrow='->').to(h.E)
Flowchart for flowcharts
^^^^^^^^^^^^^^^^^^^^^^^^
Recreation of `XKCD 518 <https://xkcd.com/518/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=11)
d += (b := flow.Start().label('START'))
d += flow.Arrow().down(d.unit/2)
d += (d1 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('DO YOU\nUNDERSTAND\nFLOW CHARTS?'))
d += flow.Arrow().length(d.unit/2)
d += (d2 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('OKAY,\nYOU SEE THE\nLINE LABELED\n"YES"?'))
d += flow.Arrow().length(d.unit/2)
d += (d3 := flow.Decision(w=5.2, h=3.9, E='YES', S='NO').label('BUT YOU\nSEE THE ONES\nLABELED "NO".'))
d += flow.Arrow().right(d.unit/2).at(d3.E)
d += flow.Box(w=2, h=1.25).anchor('W').label('WAIT,\nWHAT?')
d += flow.Arrow().down(d.unit/2).at(d3.S)
d += (listen := flow.Box(w=2, h=1).label('LISTEN.'))
d += flow.Arrow().right(d.unit/2).at(listen.E)
d += (hate := flow.Box(w=2, h=1.25).anchor('W').label('I HATE\nYOU.'))
d += flow.Arrow().right(d.unit*3.5).at(d1.E)
d += (good := flow.Box(w=2, h=1).anchor('W').label('GOOD'))
d += flow.Arrow().right(d.unit*1.5).at(d2.E)
d += (d4 := flow.Decision(w=5.3, h=4.0, E='YES', S='NO').anchor('W').label('...AND YOU CAN\nSEE THE ONES\nLABELED "NO"?'))
d += flow.Wire('-|', arrow='->').at(d4.E).to(good.S)
d += flow.Arrow().down(d.unit/2).at(d4.S)
d += (d5 := flow.Decision(w=5, h=3.6, E='YES', S='NO').label('BUT YOU\nJUST FOLLOWED\nTHEM TWICE!'))
d += flow.Arrow().right().at(d5.E)
d += (question := flow.Box(w=3.5, h=1.75).anchor('W').label("(THAT WASN'T\nA QUESTION.)"))
d += flow.Wire('n', k=-1, arrow='->').at(d5.S).to(question.S)
d += flow.Line().at(good.E).tox(question.S)
d += flow.Arrow().down()
d += (drink := flow.Box(w=2.5, h=1.5).label("LET'S GO\nDRINK."))
d += flow.Arrow().right().at(drink.E).label('6 DRINKS')
d += flow.Box(w=3.7, h=2).anchor('W').label('HEY, I SHOULD\nTRY INSTALLING\nFREEBSD!')
d += flow.Arrow().up(d.unit*.75).at(question.N)
d += (screw := flow.Box(w=2.5, h=1).anchor('S').label('SCREW IT.'))
d += flow.Arrow().at(screw.N).toy(drink.S)
State Machine Acceptor
^^^^^^^^^^^^^^^^^^^^^^
`Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:DFAexample.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Arrow().length(1)
d += (s1 := flow.StateEnd().anchor('W').label('$S_1$'))
d += elm.Arc2(arrow='<-').at(s1.NE).label('0')
d += (s2 := flow.State().anchor('NW').label('$S_2$'))
d += elm.Arc2(arrow='<-').at(s2.SW).to(s1.SE).label('0')
d += elm.ArcLoop(arrow='<-').at(s2.NE).to(s2.E).label('1')
d += elm.ArcLoop(arrow='<-').at(s1.NW).to(s1.N).label('1')
Door Controller
^^^^^^^^^^^^^^^
`Diagram Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:Fsm_Moore_model_door_control.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
delta = 4
d += (c4 := flow.Circle(r=1).label('4\nopening'))
d += (c1 := flow.Circle(r=1).at((delta, delta)).label('1\nopened'))
d += (c2 := flow.Circle(r=1).at((2*delta, 0)).label('2\nclosing'))
d += (c3 := flow.Circle(r=1).at((delta, -delta)).label('3\nclosed'))
d += elm.Arc2(arrow='->', k=.3).at(c4.NNE).to(c1.WSW).label('sensor\nopened')
d += elm.Arc2(arrow='->', k=.3).at(c1.ESE).to(c2.NNW).label('close')
d += elm.Arc2(arrow='->', k=.3).at(c2.SSW).to(c3.ENE).label('sensor\nclosed')
d += elm.Arc2(arrow='->', k=.3).at(c3.WNW).to(c4.SSE).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c4.ENE).to(c2.WNW).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c2.WSW).to(c4.ESE).label('close')
Another State Machine
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as dwg:
dwg += (a := flow.Circle().label('a').fill('lightblue'))
dwg += (b := flow.Circle().at((4, 0)).label('b').fill('lightblue'))
dwg += (c := flow.Circle().at((8, 0)).label('c').fill('lightblue'))
dwg += (f := flow.Circle().at((0, -4)).label('f').fill('lightblue'))
dwg += (e := flow.Circle().at((4, -6)).label('e').fill('lightblue'))
dwg += (d := flow.Circle().at((8, -4)).label('d').fill('lightblue'))
dwg += elm.ArcLoop(arrow='->').at(a.NW).to(a.NNE).label('00/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(b.NNW).to(b.NE).label('01/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(c.NNW).to(c.NE).label('11/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(d.E).to(d.SE).label('10/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(e.SSE).to(e.SW).label('11/1', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(f.S).to(f.SW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ENE).to(b.WNW).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.W).to(a.E).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.ENE).to(c.WNW).label('11/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.W).to(b.E).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ESE).to(d.NW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(d.WNW).to(a.SE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.ENE).to(e.NW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(e.WNW).to(f.ESE).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(e.NE).to(d.WSW).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(d.SSW).to(e.ENE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.NNW).to(a.SSW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.SSE).to(d.NNE).label('10/0', fontsize=10)
Logical Flow Diagram
^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(unit=1) as dwg:
dwg += (a := flow.Circle(r=.5).label('a'))
dwg += (x := flow.Decision(w=1.5, h=1.5).label('$X$').at(a.S).anchor('N'))
dwg += elm.RightLines(arrow='->').at(x.E).label('$\overline{X}$')
dwg += (y1 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg.move_from(y1.N, dx=-5)
dwg += (y2 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg += elm.RightLines(arrow='->').at(x.W).to(y2.N).label('$X$')
dwg += elm.Arrow().at(y2.S).label('$Y$')
dwg += (b := flow.Circle(r=.5).label('b'))
dwg.move_from(b.N, dx=2)
dwg += (c := flow.Circle(r=.5).label('c'))
dwg += elm.RightLines(arrow='->').at(y2.E).to(c.N).label('$\overline{Y}$')
dwg += elm.Arrow().at(y1.S).label('$Y$')
dwg += (d := flow.Circle(r=.5).label('d'))
dwg.move_from(d.N, dx=2)
dwg += (e := flow.Circle(r=.5).label('e'))
dwg += elm.RightLines(arrow='->').at(y1.E).to(e.N).label('$\overline{Y}$')
| 0.642545 | 0.50238 |
Analog Circuits
---------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
Discharging capacitor
^^^^^^^^^^^^^^^^^^^^^
Shows how to connect to a switch with anchors.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (V1 := elm.SourceV().label('5V'))
d += elm.Line().right(d.unit*.75)
d += (S1 := elm.SwitchSpdt2(action='close').up().anchor('b').label('$t=0$', loc='rgt'))
d += elm.Line().right(d.unit*.75).at(S1.c)
d += elm.Resistor().down().label('$100\Omega$').label(['+','$v_o$','-'], loc='bot')
d += elm.Line().to(V1.start)
d += elm.Capacitor().at(S1.a).toy(V1.start).label('1$\mu$F').dot()
Capacitor Network
^^^^^^^^^^^^^^^^^
Shows how to use endpoints to specify exact start and end placement.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (C1 := elm.Capacitor().label('8nF').idot().label('a', 'left'))
d += (C2 := elm.Capacitor().label('18nF'))
d += (C3 := elm.Capacitor().down().label('8nF', loc='bottom'))
d += (C4 := elm.Capacitor().left().label('32nF'))
d += (C5 := elm.Capacitor().label('40nF', loc='bottom').dot().label('b', 'left'))
d += (C6 := elm.Capacitor().endpoints(C1.end, C5.start).label('2.8nF'))
d += (C7 := elm.Capacitor().endpoints(C2.end, C5.start)
.label('5.6nF', loc='center', ofst=(-.3, -.1), halign='right', valign='bottom'))
ECE201-Style Circuit
^^^^^^^^^^^^^^^^^^^^
This example demonstrate use of `push()` and `pop()` and using the 'tox' and 'toy' methods.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=2) # unit=2 makes elements have shorter than normal leads
d.push()
d += (R1 := elm.Resistor().down().label('20Ω'))
d += (V1 := elm.SourceV().down().reverse().label('120V'))
d += elm.Line().right(3).dot()
d.pop()
d += elm.Line().right(3).dot()
d += elm.SourceV().down().reverse().label('60V')
d += elm.Resistor().label('5Ω').dot()
d += elm.Line().right(3).dot()
d += elm.SourceI().up().label('36A')
d += elm.Resistor().label('10Ω').dot()
d += elm.Line().left(3).hold()
d += elm.Line().right(3).dot()
d += (R6 := elm.Resistor().toy(V1.end).label('6Ω').dot())
d += elm.Line().left(3).hold()
d += elm.Resistor().right().at(R6.start).label('1.6Ω').dot(open=True).label('a', 'right')
d += elm.Line().right().at(R6.end).dot(open=True).label('b', 'right')
Loop Currents
^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.lines.LoopCurrent` element to add loop currents, and rotating a label to make it fit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=5)
d += (V1 := elm.SourceV().label('20V'))
d += (R1 := elm.Resistor().right().label('400Ω'))
d += elm.Dot()
d.push()
d += (R2 := elm.Resistor().down().label('100Ω', loc='bot', rotate=True))
d += elm.Dot()
d.pop()
d += (L1 := elm.Line())
d += (I1 := elm.SourceI().down().label('1A', loc='bot'))
d += (L2 := elm.Line().tox(V1.start))
d += elm.LoopCurrent([R1,R2,L2,V1], pad=1.25).label('$I_1$')
d += elm.LoopCurrent([R1,I1,L2,R2], pad=1.25).label('$I_2$') # Use R1 as top element for both so they get the same height
AC Loop Analysis
^^^^^^^^^^^^^^^^
Another good problem for ECE students...
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (I1 := elm.SourceI().label('5∠0° A').dot())
d.push()
d += elm.Capacitor().right().label('-j3Ω').dot()
d += elm.Inductor().down().label('j2Ω').dot().hold()
d += elm.Resistor().right().label('5Ω').dot()
d += (V1 := elm.SourceV().down().reverse().label('5∠-90° V', loc='bot'))
d += elm.Line().tox(I1.start)
d.pop()
d += elm.Line().up(d.unit*.8)
d += (L1 := elm.Inductor().tox(V1.start).label('j3Ω'))
d += elm.Line().down(d.unit*.8)
d += elm.CurrentLabel(top=False, ofst=.3).at(L1).label('$i_g$')
Infinite Transmission Line
^^^^^^^^^^^^^^^^^^^^^^^^^^
Elements can be added inside for-loops if you need multiples.
The ellipsis is just another circuit element, called `DotDotDot` since Ellipsis is a reserved keyword in Python.
This also demonstrates the :py:class:`schemdraw.elements.ElementDrawing` class to merge multiple elements into a single definition.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2:
for i in range(3):
d2 += elm.ElementDrawing(d1)
d2.push()
d2 += elm.Line().length(d2.unit/6)
d2 += elm.DotDotDot()
d2 += elm.ElementDrawing(d1)
d2.pop()
d2.here = (d2.here[0], d2.here[1]-d2.unit)
d2 += elm.Line().right().length(d2.unit/6)
d2 += elm.DotDotDot()
Power supply
^^^^^^^^^^^^
Notice the diodes could be added individually, but here the built-in `Rectifier` element is used instead.
Also note the use of newline characters inside resistor and capacitor labels.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(inches_per_unit=.5, unit=3)
d += (D := elm.Rectifier())
d += elm.Line().left(d.unit*1.5).at(D.N).dot(open=True).idot()
d += elm.Line().left(d.unit*1.5).at(D.S).dot(open=True).idot()
d += (G := elm.Gap().toy(D.N).label(['–', 'AC IN', '+']))
d += (top := elm.Line().right(d.unit*3).at(D.E).idot())
d += (Q2 := elm.BjtNpn(circle=True).up().anchor('collector').label('Q2\n2n3055'))
d += elm.Line().down(d.unit/2).at(Q2.base)
d += (Q2b := elm.Dot())
d += elm.Line().left(d.unit/3)
d += (Q1 := elm.BjtNpn(circle=True).up().anchor('emitter').label('Q1\n 2n3054'))
d += elm.Line().at(Q1.collector).toy(top.center).dot()
d += elm.Line().down(d.unit/2).at(Q1.base).dot()
d += elm.Zener().down().reverse().label('D2\n500mA', loc='bot').dot()
d += (G := elm.Ground())
d += elm.Line().left().dot()
d += elm.Capacitor(polar=True).up().reverse().label('C2\n100$\mu$F\n50V', loc='bot').dot()
d += elm.Line().right().hold()
d += elm.Resistor().toy(top.end).label('R1\n2.2K\n50V', loc='bot').dot()
d.move(dx=-d.unit, dy=0)
d += elm.Capacitor(polar=True).toy(G.start).flip().label('C1\n 1000$\mu$F\n50V').dot().idot()
d += elm.Line().at(G.start).tox(D.W)
d += elm.Line().toy(D.W).dot()
d += elm.Resistor().right().at(Q2b.center).label('R2').label('56$\Omega$ 1W', loc='bot').dot()
d.push()
d += elm.Line().toy(top.start).dot()
d += elm.Line().tox(Q2.emitter)
d.pop()
d += elm.Capacitor(polar=True).toy(G.start).label('C3\n470$\mu$F\n50V', loc='bot').dot()
d += elm.Line().tox(G.start).hold()
d += elm.Line().right().dot()
d += elm.Resistor().toy(top.center).label('R3\n10K\n1W', loc='bot').dot()
d += elm.Line().left().hold()
d += elm.Line().right()
d += elm.Dot(open=True)
d += elm.Gap().toy(G.start).label(['+', '$V_{out}$', '–'])
d += elm.Dot(open=True)
d += elm.Line().left()
5-transistor Operational Transconductance Amplifer (OTA)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the use of current labels to show the bias currents.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# tail transistor
d += (Q1 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Line().down().length(0.5)
ground = d.here
d += elm.Ground()
# input pair
d += elm.Line().left().length(1).at(Q1.drain)
d += (Q2 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Dot().at(Q1.drain)
d += elm.Line().right().length(1)
d += (Q3 := elm.AnalogNFet()).anchor('source').theta(0)
# current mirror
d += (Q4 := elm.AnalogPFet()).anchor('drain').at(Q2.drain).theta(0)
d += (Q5 := elm.AnalogPFet()).anchor('drain').at(Q3.drain).theta(0).reverse()
d += elm.Line().right().at(Q4.gate).to(Q5.gate)
d += elm.Dot().at(0.5*(Q4.gate + Q5.gate))
d += elm.Line().down().toy(Q4.drain)
d += elm.Line().left().tox(Q4.drain)
d += elm.Dot()
# vcc connection
d += elm.Line().right().at(Q4.source).to(Q5.source)
d += elm.Dot().at(0.5*(Q4.source + Q5.source))
d += elm.Vdd()
# bias source
d += elm.Line().left().length(0.25).at(Q1.gate)
d += elm.SourceV().down().toy(ground).reverse().scale(0.5).label("Bias")
d += elm.Ground()
# signal labels
d += elm.Tag().at(Q2.gate).label("In+").left()
d += elm.Tag().at(Q3.gate).label("In−").right()
d += elm.Dot().at(Q3.drain)
d += elm.Line().right().tox(Q3.gate)
d += elm.Tag().right().label("Out").reverse()
# bias currents
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q1).label("20µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q4).label("10µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q5).label("10µA")
Quadruple loop negative feedback amplifier
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# place twoports
d += (N1 := elm.Nullor()).anchor('center')
d += (T1 := elm.TransimpedanceTransactor(reverse_output=True)).reverse().flip().anchor('center').at([0,-3]).label("B")
d += (T2 := elm.CurrentTransactor()).reverse().flip().anchor('center').at([0,-6]).label("D")
d += (T3 := elm.VoltageTransactor()).reverse().anchor('center').at([0,-9]).label("A")
d += (T4 := elm.TransadmittanceTransactor(reverse_output=True)).reverse().anchor('center').at([0,-12]).label("C")
## make connections
# right side
d += elm.Line().at(N1.out_n).to(T1.in_n)
d += elm.Line().at(T1.in_p).to(T2.in_n)
d += elm.Line().at(T3.in_n).to(T4.in_n)
d += elm.Line().right().length(1).at(N1.out_p)
pre_out = d.here
d += (outline := elm.Line()).right().length(1).dot(open=True)
out = d.here
d += elm.Gap().down().label(('+','$V_o$','–')).toy(N1.out_n)
d += elm.Line().idot(open=True).down().toy(T4.in_n)
d += elm.Line().left().to(T4.in_n)
d += elm.Dot()
d += elm.CurrentLabelInline(direction='in', ofst=-0.15).at(outline).label('$I_o$')
d += elm.Line().at(T2.in_p).right().tox(out)
d += elm.Dot()
d += elm.Line().right().at(T4.in_p).tox(pre_out)
d += elm.Line().up().toy(pre_out)
d += elm.Dot()
d += elm.Line().right().at(T3.in_p).tox(pre_out)
d += elm.Dot()
# left side
d += elm.Line().down().at(N1.in_n).to(T1.out_n)
d += elm.Line().up().at(T3.out_p).to(T1.out_p)
d += elm.Line().left().at(N1.in_p).length(1)
pre_in = d.here
d += (inline := elm.Line()).length(1).dot(open=True).left()
in_node = d.here
d += elm.Gap().down().label(('+','$V_i$','–')).toy(N1.in_n)
d += elm.Line().idot(open=True).down().toy(T4.out_n)
d += elm.Line().right().to(T4.out_n)
d += elm.CurrentLabelInline(direction='out', ofst=-0.15).at(inline).label('$I_i$')
d += elm.Line().left().at(T2.out_p).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T3.out_n).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T4.out_p).tox(pre_in)
d += elm.Line().up().toy(pre_in)
d += elm.Dot()
d += elm.Line().left().at(T2.out_n).tox(pre_in)
d += elm.Dot()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/analog.rst
|
analog.rst
|
Analog Circuits
---------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
Discharging capacitor
^^^^^^^^^^^^^^^^^^^^^
Shows how to connect to a switch with anchors.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (V1 := elm.SourceV().label('5V'))
d += elm.Line().right(d.unit*.75)
d += (S1 := elm.SwitchSpdt2(action='close').up().anchor('b').label('$t=0$', loc='rgt'))
d += elm.Line().right(d.unit*.75).at(S1.c)
d += elm.Resistor().down().label('$100\Omega$').label(['+','$v_o$','-'], loc='bot')
d += elm.Line().to(V1.start)
d += elm.Capacitor().at(S1.a).toy(V1.start).label('1$\mu$F').dot()
Capacitor Network
^^^^^^^^^^^^^^^^^
Shows how to use endpoints to specify exact start and end placement.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (C1 := elm.Capacitor().label('8nF').idot().label('a', 'left'))
d += (C2 := elm.Capacitor().label('18nF'))
d += (C3 := elm.Capacitor().down().label('8nF', loc='bottom'))
d += (C4 := elm.Capacitor().left().label('32nF'))
d += (C5 := elm.Capacitor().label('40nF', loc='bottom').dot().label('b', 'left'))
d += (C6 := elm.Capacitor().endpoints(C1.end, C5.start).label('2.8nF'))
d += (C7 := elm.Capacitor().endpoints(C2.end, C5.start)
.label('5.6nF', loc='center', ofst=(-.3, -.1), halign='right', valign='bottom'))
ECE201-Style Circuit
^^^^^^^^^^^^^^^^^^^^
This example demonstrate use of `push()` and `pop()` and using the 'tox' and 'toy' methods.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=2) # unit=2 makes elements have shorter than normal leads
d.push()
d += (R1 := elm.Resistor().down().label('20Ω'))
d += (V1 := elm.SourceV().down().reverse().label('120V'))
d += elm.Line().right(3).dot()
d.pop()
d += elm.Line().right(3).dot()
d += elm.SourceV().down().reverse().label('60V')
d += elm.Resistor().label('5Ω').dot()
d += elm.Line().right(3).dot()
d += elm.SourceI().up().label('36A')
d += elm.Resistor().label('10Ω').dot()
d += elm.Line().left(3).hold()
d += elm.Line().right(3).dot()
d += (R6 := elm.Resistor().toy(V1.end).label('6Ω').dot())
d += elm.Line().left(3).hold()
d += elm.Resistor().right().at(R6.start).label('1.6Ω').dot(open=True).label('a', 'right')
d += elm.Line().right().at(R6.end).dot(open=True).label('b', 'right')
Loop Currents
^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.lines.LoopCurrent` element to add loop currents, and rotating a label to make it fit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=5)
d += (V1 := elm.SourceV().label('20V'))
d += (R1 := elm.Resistor().right().label('400Ω'))
d += elm.Dot()
d.push()
d += (R2 := elm.Resistor().down().label('100Ω', loc='bot', rotate=True))
d += elm.Dot()
d.pop()
d += (L1 := elm.Line())
d += (I1 := elm.SourceI().down().label('1A', loc='bot'))
d += (L2 := elm.Line().tox(V1.start))
d += elm.LoopCurrent([R1,R2,L2,V1], pad=1.25).label('$I_1$')
d += elm.LoopCurrent([R1,I1,L2,R2], pad=1.25).label('$I_2$') # Use R1 as top element for both so they get the same height
AC Loop Analysis
^^^^^^^^^^^^^^^^
Another good problem for ECE students...
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (I1 := elm.SourceI().label('5∠0° A').dot())
d.push()
d += elm.Capacitor().right().label('-j3Ω').dot()
d += elm.Inductor().down().label('j2Ω').dot().hold()
d += elm.Resistor().right().label('5Ω').dot()
d += (V1 := elm.SourceV().down().reverse().label('5∠-90° V', loc='bot'))
d += elm.Line().tox(I1.start)
d.pop()
d += elm.Line().up(d.unit*.8)
d += (L1 := elm.Inductor().tox(V1.start).label('j3Ω'))
d += elm.Line().down(d.unit*.8)
d += elm.CurrentLabel(top=False, ofst=.3).at(L1).label('$i_g$')
Infinite Transmission Line
^^^^^^^^^^^^^^^^^^^^^^^^^^
Elements can be added inside for-loops if you need multiples.
The ellipsis is just another circuit element, called `DotDotDot` since Ellipsis is a reserved keyword in Python.
This also demonstrates the :py:class:`schemdraw.elements.ElementDrawing` class to merge multiple elements into a single definition.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2:
for i in range(3):
d2 += elm.ElementDrawing(d1)
d2.push()
d2 += elm.Line().length(d2.unit/6)
d2 += elm.DotDotDot()
d2 += elm.ElementDrawing(d1)
d2.pop()
d2.here = (d2.here[0], d2.here[1]-d2.unit)
d2 += elm.Line().right().length(d2.unit/6)
d2 += elm.DotDotDot()
Power supply
^^^^^^^^^^^^
Notice the diodes could be added individually, but here the built-in `Rectifier` element is used instead.
Also note the use of newline characters inside resistor and capacitor labels.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(inches_per_unit=.5, unit=3)
d += (D := elm.Rectifier())
d += elm.Line().left(d.unit*1.5).at(D.N).dot(open=True).idot()
d += elm.Line().left(d.unit*1.5).at(D.S).dot(open=True).idot()
d += (G := elm.Gap().toy(D.N).label(['–', 'AC IN', '+']))
d += (top := elm.Line().right(d.unit*3).at(D.E).idot())
d += (Q2 := elm.BjtNpn(circle=True).up().anchor('collector').label('Q2\n2n3055'))
d += elm.Line().down(d.unit/2).at(Q2.base)
d += (Q2b := elm.Dot())
d += elm.Line().left(d.unit/3)
d += (Q1 := elm.BjtNpn(circle=True).up().anchor('emitter').label('Q1\n 2n3054'))
d += elm.Line().at(Q1.collector).toy(top.center).dot()
d += elm.Line().down(d.unit/2).at(Q1.base).dot()
d += elm.Zener().down().reverse().label('D2\n500mA', loc='bot').dot()
d += (G := elm.Ground())
d += elm.Line().left().dot()
d += elm.Capacitor(polar=True).up().reverse().label('C2\n100$\mu$F\n50V', loc='bot').dot()
d += elm.Line().right().hold()
d += elm.Resistor().toy(top.end).label('R1\n2.2K\n50V', loc='bot').dot()
d.move(dx=-d.unit, dy=0)
d += elm.Capacitor(polar=True).toy(G.start).flip().label('C1\n 1000$\mu$F\n50V').dot().idot()
d += elm.Line().at(G.start).tox(D.W)
d += elm.Line().toy(D.W).dot()
d += elm.Resistor().right().at(Q2b.center).label('R2').label('56$\Omega$ 1W', loc='bot').dot()
d.push()
d += elm.Line().toy(top.start).dot()
d += elm.Line().tox(Q2.emitter)
d.pop()
d += elm.Capacitor(polar=True).toy(G.start).label('C3\n470$\mu$F\n50V', loc='bot').dot()
d += elm.Line().tox(G.start).hold()
d += elm.Line().right().dot()
d += elm.Resistor().toy(top.center).label('R3\n10K\n1W', loc='bot').dot()
d += elm.Line().left().hold()
d += elm.Line().right()
d += elm.Dot(open=True)
d += elm.Gap().toy(G.start).label(['+', '$V_{out}$', '–'])
d += elm.Dot(open=True)
d += elm.Line().left()
5-transistor Operational Transconductance Amplifer (OTA)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the use of current labels to show the bias currents.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# tail transistor
d += (Q1 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Line().down().length(0.5)
ground = d.here
d += elm.Ground()
# input pair
d += elm.Line().left().length(1).at(Q1.drain)
d += (Q2 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Dot().at(Q1.drain)
d += elm.Line().right().length(1)
d += (Q3 := elm.AnalogNFet()).anchor('source').theta(0)
# current mirror
d += (Q4 := elm.AnalogPFet()).anchor('drain').at(Q2.drain).theta(0)
d += (Q5 := elm.AnalogPFet()).anchor('drain').at(Q3.drain).theta(0).reverse()
d += elm.Line().right().at(Q4.gate).to(Q5.gate)
d += elm.Dot().at(0.5*(Q4.gate + Q5.gate))
d += elm.Line().down().toy(Q4.drain)
d += elm.Line().left().tox(Q4.drain)
d += elm.Dot()
# vcc connection
d += elm.Line().right().at(Q4.source).to(Q5.source)
d += elm.Dot().at(0.5*(Q4.source + Q5.source))
d += elm.Vdd()
# bias source
d += elm.Line().left().length(0.25).at(Q1.gate)
d += elm.SourceV().down().toy(ground).reverse().scale(0.5).label("Bias")
d += elm.Ground()
# signal labels
d += elm.Tag().at(Q2.gate).label("In+").left()
d += elm.Tag().at(Q3.gate).label("In−").right()
d += elm.Dot().at(Q3.drain)
d += elm.Line().right().tox(Q3.gate)
d += elm.Tag().right().label("Out").reverse()
# bias currents
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q1).label("20µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q4).label("10µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q5).label("10µA")
Quadruple loop negative feedback amplifier
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# place twoports
d += (N1 := elm.Nullor()).anchor('center')
d += (T1 := elm.TransimpedanceTransactor(reverse_output=True)).reverse().flip().anchor('center').at([0,-3]).label("B")
d += (T2 := elm.CurrentTransactor()).reverse().flip().anchor('center').at([0,-6]).label("D")
d += (T3 := elm.VoltageTransactor()).reverse().anchor('center').at([0,-9]).label("A")
d += (T4 := elm.TransadmittanceTransactor(reverse_output=True)).reverse().anchor('center').at([0,-12]).label("C")
## make connections
# right side
d += elm.Line().at(N1.out_n).to(T1.in_n)
d += elm.Line().at(T1.in_p).to(T2.in_n)
d += elm.Line().at(T3.in_n).to(T4.in_n)
d += elm.Line().right().length(1).at(N1.out_p)
pre_out = d.here
d += (outline := elm.Line()).right().length(1).dot(open=True)
out = d.here
d += elm.Gap().down().label(('+','$V_o$','–')).toy(N1.out_n)
d += elm.Line().idot(open=True).down().toy(T4.in_n)
d += elm.Line().left().to(T4.in_n)
d += elm.Dot()
d += elm.CurrentLabelInline(direction='in', ofst=-0.15).at(outline).label('$I_o$')
d += elm.Line().at(T2.in_p).right().tox(out)
d += elm.Dot()
d += elm.Line().right().at(T4.in_p).tox(pre_out)
d += elm.Line().up().toy(pre_out)
d += elm.Dot()
d += elm.Line().right().at(T3.in_p).tox(pre_out)
d += elm.Dot()
# left side
d += elm.Line().down().at(N1.in_n).to(T1.out_n)
d += elm.Line().up().at(T3.out_p).to(T1.out_p)
d += elm.Line().left().at(N1.in_p).length(1)
pre_in = d.here
d += (inline := elm.Line()).length(1).dot(open=True).left()
in_node = d.here
d += elm.Gap().down().label(('+','$V_i$','–')).toy(N1.in_n)
d += elm.Line().idot(open=True).down().toy(T4.out_n)
d += elm.Line().right().to(T4.out_n)
d += elm.CurrentLabelInline(direction='out', ofst=-0.15).at(inline).label('$I_i$')
d += elm.Line().left().at(T2.out_p).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T3.out_n).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T4.out_p).tox(pre_in)
d += elm.Line().up().toy(pre_in)
d += elm.Dot()
d += elm.Line().left().at(T2.out_n).tox(pre_in)
d += elm.Dot()
| 0.877069 | 0.469095 |
.. _gallery:
Circuit Gallery
===============
.. toctree::
analog
opamp
logicgate
timing
solidstate
ic
signalproc
flowcharting
styles
-------
Need more circuit examples? Check out the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/index.rst
|
index.rst
|
.. _gallery:
Circuit Gallery
===============
.. toctree::
analog
opamp
logicgate
timing
solidstate
ic
signalproc
flowcharting
styles
-------
Need more circuit examples? Check out the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.79854 | 0.30691 |
Digital Logic
-------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Logic gate definitions are in the :py:mod:`schemdraw.logic.logic` module. Here it was imported with
.. code-block:: python
from schemdraw import logic
Half Adder
^^^^^^^^^^
Notice the half and full adders set the drawing unit to 0.5 so the lines aren't quite as long and look better with logic gates.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (S := logic.Xor().label('S', 'right'))
d += logic.Line().left(d.unit*2).at(S.in1).idot().label('A', 'left')
d += (B := logic.Line().left().at(S.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().down(d.unit*3).at(S.in1)
d += (C := logic.And().right().anchor('in1').label('C', 'right'))
d += logic.Wire('|-').at(B.end).to(C.in2)
Full Adder
^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (X1 := logic.Xor())
d += (A := logic.Line().left(d.unit*2).at(X1.in1).idot().label('A', 'left'))
d += (B := logic.Line().left().at(X1.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().right().at(X1.out).idot()
d += (X2 := logic.Xor().anchor('in1'))
d += (C := logic.Line().down(d.unit*2).at(X2.in2))
d.push()
d += logic.Dot().at(C.center)
d += logic.Line().tox(A.end).label('C$_{in}$', 'left')
d.pop()
d += (A1 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A1.in2).to(X1.out)
d.move_from(A1.in2, dy=-d.unit*2)
d += (A2 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A2.in1).to(A.start)
d += logic.Wire('-|').at(A2.in2).to(B.end)
d.move_from(A1.out, dy=-(A1.out.y-A2.out.y)/2)
d += (O1 := logic.Or().right().label('C$_{out}$', 'right'))
d += logic.Line().at(A1.out).toy(O1.in1)
d += logic.Line().at(A2.out).toy(O1.in2)
d += logic.Line().at(X2.out).tox(O1.out).label('S', 'right')
J-K Flip Flop
^^^^^^^^^^^^^
Note the use of the LaTeX command **overline{Q}** in the label to draw a bar over the inverting output label.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# Two front gates (SR latch)
d += (G1 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('Q', 'right')
d.move_from(G1.in1, dy=-2.5)
d += (G2 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('$\overline{Q}$', 'right')
d += logic.Wire('N', k=.5).at(G2.in1).to(G1.out).dot()
d += logic.Wire('N', k=.5).at(G1.in2).to(G2.out).dot()
# Two back gates
d += logic.Line().left(d.unit/6).at(G1.in1)
d += (J := logic.Nand(inputs=3).anchor('out').right())
d += logic.Wire('n', k=.5).at(J.in1).to(G2.out, dx=1).dot()
d += logic.Line().left(d.unit/4).at(J.in2).label('J', 'left')
d += logic.Line().left(d.unit/6).at(G2.in2)
d += (K := logic.Nand(inputs=3).right().anchor('out'))
d += logic.Wire('n', k=-.5).at(K.in3).to(G1.out, dx=.5).dot()
d += logic.Line().left(d.unit/4).at(K.in2).label('K', 'left')
d += (C := logic.Line().at(J.in3).toy(K.in1))
d += logic.Dot().at(C.center)
d += logic.Line().left(d.unit/4).label('CLK', 'left')
S-R Latch (Gates)
^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (g1 := logic.Nor())
d.move_from(g1.in1, dy=-2.5)
d += (g2 := logic.Nor().anchor('in1'))
d += (g1out := logic.Line().right(.25).at(g1.out))
d += logic.Wire('N', k=.5).at(g2.in1).to(g1out.end).dot()
d += (g2out := logic.Line().right(.25).at(g2.out))
d += logic.Wire('N', k=.5).at(g1.in2).to(g2out.end).dot()
d += logic.Line().at(g1.in1).left(.5).label('R', 'left')
d += logic.Line().at(g2.in2).left(.5).label('S', 'left')
d += logic.Line().at(g1.out).right(.75).label('Q', 'right')
d += logic.Line().at(g2.out).right(.75).label('$\overline{Q}$', 'right')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/logicgate.rst
|
logicgate.rst
|
Digital Logic
-------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Logic gate definitions are in the :py:mod:`schemdraw.logic.logic` module. Here it was imported with
.. code-block:: python
from schemdraw import logic
Half Adder
^^^^^^^^^^
Notice the half and full adders set the drawing unit to 0.5 so the lines aren't quite as long and look better with logic gates.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (S := logic.Xor().label('S', 'right'))
d += logic.Line().left(d.unit*2).at(S.in1).idot().label('A', 'left')
d += (B := logic.Line().left().at(S.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().down(d.unit*3).at(S.in1)
d += (C := logic.And().right().anchor('in1').label('C', 'right'))
d += logic.Wire('|-').at(B.end).to(C.in2)
Full Adder
^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (X1 := logic.Xor())
d += (A := logic.Line().left(d.unit*2).at(X1.in1).idot().label('A', 'left'))
d += (B := logic.Line().left().at(X1.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().right().at(X1.out).idot()
d += (X2 := logic.Xor().anchor('in1'))
d += (C := logic.Line().down(d.unit*2).at(X2.in2))
d.push()
d += logic.Dot().at(C.center)
d += logic.Line().tox(A.end).label('C$_{in}$', 'left')
d.pop()
d += (A1 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A1.in2).to(X1.out)
d.move_from(A1.in2, dy=-d.unit*2)
d += (A2 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A2.in1).to(A.start)
d += logic.Wire('-|').at(A2.in2).to(B.end)
d.move_from(A1.out, dy=-(A1.out.y-A2.out.y)/2)
d += (O1 := logic.Or().right().label('C$_{out}$', 'right'))
d += logic.Line().at(A1.out).toy(O1.in1)
d += logic.Line().at(A2.out).toy(O1.in2)
d += logic.Line().at(X2.out).tox(O1.out).label('S', 'right')
J-K Flip Flop
^^^^^^^^^^^^^
Note the use of the LaTeX command **overline{Q}** in the label to draw a bar over the inverting output label.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# Two front gates (SR latch)
d += (G1 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('Q', 'right')
d.move_from(G1.in1, dy=-2.5)
d += (G2 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('$\overline{Q}$', 'right')
d += logic.Wire('N', k=.5).at(G2.in1).to(G1.out).dot()
d += logic.Wire('N', k=.5).at(G1.in2).to(G2.out).dot()
# Two back gates
d += logic.Line().left(d.unit/6).at(G1.in1)
d += (J := logic.Nand(inputs=3).anchor('out').right())
d += logic.Wire('n', k=.5).at(J.in1).to(G2.out, dx=1).dot()
d += logic.Line().left(d.unit/4).at(J.in2).label('J', 'left')
d += logic.Line().left(d.unit/6).at(G2.in2)
d += (K := logic.Nand(inputs=3).right().anchor('out'))
d += logic.Wire('n', k=-.5).at(K.in3).to(G1.out, dx=.5).dot()
d += logic.Line().left(d.unit/4).at(K.in2).label('K', 'left')
d += (C := logic.Line().at(J.in3).toy(K.in1))
d += logic.Dot().at(C.center)
d += logic.Line().left(d.unit/4).label('CLK', 'left')
S-R Latch (Gates)
^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (g1 := logic.Nor())
d.move_from(g1.in1, dy=-2.5)
d += (g2 := logic.Nor().anchor('in1'))
d += (g1out := logic.Line().right(.25).at(g1.out))
d += logic.Wire('N', k=.5).at(g2.in1).to(g1out.end).dot()
d += (g2out := logic.Line().right(.25).at(g2.out))
d += logic.Wire('N', k=.5).at(g1.in2).to(g2out.end).dot()
d += logic.Line().at(g1.in1).left(.5).label('R', 'left')
d += logic.Line().at(g2.in2).left(.5).label('S', 'left')
d += logic.Line().at(g1.out).right(.75).label('Q', 'right')
d += logic.Line().at(g2.out).right(.75).label('$\overline{Q}$', 'right')
| 0.806548 | 0.70044 |
Integrated Circuits
-------------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
555 LED Blinker Circuit
^^^^^^^^^^^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.intcircuits.Ic` class to define a custom integrated circuit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
IC555def = elm.Ic(pins=[elm.IcPin(name='TRG', side='left', pin='2'),
elm.IcPin(name='THR', side='left', pin='6'),
elm.IcPin(name='DIS', side='left', pin='7'),
elm.IcPin(name='CTL', side='right', pin='5'),
elm.IcPin(name='OUT', side='right', pin='3'),
elm.IcPin(name='RST', side='top', pin='4'),
elm.IcPin(name='Vcc', side='top', pin='8'),
elm.IcPin(name='GND', side='bot', pin='1'),],
edgepadW=.5,
edgepadH=1,
pinspacing=1.5,
leadlen=1,
label='555')
d += (T := IC555def)
d += (BOT := elm.Ground().at(T.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(T.DIS, T.THR).label('Rb').idot()
d += elm.Resistor().up().at(T.DIS).label('Ra').label('+Vcc', 'right')
d += elm.Line().endpoints(T.THR, T.TRG)
d += elm.Capacitor().at(T.TRG).toy(BOT.start).label('C')
d += elm.Line().tox(BOT.start)
d += elm.Capacitor().at(T.CTL).toy(BOT.start).label('.01$\mu$F', 'bottom').dot()
d += elm.Dot().at(T.DIS)
d += elm.Dot().at(T.THR)
d += elm.Dot().at(T.TRG)
d += elm.Line().endpoints(T.RST,T.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Resistor().right().at(T.OUT).label('330')
d += elm.LED().flip().toy(BOT.start)
d += elm.Line().tox(BOT.start)
Seven-Segment Display Counter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (IC555 := elm.Ic555())
d += (gnd := elm.Ground(xy=IC555.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(IC555.DIS, IC555.THR).label('100 kΩ')
d += elm.Resistor().up().at(IC555.DIS).label('1 kΩ').label('+Vcc', 'right')
d += elm.Line().endpoints(IC555.THR, IC555.TRG)
d += elm.Capacitor(polar=True).at(IC555.TRG).toy(gnd.start).label('10 μF')
d += elm.Line().tox(gnd.start)
d += elm.Capacitor().at(IC555.CTL).toy(gnd.start).label('.01 μF', 'bottom')
d += elm.Line().tox(gnd.start)
d += elm.Dot().at(IC555.DIS)
d += elm.Dot().at(IC555.THR)
d += elm.Dot().at(IC555.TRG)
d += elm.Line().endpoints(IC555.RST,IC555.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
IC4026 = elm.Ic(pins=[elm.IcPin('CLK', pin='1', side='left'),
elm.IcPin('INH', pin='2', side='left'), # Inhibit
elm.IcPin('RST', pin='15', side='left'),
elm.IcPin('DEI', pin='3', side='left'), # Display Enable In
elm.IcPin('Vss', pin='8', side='bot'),
elm.IcPin('Vdd', pin='16', side='top'),
elm.IcPin('UCS', pin='14', side='bot'), # Ungated C Segment
elm.IcPin('DEO', pin='4', side='bot'), # Display Enable Out
elm.IcPin('Co', pin='4', side='bot'), # Carry out
elm.IcPin('g', pin='7', side='right'),
elm.IcPin('f', pin='6', side='right'),
elm.IcPin('e', pin='11', side='right'),
elm.IcPin('d', pin='9', side='right'),
elm.IcPin('c', pin='13', side='right'),
elm.IcPin('b', pin='12', side='right'),
elm.IcPin('a', pin='10', side='right'),
],
w=4, leadlen=.8).label('4026').right()
d.move_from(IC555.OUT, dx=5, dy=-1)
d += IC4026.anchor('center')
d += elm.Wire('c').at(IC555.OUT).to(IC4026.CLK)
d += elm.Line().endpoints(IC4026.INH, IC4026.RST).dot()
d += elm.Line().left(d.unit/4)
d += elm.Ground()
d += elm.Wire('|-').at(IC4026.DEI).to(IC4026.Vdd).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Line().at(IC4026.Vss).tox(IC4026.UCS).dot()
d += elm.Ground()
d += elm.Line().tox(IC4026.DEO).dot()
d += elm.Line().tox(IC4026.Co)
d += elm.Resistor().right().at(IC4026.a)
d += (disp := elm.SevenSegment(cathode=True).anchor('a'))
d += elm.Resistor().at(IC4026.b)
d += elm.Resistor().at(IC4026.c)
d += elm.Resistor().at(IC4026.d)
d += elm.Resistor().at(IC4026.e)
d += elm.Resistor().at(IC4026.f)
d += elm.Resistor().at(IC4026.g).label('7 x 330', loc='bottom')
d += elm.Ground(lead=False).at(disp.cathode)
Arduino Board
^^^^^^^^^^^^^
The Arduino board uses :py:class:`schemdraw.elements.connectors.OrthoLines` to easily add all connections between data bus and headers.
.. jupyter-execute::
:code-below:
class Atmega328(elm.Ic):
def __init__(self, *args, **kwargs):
pins=[elm.IcPin(name='PD0', pin='2', side='r', slot='1/22'),
elm.IcPin(name='PD1', pin='3', side='r', slot='2/22'),
elm.IcPin(name='PD2', pin='4', side='r', slot='3/22'),
elm.IcPin(name='PD3', pin='5', side='r', slot='4/22'),
elm.IcPin(name='PD4', pin='6', side='r', slot='5/22'),
elm.IcPin(name='PD5', pin='11', side='r', slot='6/22'),
elm.IcPin(name='PD6', pin='12', side='r', slot='7/22'),
elm.IcPin(name='PD7', pin='13', side='r', slot='8/22'),
elm.IcPin(name='PC0', pin='23', side='r', slot='10/22'),
elm.IcPin(name='PC1', pin='24', side='r', slot='11/22'),
elm.IcPin(name='PC2', pin='25', side='r', slot='12/22'),
elm.IcPin(name='PC3', pin='26', side='r', slot='13/22'),
elm.IcPin(name='PC4', pin='27', side='r', slot='14/22'),
elm.IcPin(name='PC5', pin='28', side='r', slot='15/22'),
elm.IcPin(name='PB0', pin='14', side='r', slot='17/22'),
elm.IcPin(name='PB1', pin='15', side='r', slot='18/22'),
elm.IcPin(name='PB2', pin='16', side='r', slot='19/22'),
elm.IcPin(name='PB3', pin='17', side='r', slot='20/22'),
elm.IcPin(name='PB4', pin='18', side='r', slot='21/22'),
elm.IcPin(name='PB5', pin='19', side='r', slot='22/22'),
elm.IcPin(name='RESET', side='l', slot='22/22', invert=True, pin='1'),
elm.IcPin(name='XTAL2', side='l', slot='19/22', pin='10'),
elm.IcPin(name='XTAL1', side='l', slot='17/22', pin='9'),
elm.IcPin(name='AREF', side='l', slot='15/22', pin='21'),
elm.IcPin(name='AVCC', side='l', slot='14/22', pin='20'),
elm.IcPin(name='AGND', side='l', slot='13/22', pin='22'),
elm.IcPin(name='VCC', side='l', slot='11/22', pin='7'),
elm.IcPin(name='GND', side='l', slot='10/22', pin='8')]
super().__init__(pins=pins, w=5, plblofst=.05, botlabel='ATMEGA328', **kwargs)
with schemdraw.Drawing() as d:
d.config(fontsize=11, inches_per_unit=.4)
d += (Q1 := Atmega328())
d += (JP4 := elm.Header(rows=10, shownumber=True, pinsright=['D8', 'D9', 'D10', 'D11', 'D12', 'D13', '', '', '', ''], pinalignright='center')
.flip().at(Q1.PB5, dx=4, dy=1).anchor('pin6').label('JP4', fontsize=10))
d += (JP3 := elm.Header(rows=6, shownumber=True, pinsright=['A0', 'A1', 'A2', 'A3', 'A4', 'A5'], pinalignright='center')
.flip().at(Q1.PC5, dx=4).anchor('pin6').label('JP3', fontsize=10))
d += (JP2 := elm.Header(rows=8, shownumber=True, pinsright=['D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7'],
pinalignright='center')).at(Q1.PD7, dx=3).flip().anchor('pin8').label('JP2', fontsize=10)
d += elm.OrthoLines(n=6).at(Q1.PB5).to(JP4.pin6)
d += elm.OrthoLines(n=6).at(Q1.PC5).to(JP3.pin6)
d += elm.OrthoLines(n=8).at(Q1.PD7).to(JP2.pin8)
d += elm.Line().left(.9).at(JP4.pin7).label('GND', 'left')
d += elm.Line().left(.9).at(JP4.pin8).label('AREF', 'left')
d += elm.Line().left(.9).at(JP4.pin9).label('AD4/SDA', 'left')
d += elm.Line().left(.9).at(JP4.pin10).label('AD5/SCL', 'left')
d += (JP1 := elm.Header(rows=6, shownumber=True, pinsright=['VCC', 'RXD', 'TXD', 'DTR', 'RTS', 'GND'],
pinalignright='center').right().at(Q1.PD0, dx=4, dy=-2).anchor('pin1'))
d += elm.Line().left(d.unit/2).at(JP1.pin1)
d += elm.Vdd().label('+5V')
d += elm.Line().left().at(JP1.pin2)
d += elm.Line().toy(Q1.PD0).dot()
d += elm.Line().left(d.unit+.6).at(JP1.pin3)
d += elm.Line().toy(Q1.PD1).dot()
d += elm.Line().left(d.unit/2).at(JP1.pin6)
d += elm.Ground()
d += elm.Line().left(d.unit*2).at(Q1.XTAL2).dot()
d.push()
d += elm.Capacitor().left(d.unit/2).scale(.75)
d += elm.Line().toy(Q1.XTAL1).dot()
d += elm.Ground()
d += elm.Capacitor().right(d.unit/2).scale(.75).dot()
d.pop()
d += elm.Crystal().toy(Q1.XTAL1).label('16MHz', 'bottom')
d += elm.Line().tox(Q1.XTAL1)
d += elm.Line().left(d.unit/3).at(Q1.AREF).label('AREF', 'left')
d += elm.Line().left(1.5*d.unit).at(Q1.AVCC)
d += elm.Vdd().label('+5V')
d += elm.Line().toy(Q1.VCC).dot().idot()
d += elm.Line().tox(Q1.VCC).hold()
d += elm.Capacitor().down().label('100n')
d += (GND := elm.Ground())
d += elm.Line().left().at(Q1.AGND)
d += elm.Line().toy(Q1.GND).dot()
d += elm.Line().tox(Q1.GND).hold()
d += elm.Wire('|-').to(GND.center).dot()
d += elm.Line().left().at(Q1.RESET).dot()
d.push()
d += elm.RBox().up().label('10K')
d += elm.Vdd().label('+5V')
d.pop()
d += elm.Line().left().dot()
d.push()
d += (RST := elm.Button().up().label('Reset'))
d += elm.Line().left(d.unit/2)
d += elm.Ground()
d.pop()
d += elm.Capacitor().left().at(JP1.pin4).label('100n', 'bottom')
d += elm.Wire('c', k=-16).to(RST.start)
.. _dip741:
741 Opamp, DIP Layout
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q := elm.IcDIP(pins=8)
.label('Offset Null', loc='p1', fontsize=10)
.label('Inverting Input', loc='p2', fontsize=10)
.label('Non-inverting Input', loc='p3', fontsize=10)
.label('V-', loc='p4', fontsize=10)
.label('Offset Null', loc='p5', fontsize=10)
.label('Output', loc='p6', fontsize=10)
.label('V+', loc='p7', fontsize=10)
.label('NC', loc='p8', fontsize=10))
d += elm.Line().at(Q.p2_in).length(d.unit/5)
d += (op := elm.Opamp().anchor('in1').scale(.8))
d += elm.Line().at(Q.p3_in).length(d.unit/5)
d += elm.Wire('c', k=.3).at(op.out).to(Q.p6_in)
d += elm.Wire('-|').at(Q.p4_in).to(op.n1)
d += elm.Wire('-|').at(Q.p7_in).to(op.n2)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/ic.rst
|
ic.rst
|
Integrated Circuits
-------------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
555 LED Blinker Circuit
^^^^^^^^^^^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.intcircuits.Ic` class to define a custom integrated circuit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
IC555def = elm.Ic(pins=[elm.IcPin(name='TRG', side='left', pin='2'),
elm.IcPin(name='THR', side='left', pin='6'),
elm.IcPin(name='DIS', side='left', pin='7'),
elm.IcPin(name='CTL', side='right', pin='5'),
elm.IcPin(name='OUT', side='right', pin='3'),
elm.IcPin(name='RST', side='top', pin='4'),
elm.IcPin(name='Vcc', side='top', pin='8'),
elm.IcPin(name='GND', side='bot', pin='1'),],
edgepadW=.5,
edgepadH=1,
pinspacing=1.5,
leadlen=1,
label='555')
d += (T := IC555def)
d += (BOT := elm.Ground().at(T.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(T.DIS, T.THR).label('Rb').idot()
d += elm.Resistor().up().at(T.DIS).label('Ra').label('+Vcc', 'right')
d += elm.Line().endpoints(T.THR, T.TRG)
d += elm.Capacitor().at(T.TRG).toy(BOT.start).label('C')
d += elm.Line().tox(BOT.start)
d += elm.Capacitor().at(T.CTL).toy(BOT.start).label('.01$\mu$F', 'bottom').dot()
d += elm.Dot().at(T.DIS)
d += elm.Dot().at(T.THR)
d += elm.Dot().at(T.TRG)
d += elm.Line().endpoints(T.RST,T.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Resistor().right().at(T.OUT).label('330')
d += elm.LED().flip().toy(BOT.start)
d += elm.Line().tox(BOT.start)
Seven-Segment Display Counter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (IC555 := elm.Ic555())
d += (gnd := elm.Ground(xy=IC555.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(IC555.DIS, IC555.THR).label('100 kΩ')
d += elm.Resistor().up().at(IC555.DIS).label('1 kΩ').label('+Vcc', 'right')
d += elm.Line().endpoints(IC555.THR, IC555.TRG)
d += elm.Capacitor(polar=True).at(IC555.TRG).toy(gnd.start).label('10 μF')
d += elm.Line().tox(gnd.start)
d += elm.Capacitor().at(IC555.CTL).toy(gnd.start).label('.01 μF', 'bottom')
d += elm.Line().tox(gnd.start)
d += elm.Dot().at(IC555.DIS)
d += elm.Dot().at(IC555.THR)
d += elm.Dot().at(IC555.TRG)
d += elm.Line().endpoints(IC555.RST,IC555.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
IC4026 = elm.Ic(pins=[elm.IcPin('CLK', pin='1', side='left'),
elm.IcPin('INH', pin='2', side='left'), # Inhibit
elm.IcPin('RST', pin='15', side='left'),
elm.IcPin('DEI', pin='3', side='left'), # Display Enable In
elm.IcPin('Vss', pin='8', side='bot'),
elm.IcPin('Vdd', pin='16', side='top'),
elm.IcPin('UCS', pin='14', side='bot'), # Ungated C Segment
elm.IcPin('DEO', pin='4', side='bot'), # Display Enable Out
elm.IcPin('Co', pin='4', side='bot'), # Carry out
elm.IcPin('g', pin='7', side='right'),
elm.IcPin('f', pin='6', side='right'),
elm.IcPin('e', pin='11', side='right'),
elm.IcPin('d', pin='9', side='right'),
elm.IcPin('c', pin='13', side='right'),
elm.IcPin('b', pin='12', side='right'),
elm.IcPin('a', pin='10', side='right'),
],
w=4, leadlen=.8).label('4026').right()
d.move_from(IC555.OUT, dx=5, dy=-1)
d += IC4026.anchor('center')
d += elm.Wire('c').at(IC555.OUT).to(IC4026.CLK)
d += elm.Line().endpoints(IC4026.INH, IC4026.RST).dot()
d += elm.Line().left(d.unit/4)
d += elm.Ground()
d += elm.Wire('|-').at(IC4026.DEI).to(IC4026.Vdd).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Line().at(IC4026.Vss).tox(IC4026.UCS).dot()
d += elm.Ground()
d += elm.Line().tox(IC4026.DEO).dot()
d += elm.Line().tox(IC4026.Co)
d += elm.Resistor().right().at(IC4026.a)
d += (disp := elm.SevenSegment(cathode=True).anchor('a'))
d += elm.Resistor().at(IC4026.b)
d += elm.Resistor().at(IC4026.c)
d += elm.Resistor().at(IC4026.d)
d += elm.Resistor().at(IC4026.e)
d += elm.Resistor().at(IC4026.f)
d += elm.Resistor().at(IC4026.g).label('7 x 330', loc='bottom')
d += elm.Ground(lead=False).at(disp.cathode)
Arduino Board
^^^^^^^^^^^^^
The Arduino board uses :py:class:`schemdraw.elements.connectors.OrthoLines` to easily add all connections between data bus and headers.
.. jupyter-execute::
:code-below:
class Atmega328(elm.Ic):
def __init__(self, *args, **kwargs):
pins=[elm.IcPin(name='PD0', pin='2', side='r', slot='1/22'),
elm.IcPin(name='PD1', pin='3', side='r', slot='2/22'),
elm.IcPin(name='PD2', pin='4', side='r', slot='3/22'),
elm.IcPin(name='PD3', pin='5', side='r', slot='4/22'),
elm.IcPin(name='PD4', pin='6', side='r', slot='5/22'),
elm.IcPin(name='PD5', pin='11', side='r', slot='6/22'),
elm.IcPin(name='PD6', pin='12', side='r', slot='7/22'),
elm.IcPin(name='PD7', pin='13', side='r', slot='8/22'),
elm.IcPin(name='PC0', pin='23', side='r', slot='10/22'),
elm.IcPin(name='PC1', pin='24', side='r', slot='11/22'),
elm.IcPin(name='PC2', pin='25', side='r', slot='12/22'),
elm.IcPin(name='PC3', pin='26', side='r', slot='13/22'),
elm.IcPin(name='PC4', pin='27', side='r', slot='14/22'),
elm.IcPin(name='PC5', pin='28', side='r', slot='15/22'),
elm.IcPin(name='PB0', pin='14', side='r', slot='17/22'),
elm.IcPin(name='PB1', pin='15', side='r', slot='18/22'),
elm.IcPin(name='PB2', pin='16', side='r', slot='19/22'),
elm.IcPin(name='PB3', pin='17', side='r', slot='20/22'),
elm.IcPin(name='PB4', pin='18', side='r', slot='21/22'),
elm.IcPin(name='PB5', pin='19', side='r', slot='22/22'),
elm.IcPin(name='RESET', side='l', slot='22/22', invert=True, pin='1'),
elm.IcPin(name='XTAL2', side='l', slot='19/22', pin='10'),
elm.IcPin(name='XTAL1', side='l', slot='17/22', pin='9'),
elm.IcPin(name='AREF', side='l', slot='15/22', pin='21'),
elm.IcPin(name='AVCC', side='l', slot='14/22', pin='20'),
elm.IcPin(name='AGND', side='l', slot='13/22', pin='22'),
elm.IcPin(name='VCC', side='l', slot='11/22', pin='7'),
elm.IcPin(name='GND', side='l', slot='10/22', pin='8')]
super().__init__(pins=pins, w=5, plblofst=.05, botlabel='ATMEGA328', **kwargs)
with schemdraw.Drawing() as d:
d.config(fontsize=11, inches_per_unit=.4)
d += (Q1 := Atmega328())
d += (JP4 := elm.Header(rows=10, shownumber=True, pinsright=['D8', 'D9', 'D10', 'D11', 'D12', 'D13', '', '', '', ''], pinalignright='center')
.flip().at(Q1.PB5, dx=4, dy=1).anchor('pin6').label('JP4', fontsize=10))
d += (JP3 := elm.Header(rows=6, shownumber=True, pinsright=['A0', 'A1', 'A2', 'A3', 'A4', 'A5'], pinalignright='center')
.flip().at(Q1.PC5, dx=4).anchor('pin6').label('JP3', fontsize=10))
d += (JP2 := elm.Header(rows=8, shownumber=True, pinsright=['D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7'],
pinalignright='center')).at(Q1.PD7, dx=3).flip().anchor('pin8').label('JP2', fontsize=10)
d += elm.OrthoLines(n=6).at(Q1.PB5).to(JP4.pin6)
d += elm.OrthoLines(n=6).at(Q1.PC5).to(JP3.pin6)
d += elm.OrthoLines(n=8).at(Q1.PD7).to(JP2.pin8)
d += elm.Line().left(.9).at(JP4.pin7).label('GND', 'left')
d += elm.Line().left(.9).at(JP4.pin8).label('AREF', 'left')
d += elm.Line().left(.9).at(JP4.pin9).label('AD4/SDA', 'left')
d += elm.Line().left(.9).at(JP4.pin10).label('AD5/SCL', 'left')
d += (JP1 := elm.Header(rows=6, shownumber=True, pinsright=['VCC', 'RXD', 'TXD', 'DTR', 'RTS', 'GND'],
pinalignright='center').right().at(Q1.PD0, dx=4, dy=-2).anchor('pin1'))
d += elm.Line().left(d.unit/2).at(JP1.pin1)
d += elm.Vdd().label('+5V')
d += elm.Line().left().at(JP1.pin2)
d += elm.Line().toy(Q1.PD0).dot()
d += elm.Line().left(d.unit+.6).at(JP1.pin3)
d += elm.Line().toy(Q1.PD1).dot()
d += elm.Line().left(d.unit/2).at(JP1.pin6)
d += elm.Ground()
d += elm.Line().left(d.unit*2).at(Q1.XTAL2).dot()
d.push()
d += elm.Capacitor().left(d.unit/2).scale(.75)
d += elm.Line().toy(Q1.XTAL1).dot()
d += elm.Ground()
d += elm.Capacitor().right(d.unit/2).scale(.75).dot()
d.pop()
d += elm.Crystal().toy(Q1.XTAL1).label('16MHz', 'bottom')
d += elm.Line().tox(Q1.XTAL1)
d += elm.Line().left(d.unit/3).at(Q1.AREF).label('AREF', 'left')
d += elm.Line().left(1.5*d.unit).at(Q1.AVCC)
d += elm.Vdd().label('+5V')
d += elm.Line().toy(Q1.VCC).dot().idot()
d += elm.Line().tox(Q1.VCC).hold()
d += elm.Capacitor().down().label('100n')
d += (GND := elm.Ground())
d += elm.Line().left().at(Q1.AGND)
d += elm.Line().toy(Q1.GND).dot()
d += elm.Line().tox(Q1.GND).hold()
d += elm.Wire('|-').to(GND.center).dot()
d += elm.Line().left().at(Q1.RESET).dot()
d.push()
d += elm.RBox().up().label('10K')
d += elm.Vdd().label('+5V')
d.pop()
d += elm.Line().left().dot()
d.push()
d += (RST := elm.Button().up().label('Reset'))
d += elm.Line().left(d.unit/2)
d += elm.Ground()
d.pop()
d += elm.Capacitor().left().at(JP1.pin4).label('100n', 'bottom')
d += elm.Wire('c', k=-16).to(RST.start)
.. _dip741:
741 Opamp, DIP Layout
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q := elm.IcDIP(pins=8)
.label('Offset Null', loc='p1', fontsize=10)
.label('Inverting Input', loc='p2', fontsize=10)
.label('Non-inverting Input', loc='p3', fontsize=10)
.label('V-', loc='p4', fontsize=10)
.label('Offset Null', loc='p5', fontsize=10)
.label('Output', loc='p6', fontsize=10)
.label('V+', loc='p7', fontsize=10)
.label('NC', loc='p8', fontsize=10))
d += elm.Line().at(Q.p2_in).length(d.unit/5)
d += (op := elm.Opamp().anchor('in1').scale(.8))
d += elm.Line().at(Q.p3_in).length(d.unit/5)
d += elm.Wire('c', k=.3).at(op.out).to(Q.p6_in)
d += elm.Wire('-|').at(Q.p4_in).to(op.n1)
d += elm.Wire('-|').at(Q.p7_in).to(op.n2)
| 0.772959 | 0.365315 |
Opamp Circuits
--------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Inverting Opamp
^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down(d.unit/4).at(op.in2)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up(d.unit/2).at(op.in1)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right(d.unit/4).at(op.out).label('$v_{o}$', loc='right')
Non-inverting Opamp
^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += (out := elm.Line(at=op.out).length(.75))
d += elm.Line().up().at(op.in1).length(1.5).dot()
d.push()
d += elm.Resistor().left().label('$R_1$')
d += elm.Ground()
d.pop()
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Resistor().left().at(op.in2).idot().label('$R_2$')
d += elm.SourceV().down().reverse().label('$v_{in}$')
d += elm.Line().right().dot()
d += elm.Resistor().up().label('$R_3$').hold()
d += elm.Line().tox(out.end)
d += elm.Gap().toy(op.out).label(['–','$v_o$','+'])
Multi-stage amplifier
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Ground(lead=False)
d += elm.SourceV().label('500mV')
d += elm.Resistor().right().label('20k$\Omega$').dot()
d += (O1 := elm.Opamp(leads=True).anchor('in1'))
d += elm.Ground().at(O1.in2)
d += elm.Line().up(2).at(O1.in1)
d += elm.Resistor().tox(O1.out).label('100k$\Omega$')
d += elm.Line().toy(O1.out).dot()
d += elm.Line().right(5).at(O1.out)
d += (O2 := elm.Opamp(leads=True).anchor('in2'))
d += elm.Resistor().left().at(O2.in1).idot().label('30k$\Omega$')
d += elm.Ground()
d += elm.Line().up(1.5).at(O2.in1)
d += elm.Resistor().tox(O2.out).label('90k$\Omega$')
d += elm.Line().toy(O2.out).dot()
d += elm.Line().right(1).at(O2.out).label('$v_{out}$', loc='rgt')
Opamp pin labeling
^^^^^^^^^^^^^^^^^^
This example shows how to label pin numbers on a 741 opamp, and connect to the offset anchors.
Pin labels are somewhat manually placed; without the `ofst` and `align` keywords they
will be drawn directly over the anchor position.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
op = (elm.Opamp().label('741', loc='center', ofst=0)
.label('1', 'n1', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('5', 'n1a', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('4', 'vs', fontsize=9, ofst=(-.1, -.2), halign='right', valign='top')
.label('7', 'vd', fontsize=9, ofst=(-.1, .2), halign='right', valign='bottom')
.label('2', 'in1', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('3', 'in2', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('6', 'out', fontsize=9, ofst=(-.1, .1), halign='left', valign='bottom'))
d += op
d += elm.Line().left(.5).at(op.in1)
d += elm.Line().down(d.unit/2)
d += elm.Ground(lead=False)
d += elm.Line().left(.5).at(op.in2)
d += elm.Line().right(.5).at(op.out).label('$V_o$', 'right')
d += elm.Line().up(1).at(op.vd).label('$+V_s$', 'right')
d += (trim := elm.Potentiometer().down().at(op.n1).flip().scale(0.7))
d += elm.Line().tox(op.n1a)
d += elm.Line().up().to(op.n1a)
d += elm.Line().at(trim.tap).tox(op.vs).dot()
d.push()
d += elm.Line().down(d.unit/3)
d += elm.Ground()
d.pop()
d += elm.Line().toy(op.vs)
Triaxial Cable Driver
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=10)
d += elm.Line().length(d.unit/5).label('V', 'left')
d += (smu := elm.Opamp(sign=False).anchor('in2')
.label('SMU', 'center', ofst=[-.4, 0], halign='center', valign='center'))
d += elm.Line().at(smu.out).length(.3)
d.push()
d += elm.Line().length(d.unit/4)
d += (triax := elm.Triax(length=5, shieldofststart=.75))
d.pop()
d += elm.Resistor().up().scale(0.6).idot()
d += elm.Line().left().dot()
d += elm.Wire('|-').to(smu.in1).hold()
d += elm.Wire('|-').delta(d.unit/5, d.unit/5)
d += (buf := elm.Opamp(sign=False).anchor('in2').scale(0.6)
.label('BUF', 'center', ofst=(-.4, 0), halign='center', valign='center'))
d += elm.Line().left(d.unit/5).at(buf.in1)
d += elm.Wire('n').to(buf.out, dx=.5).dot()
d += elm.Wire('-|').at(buf.out).to(triax.guardstart_top)
d += elm.GroundChassis().at(triax.shieldcenter)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/opamp.rst
|
opamp.rst
|
Opamp Circuits
--------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Inverting Opamp
^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down(d.unit/4).at(op.in2)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up(d.unit/2).at(op.in1)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right(d.unit/4).at(op.out).label('$v_{o}$', loc='right')
Non-inverting Opamp
^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += (out := elm.Line(at=op.out).length(.75))
d += elm.Line().up().at(op.in1).length(1.5).dot()
d.push()
d += elm.Resistor().left().label('$R_1$')
d += elm.Ground()
d.pop()
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Resistor().left().at(op.in2).idot().label('$R_2$')
d += elm.SourceV().down().reverse().label('$v_{in}$')
d += elm.Line().right().dot()
d += elm.Resistor().up().label('$R_3$').hold()
d += elm.Line().tox(out.end)
d += elm.Gap().toy(op.out).label(['–','$v_o$','+'])
Multi-stage amplifier
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Ground(lead=False)
d += elm.SourceV().label('500mV')
d += elm.Resistor().right().label('20k$\Omega$').dot()
d += (O1 := elm.Opamp(leads=True).anchor('in1'))
d += elm.Ground().at(O1.in2)
d += elm.Line().up(2).at(O1.in1)
d += elm.Resistor().tox(O1.out).label('100k$\Omega$')
d += elm.Line().toy(O1.out).dot()
d += elm.Line().right(5).at(O1.out)
d += (O2 := elm.Opamp(leads=True).anchor('in2'))
d += elm.Resistor().left().at(O2.in1).idot().label('30k$\Omega$')
d += elm.Ground()
d += elm.Line().up(1.5).at(O2.in1)
d += elm.Resistor().tox(O2.out).label('90k$\Omega$')
d += elm.Line().toy(O2.out).dot()
d += elm.Line().right(1).at(O2.out).label('$v_{out}$', loc='rgt')
Opamp pin labeling
^^^^^^^^^^^^^^^^^^
This example shows how to label pin numbers on a 741 opamp, and connect to the offset anchors.
Pin labels are somewhat manually placed; without the `ofst` and `align` keywords they
will be drawn directly over the anchor position.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
op = (elm.Opamp().label('741', loc='center', ofst=0)
.label('1', 'n1', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('5', 'n1a', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('4', 'vs', fontsize=9, ofst=(-.1, -.2), halign='right', valign='top')
.label('7', 'vd', fontsize=9, ofst=(-.1, .2), halign='right', valign='bottom')
.label('2', 'in1', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('3', 'in2', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('6', 'out', fontsize=9, ofst=(-.1, .1), halign='left', valign='bottom'))
d += op
d += elm.Line().left(.5).at(op.in1)
d += elm.Line().down(d.unit/2)
d += elm.Ground(lead=False)
d += elm.Line().left(.5).at(op.in2)
d += elm.Line().right(.5).at(op.out).label('$V_o$', 'right')
d += elm.Line().up(1).at(op.vd).label('$+V_s$', 'right')
d += (trim := elm.Potentiometer().down().at(op.n1).flip().scale(0.7))
d += elm.Line().tox(op.n1a)
d += elm.Line().up().to(op.n1a)
d += elm.Line().at(trim.tap).tox(op.vs).dot()
d.push()
d += elm.Line().down(d.unit/3)
d += elm.Ground()
d.pop()
d += elm.Line().toy(op.vs)
Triaxial Cable Driver
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=10)
d += elm.Line().length(d.unit/5).label('V', 'left')
d += (smu := elm.Opamp(sign=False).anchor('in2')
.label('SMU', 'center', ofst=[-.4, 0], halign='center', valign='center'))
d += elm.Line().at(smu.out).length(.3)
d.push()
d += elm.Line().length(d.unit/4)
d += (triax := elm.Triax(length=5, shieldofststart=.75))
d.pop()
d += elm.Resistor().up().scale(0.6).idot()
d += elm.Line().left().dot()
d += elm.Wire('|-').to(smu.in1).hold()
d += elm.Wire('|-').delta(d.unit/5, d.unit/5)
d += (buf := elm.Opamp(sign=False).anchor('in2').scale(0.6)
.label('BUF', 'center', ofst=(-.4, 0), halign='center', valign='center'))
d += elm.Line().left(d.unit/5).at(buf.in1)
d += elm.Wire('n').to(buf.out, dx=.5).dot()
d += elm.Wire('-|').at(buf.out).to(triax.guardstart_top)
d += elm.GroundChassis().at(triax.shieldcenter)
| 0.749362 | 0.514034 |
.. _gallerytiming:
Timing Diagrams
---------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Timing diagrams, based on `WaveDrom <https://wavedrom.com/>`_, are drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` class.
.. code-block:: python
from schemdraw import logic
SRAM read/write cycle
^^^^^^^^^^^^^^^^^^^^^
The SRAM examples make use of Schemdraw's extended 'edge' notation for labeling
timings just above and below the wave.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0.....1.'},
{'name': 'Out Enable', 'wave': '1.0.....1.'},
{'name': 'Data Out', 'wave': 'z...x6...z', 'data': ['Valid data']},
],
'edge': ['[0^:1.2]+[0^:8] $t_{WC}$',
'[0v:1]+[0v:5] $t_{AQ}$',
'[1:2]+[1:5] $t_{EQ}$',
'[2:2]+[2:5] $t_{GQ}$',
'[0^:5]-[3v:5]{lightgray,:}',
]
}, ygap=.5, grid=False)
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0......1'},
{'name': 'Write Enable', 'wave': '1..0...1..'},
{'name': 'Data In', 'wave': 'x...5....x', 'data': ['Valid data']},
],
'edge': ['[0^:1]+[0^:8] $t_{WC}$',
'[2:1]+[2:3] $t_{SA}$',
'[3^:4]+[3^:7] $t_{WD}$',
'[3^:7]+[3^:9] $t_{HD}$',
'[0^:1]-[2:1]{lightgray,:}'],
}, ygap=.4, grid=False)
J-K Flip Flop
^^^^^^^^^^^^^
Timing diagram for a J-K flip flop taken from `here <https://commons.wikimedia.org/wiki/File:JK_timing_diagram.svg>`_.
Notice the use of the `async` dictionary parameter on the J and K signals, and the color parameters for the output signals.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'J', 'wave': '0101', 'async': [0, .8, 1.3, 3.7, 7]},
{'name': 'K', 'wave': '010101', 'async': [0, 1.2, 2.3, 2.8, 3.2, 3.7, 7]},
{'name': 'Q', 'wave': '010.101', 'color': 'red', 'lw': 1.5},
{'name': '$\overline{Q}$', 'wave': '101.010', 'color': 'blue', 'lw': 1.5}],
'config': {'hscale': 1.5}}, risetime=.05)
Tutorial Examples
^^^^^^^^^^^^^^^^^
These examples were copied from `WaveDrom Tutorial <https://wavedrom.com/tutorial.html>`_.
They use the `from_json` class method so the examples can be pasted directly as a string. Otherwise, the setup must be converted to a proper Python dictionary.
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [{ name: "Alfa", wave: "01.zx=ud.23.456789" }] }''')
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "p.....|..." },
{ name: "Data", wave: "x.345x|=.x", data: ["head", "body", "tail", "data"] },
{ name: "Request", wave: "0.1..0|1.0" },
{},
{ name: "Acknowledge", wave: "1.....|01." }
]}''')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/timing.rst
|
timing.rst
|
.. _gallerytiming:
Timing Diagrams
---------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Timing diagrams, based on `WaveDrom <https://wavedrom.com/>`_, are drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` class.
.. code-block:: python
from schemdraw import logic
SRAM read/write cycle
^^^^^^^^^^^^^^^^^^^^^
The SRAM examples make use of Schemdraw's extended 'edge' notation for labeling
timings just above and below the wave.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0.....1.'},
{'name': 'Out Enable', 'wave': '1.0.....1.'},
{'name': 'Data Out', 'wave': 'z...x6...z', 'data': ['Valid data']},
],
'edge': ['[0^:1.2]+[0^:8] $t_{WC}$',
'[0v:1]+[0v:5] $t_{AQ}$',
'[1:2]+[1:5] $t_{EQ}$',
'[2:2]+[2:5] $t_{GQ}$',
'[0^:5]-[3v:5]{lightgray,:}',
]
}, ygap=.5, grid=False)
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0......1'},
{'name': 'Write Enable', 'wave': '1..0...1..'},
{'name': 'Data In', 'wave': 'x...5....x', 'data': ['Valid data']},
],
'edge': ['[0^:1]+[0^:8] $t_{WC}$',
'[2:1]+[2:3] $t_{SA}$',
'[3^:4]+[3^:7] $t_{WD}$',
'[3^:7]+[3^:9] $t_{HD}$',
'[0^:1]-[2:1]{lightgray,:}'],
}, ygap=.4, grid=False)
J-K Flip Flop
^^^^^^^^^^^^^
Timing diagram for a J-K flip flop taken from `here <https://commons.wikimedia.org/wiki/File:JK_timing_diagram.svg>`_.
Notice the use of the `async` dictionary parameter on the J and K signals, and the color parameters for the output signals.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'J', 'wave': '0101', 'async': [0, .8, 1.3, 3.7, 7]},
{'name': 'K', 'wave': '010101', 'async': [0, 1.2, 2.3, 2.8, 3.2, 3.7, 7]},
{'name': 'Q', 'wave': '010.101', 'color': 'red', 'lw': 1.5},
{'name': '$\overline{Q}$', 'wave': '101.010', 'color': 'blue', 'lw': 1.5}],
'config': {'hscale': 1.5}}, risetime=.05)
Tutorial Examples
^^^^^^^^^^^^^^^^^
These examples were copied from `WaveDrom Tutorial <https://wavedrom.com/tutorial.html>`_.
They use the `from_json` class method so the examples can be pasted directly as a string. Otherwise, the setup must be converted to a proper Python dictionary.
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [{ name: "Alfa", wave: "01.zx=ud.23.456789" }] }''')
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "p.....|..." },
{ name: "Data", wave: "x.345x|=.x", data: ["head", "body", "tail", "data"] },
{ name: "Request", wave: "0.1..0|1.0" },
{},
{ name: "Acknowledge", wave: "1.....|01." }
]}''')
| 0.794425 | 0.589096 |
Signal Processing
-----------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import dsp
Signal processing elements are in the :py:mod:`schemdraw.dsp.dsp` module.
.. code-block:: python
from schemdraw import dsp
Various Networks
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Line().length(d.unit/3).label('in')
d += (inpt := dsp.Dot())
d += dsp.Arrow().length(d.unit/3)
d += (delay := dsp.Box(w=2, h=2).anchor('W').label('Delay\nT'))
d += dsp.Arrow().right(d.unit/2).at(delay.E)
d += (sm := dsp.SumSigma())
d += dsp.Arrow().at(sm.E).length(d.unit/2)
d += (intg := dsp.Box(w=2, h=2).anchor('W').label('$\int$'))
d += dsp.Arrow().right(d.unit/2).at(intg.E).label('out', loc='right')
d += dsp.Line().down(d.unit/2).at(inpt.center)
d += dsp.Line().tox(sm.S)
d += dsp.Arrow().toy(sm.S).label('+', loc='bot')
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=14)
d += dsp.Line().length(d.unit/2).label('F(s)').dot()
d.push()
d += dsp.Line().up(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h1 := dsp.Box(w=2, h=2).anchor('W').label('$H_1(s)$'))
d.pop()
d += dsp.Line().down(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h2 := dsp.Box(w=2, h=2).anchor('W').label('$H_2(s)$'))
d += (sm := dsp.SumSigma().right().at((h1.E[0] + d.unit/2, 0)).anchor('center'))
d += dsp.Line().at(h1.E).tox(sm.N)
d += dsp.Arrow().toy(sm.N)
d += dsp.Line().at(h2.E).tox(sm.S)
d += dsp.Arrow().toy(sm.S)
d += dsp.Arrow().right(d.unit/3).at(sm.E).label('Y(s)', 'right')
Superheterodyne Receiver
^^^^^^^^^^^^^^^^^^^^^^^^
`Source <https://www.electronicdesign.com/adc/high-speed-rf-sampling-adc-boosts-bandwidth-dynamic-range>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += dsp.Antenna()
d += dsp.Line().right(d.unit/4)
d += dsp.Filter(response='bp').fill('thistle').anchor('W').label('RF filter\n#1', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/4)
d += dsp.Amp().fill('lightblue').label('LNA')
d += dsp.Line().length(d.unit/4)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('RF filter\n#2', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/3)
d += (mix := dsp.Mixer().fill('navajowhite').label('Mixer'))
d += dsp.Line().at(mix.S).down(d.unit/3)
d += dsp.Oscillator().right().anchor('N').fill('navajowhite').label('Local\nOscillator', 'right', ofst=.2)
d += dsp.Line().at(mix.E).right(d.unit/3)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('IF filter', 'bottom', ofst=.2)
d += dsp.Line().right(d.unit/4)
d += dsp.Amp().fill('lightblue').label('IF\namplifier')
d += dsp.Line().length(d.unit/4)
d += dsp.Demod().anchor('W').fill('navajowhite').label('Demodulator', 'bottom', ofst=.2)
d += dsp.Arrow().right(d.unit/3)
Direct Conversion Receiver
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Antenna()
d += dsp.Arrow().right(d.unit/2).label('$f_{RF}$', 'bot')
d += dsp.Amp().label('LNA')
d += dsp.Line().right(d.unit/5).dot()
d.push()
d += dsp.Line().length(d.unit/4)
d += (mix1 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().length(d.unit/2)
d += (lpf1 := dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2))
d += dsp.Line().length(d.unit/6)
d += (adc1 := dsp.Adc().label('ADC'))
d += dsp.Arrow().length(d.unit/3)
d += (dsp1 := dsp.Ic(pins=[dsp.IcPin(side='L'), dsp.IcPin(side='L'), dsp.IcPin(side='R')],
size=(2.75, 5), leadlen=0).anchor('inL2').label('DSP'))
d += dsp.Arrow().at(dsp1.inR1).length(d.unit/3)
d.pop()
d += dsp.Line().toy(dsp1.inL1)
d += dsp.Arrow().tox(mix1.W)
d += (mix2 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().tox(lpf1.W)
d += dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2)
d += dsp.Line().tox(adc1.W)
d += dsp.Adc().label('ADC')
d += dsp.Arrow().to(dsp1.inL1)
d += dsp.Arrow().down(d.unit/6).reverse().at(mix1.S)
d += dsp.Line().left(d.unit*1.25)
d += dsp.Line().down(d.unit*.75)
d += (flo := dsp.Dot().label('$f_{LO}$', 'left'))
d.push()
d += dsp.Line().down(d.unit/5)
d += dsp.Oscillator().right().anchor('N').label('LO', 'left', ofst=.15)
d.pop()
d += dsp.Arrow().down(d.unit/4).reverse().at(mix2.S)
d += (b1 := dsp.Square().right().label('90°').anchor('N'))
d += dsp.Arrow().left(d.unit/4).reverse().at(b1.W)
d += dsp.Line().toy(flo.center)
d += dsp.Line().tox(flo.center)
Digital Filter
^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=1, fontsize=14)
d += dsp.Line().length(d.unit*2).label('x[n]', 'left').dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_0$', 'bottom')
d += dsp.Arrow()
d += (s0 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down()
d += (z1 := dsp.Square(label='$z^{-1}$'))
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_1$', 'bottom')
d += dsp.Arrow()
d += (s1 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().right()
d += dsp.Amp().label('$b_2$', 'bottom')
d += dsp.Arrow()
d += (s2 := dsp.Sum().anchor('W'))
d += dsp.Arrow().at(s2.N).toy(s1.S)
d += dsp.Arrow().at(s1.N).toy(s0.S)
d += dsp.Line().right(d.unit*2.75).at(s0.E).dot()
d += dsp.Arrow().right().label('y[n]', 'right').hold()
d += dsp.Arrow().down()
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().left()
d += (a1 := dsp.Amp().label('$-a_1$', 'bottom'))
d += dsp.Arrow().at(a1.out).tox(s1.E)
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().left()
d += (a2 := dsp.Amp().label('$-a_2$', 'bottom'))
d += dsp.Arrow().at(a2.out).tox(s2.E)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/signalproc.rst
|
signalproc.rst
|
Signal Processing
-----------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import dsp
Signal processing elements are in the :py:mod:`schemdraw.dsp.dsp` module.
.. code-block:: python
from schemdraw import dsp
Various Networks
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Line().length(d.unit/3).label('in')
d += (inpt := dsp.Dot())
d += dsp.Arrow().length(d.unit/3)
d += (delay := dsp.Box(w=2, h=2).anchor('W').label('Delay\nT'))
d += dsp.Arrow().right(d.unit/2).at(delay.E)
d += (sm := dsp.SumSigma())
d += dsp.Arrow().at(sm.E).length(d.unit/2)
d += (intg := dsp.Box(w=2, h=2).anchor('W').label('$\int$'))
d += dsp.Arrow().right(d.unit/2).at(intg.E).label('out', loc='right')
d += dsp.Line().down(d.unit/2).at(inpt.center)
d += dsp.Line().tox(sm.S)
d += dsp.Arrow().toy(sm.S).label('+', loc='bot')
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=14)
d += dsp.Line().length(d.unit/2).label('F(s)').dot()
d.push()
d += dsp.Line().up(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h1 := dsp.Box(w=2, h=2).anchor('W').label('$H_1(s)$'))
d.pop()
d += dsp.Line().down(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h2 := dsp.Box(w=2, h=2).anchor('W').label('$H_2(s)$'))
d += (sm := dsp.SumSigma().right().at((h1.E[0] + d.unit/2, 0)).anchor('center'))
d += dsp.Line().at(h1.E).tox(sm.N)
d += dsp.Arrow().toy(sm.N)
d += dsp.Line().at(h2.E).tox(sm.S)
d += dsp.Arrow().toy(sm.S)
d += dsp.Arrow().right(d.unit/3).at(sm.E).label('Y(s)', 'right')
Superheterodyne Receiver
^^^^^^^^^^^^^^^^^^^^^^^^
`Source <https://www.electronicdesign.com/adc/high-speed-rf-sampling-adc-boosts-bandwidth-dynamic-range>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += dsp.Antenna()
d += dsp.Line().right(d.unit/4)
d += dsp.Filter(response='bp').fill('thistle').anchor('W').label('RF filter\n#1', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/4)
d += dsp.Amp().fill('lightblue').label('LNA')
d += dsp.Line().length(d.unit/4)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('RF filter\n#2', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/3)
d += (mix := dsp.Mixer().fill('navajowhite').label('Mixer'))
d += dsp.Line().at(mix.S).down(d.unit/3)
d += dsp.Oscillator().right().anchor('N').fill('navajowhite').label('Local\nOscillator', 'right', ofst=.2)
d += dsp.Line().at(mix.E).right(d.unit/3)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('IF filter', 'bottom', ofst=.2)
d += dsp.Line().right(d.unit/4)
d += dsp.Amp().fill('lightblue').label('IF\namplifier')
d += dsp.Line().length(d.unit/4)
d += dsp.Demod().anchor('W').fill('navajowhite').label('Demodulator', 'bottom', ofst=.2)
d += dsp.Arrow().right(d.unit/3)
Direct Conversion Receiver
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Antenna()
d += dsp.Arrow().right(d.unit/2).label('$f_{RF}$', 'bot')
d += dsp.Amp().label('LNA')
d += dsp.Line().right(d.unit/5).dot()
d.push()
d += dsp.Line().length(d.unit/4)
d += (mix1 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().length(d.unit/2)
d += (lpf1 := dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2))
d += dsp.Line().length(d.unit/6)
d += (adc1 := dsp.Adc().label('ADC'))
d += dsp.Arrow().length(d.unit/3)
d += (dsp1 := dsp.Ic(pins=[dsp.IcPin(side='L'), dsp.IcPin(side='L'), dsp.IcPin(side='R')],
size=(2.75, 5), leadlen=0).anchor('inL2').label('DSP'))
d += dsp.Arrow().at(dsp1.inR1).length(d.unit/3)
d.pop()
d += dsp.Line().toy(dsp1.inL1)
d += dsp.Arrow().tox(mix1.W)
d += (mix2 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().tox(lpf1.W)
d += dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2)
d += dsp.Line().tox(adc1.W)
d += dsp.Adc().label('ADC')
d += dsp.Arrow().to(dsp1.inL1)
d += dsp.Arrow().down(d.unit/6).reverse().at(mix1.S)
d += dsp.Line().left(d.unit*1.25)
d += dsp.Line().down(d.unit*.75)
d += (flo := dsp.Dot().label('$f_{LO}$', 'left'))
d.push()
d += dsp.Line().down(d.unit/5)
d += dsp.Oscillator().right().anchor('N').label('LO', 'left', ofst=.15)
d.pop()
d += dsp.Arrow().down(d.unit/4).reverse().at(mix2.S)
d += (b1 := dsp.Square().right().label('90°').anchor('N'))
d += dsp.Arrow().left(d.unit/4).reverse().at(b1.W)
d += dsp.Line().toy(flo.center)
d += dsp.Line().tox(flo.center)
Digital Filter
^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=1, fontsize=14)
d += dsp.Line().length(d.unit*2).label('x[n]', 'left').dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_0$', 'bottom')
d += dsp.Arrow()
d += (s0 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down()
d += (z1 := dsp.Square(label='$z^{-1}$'))
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_1$', 'bottom')
d += dsp.Arrow()
d += (s1 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().right()
d += dsp.Amp().label('$b_2$', 'bottom')
d += dsp.Arrow()
d += (s2 := dsp.Sum().anchor('W'))
d += dsp.Arrow().at(s2.N).toy(s1.S)
d += dsp.Arrow().at(s1.N).toy(s0.S)
d += dsp.Line().right(d.unit*2.75).at(s0.E).dot()
d += dsp.Arrow().right().label('y[n]', 'right').hold()
d += dsp.Arrow().down()
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().left()
d += (a1 := dsp.Amp().label('$-a_1$', 'bottom'))
d += dsp.Arrow().at(a1.out).tox(s1.E)
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().left()
d += (a2 := dsp.Amp().label('$-a_2$', 'bottom'))
d += dsp.Arrow().at(a2.out).tox(s2.E)
| 0.705684 | 0.579341 |
Styles
------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Circuit elements can be styled using Matplotlib colors, line-styles, and line widths.
Resistor circle
^^^^^^^^^^^^^^^
Uses named colors in a loop.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
for i, color in enumerate(['red', 'orange', 'yellow', 'yellowgreen', 'green', 'blue', 'indigo', 'violet']):
d += elm.Resistor().theta(45*i+20).color(color).label('R{}'.format(i))
Hand-drawn
^^^^^^^^^^
And for a change of pace, activate Matplotlib's XKCD mode for "hand-drawn" look!
.. jupyter-execute::
:code-below:
import matplotlib.pyplot as plt
plt.xkcd()
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down().at(op.in2).length(d.unit/4)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up().at(op.in1).length(d.unit/2)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right().at(op.out).length(d.unit/4).label('$v_{o}$', loc='right')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/styles.rst
|
styles.rst
|
Styles
------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Circuit elements can be styled using Matplotlib colors, line-styles, and line widths.
Resistor circle
^^^^^^^^^^^^^^^
Uses named colors in a loop.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
for i, color in enumerate(['red', 'orange', 'yellow', 'yellowgreen', 'green', 'blue', 'indigo', 'violet']):
d += elm.Resistor().theta(45*i+20).color(color).label('R{}'.format(i))
Hand-drawn
^^^^^^^^^^
And for a change of pace, activate Matplotlib's XKCD mode for "hand-drawn" look!
.. jupyter-execute::
:code-below:
import matplotlib.pyplot as plt
plt.xkcd()
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down().at(op.in2).length(d.unit/4)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up().at(op.in1).length(d.unit/2)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right().at(op.out).length(d.unit/4).label('$v_{o}$', loc='right')
| 0.70477 | 0.456955 |
Solid State
-----------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
S-R Latch (Transistors)
^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q1 := elm.BjtNpn(circle=True).reverse().label('Q1', 'left'))
d += (Q2 := elm.BjtNpn(circle=True).at((d.unit*2, 0)).label('Q2'))
d += elm.Line().up(d.unit/2).at(Q1.collector)
d += (R1 := elm.Resistor().up().label('R1').hold())
d += elm.Dot().label('V1', 'left')
d += elm.Resistor().right(d.unit*.75).label('R3', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Set', 'right').hold()
d += elm.Line().to(Q2.base)
d += elm.Line().up(d.unit/2).at(Q2.collector)
d += elm.Dot().label('V2', 'right')
d += (R2 := elm.Resistor().up().label('R2', 'bottom').hold())
d += elm.Resistor().left(d.unit*.75).label('R4', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Reset', 'right').hold()
d += elm.Line().to(Q1.base)
d += elm.Line().down(d.unit/4).at(Q1.emitter)
d += (BOT := elm.Line().tox(Q2.emitter))
d += elm.Line().to(Q2.emitter)
d += elm.Dot().at(BOT.center)
d += elm.Ground().at(BOT.center)
d += (TOP := elm.Line().endpoints(R1.end, R2.end))
d += elm.Dot().at(TOP.center)
d += elm.Vdd().at(TOP.center).label('+Vcc')
741 Opamp Internal Schematic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12, unit=2.5)
d += (Q1 := elm.BjtNpn().label('Q1').label('+IN', 'left'))
d += (Q3 := elm.BjtPnp().left().at(Q1.emitter).anchor('emitter').flip().label('Q3', 'left'))
d += elm.Line().down().at(Q3.collector).dot()
d.push()
d += elm.Line().right(d.unit/4)
d += (Q7 := elm.BjtNpn().anchor('base').label('Q7'))
d.pop()
d += elm.Line().down(d.unit*1.25)
d += (Q5 := elm.BjtNpn().left().flip().anchor('collector').label('Q5', 'left'))
d += elm.Line().left(d.unit/2).at(Q5.emitter).label('OFST\nNULL', 'left').flip()
d += elm.Resistor().down().at(Q5.emitter).label('R1\n1K')
d += elm.Line().right(d.unit*.75).dot()
d += (R3 := elm.Resistor().up().label('R3\n50K'))
d += elm.Line().toy(Q5.base).dot()
d.push()
d += elm.Line().left().to(Q5.base)
d += elm.Line().at(Q7.emitter).toy(Q5.base).dot()
d.pop()
d += elm.Line().right(d.unit/4)
d += (Q6 := elm.BjtNpn().anchor('base').label('Q6'))
d += elm.Line().at(Q6.emitter).length(d.unit/3).label('\nOFST\nNULL', 'right').hold()
d += elm.Resistor().down().at(Q6.emitter).label('R2\n1K').dot()
d += elm.Line().at(Q6.collector).toy(Q3.collector)
d += (Q4 := elm.BjtPnp().right().anchor('collector').label('Q4'))
d += elm.Line().at(Q4.base).tox(Q3.base)
d += elm.Line().at(Q4.emitter).toy(Q1.emitter)
d += (Q2 := elm.BjtNpn().left().flip().anchor('emitter').label('Q2', 'left').label('$-$IN', 'right'))
d += elm.Line().up(d.unit/3).at(Q2.collector).dot()
d += (Q8 := elm.BjtPnp().left().flip().anchor('base').label('Q8', 'left'))
d += elm.Line().at(Q8.collector).toy(Q2.collector).dot()
d += elm.Line().at(Q2.collector).tox(Q1.collector)
d += elm.Line().up(d.unit/4).at(Q8.emitter)
d += (top := elm.Line().tox(Q7.collector))
d += elm.Line().toy(Q7.collector)
d += elm.Line().right(d.unit*2).at(top.start)
d += elm.Line().down(d.unit/4)
d += (Q9 := elm.BjtPnp().right().anchor('emitter').label('Q9', ofst=-.1))
d += elm.Line().at(Q9.base).tox(Q8.base)
d += elm.Dot().at(Q4.base)
d += elm.Line().down(d.unit/2).at(Q4.base)
d += elm.Line().tox(Q9.collector).dot()
d += elm.Line().at(Q9.collector).toy(Q6.collector)
d += (Q10 := elm.BjtNpn().left().flip().anchor('collector').label('Q10', 'left'))
d += elm.Resistor().at(Q10.emitter).toy(R3.start).label('R4\n5K').dot()
d += (Q11 := elm.BjtNpn().right().at(Q10.base).anchor('base').label('Q11'))
d += elm.Dot().at(Q11.base)
d += elm.Line().up(d.unit/2)
d += elm.Line().tox(Q11.collector).dot()
d += elm.Line().at(Q11.emitter).toy(R3.start).dot()
d += elm.Line().up(d.unit*2).at(Q11.collector)
d += elm.Resistor().toy(Q9.collector).label('R5\n39K')
d += (Q12 := elm.BjtPnp().left().flip().anchor('collector').label('Q12', 'left', ofst=-.1))
d += elm.Line().up(d.unit/4).at(Q12.emitter).dot()
d += elm.Line().tox(Q9.emitter).dot()
d += elm.Line().right(d.unit/4).at(Q12.base).dot()
d += elm.Wire('|-').to(Q12.collector).dot().hold()
d += elm.Line().right(d.unit*1.5)
d += (Q13 := elm.BjtPnp().anchor('base').label('Q13'))
d += elm.Line().up(d.unit/4).dot()
d += elm.Line().tox(Q12.emitter)
d += (K := elm.Line().down(d.unit/5).at(Q13.collector).dot())
d += elm.Line().down()
d += (Q16 := elm.BjtNpn().right().anchor('collector').label('Q16', ofst=-.1))
d += elm.Line().left(d.unit/3).at(Q16.base).dot()
d += (R7 := elm.Resistor().up().toy(K.end).label('R7\n4.5K').dot())
d += elm.Line().tox(Q13.collector).hold()
d += (R8 := elm.Resistor().down().at(R7.start).label('R8\n7.5K').dot())
d += elm.Line().tox(Q16.emitter)
d += (J := elm.Dot())
d += elm.Line().toy(Q16.emitter)
d += (Q15 := elm.BjtNpn().right().at(R8.end).anchor('collector').label('Q15'))
d += elm.Line().left(d.unit/2).at(Q15.base).dot()
d += (C1 := elm.Capacitor().toy(R7.end).label('C1\n30pF'))
d += elm.Line().tox(Q13.collector)
d += elm.Line().at(C1.start).tox(Q6.collector).dot()
d += elm.Line().down(d.unit/2).at(J.center)
d += (Q19 := elm.BjtNpn().right().anchor('collector').label('Q19'))
d += elm.Line().at(Q19.base).tox(Q15.emitter).dot()
d += elm.Line().toy(Q15.emitter).hold()
d += elm.Line().down(d.unit/4).at(Q19.emitter).dot()
d += elm.Line().left()
d += (Q22 := elm.BjtNpn().left().anchor('base').flip().label('Q22', 'left'))
d += elm.Line().at(Q22.collector).toy(Q15.base).dot()
d += elm.Line().at(Q22.emitter).toy(R3.start).dot()
d += elm.Line().tox(R3.start).hold()
d += elm.Line().tox(Q15.emitter).dot()
d.push()
d += elm.Resistor().up().label('R12\n50K')
d += elm.Line().toy(Q19.base)
d.pop()
d += elm.Line().tox(Q19.emitter).dot()
d += (R11 := elm.Resistor().up().label('R11\n50'))
d += elm.Line().toy(Q19.emitter)
d += elm.Line().up(d.unit/4).at(Q13.emitter)
d += elm.Line().right(d.unit*1.5).dot()
d += elm.Line().length(d.unit/4).label('V+', 'right').hold()
d += elm.Line().down(d.unit*.75)
d += (Q14 := elm.BjtNpn().right().anchor('collector').label('Q14'))
d += elm.Line().left(d.unit/2).at(Q14.base)
d.push()
d += elm.Line().down(d.unit/2).idot()
d += (Q17 := elm.BjtNpn().left().anchor('collector').flip().label('Q17', 'left', ofst=-.1))
d += elm.Line().at(Q17.base).tox(Q14.emitter).dot()
d += (J := elm.Line().toy(Q14.emitter))
d.pop()
d += elm.Line().tox(Q13.collector).dot()
d += elm.Resistor().down().at(J.start).label('R9\n25').dot()
d += elm.Wire('-|').to(Q17.emitter).hold()
d += elm.Line().down(d.unit/4).dot()
d += elm.Line().right(d.unit/4).label('OUT', 'right').hold()
d += elm.Resistor().down().label('R10\n50')
d += (Q20 := elm.BjtPnp().right().anchor('emitter').label('Q20'))
d += elm.Wire('c', k=-1).at(Q20.base).to(Q15.collector)
d += elm.Line().at(Q20.collector).toy(R3.start).dot()
d += elm.Line().right(d.unit/4).label('V-', 'right').hold()
d += elm.Line().tox(R11.start)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/solidstate-checkpoint.rst
|
solidstate-checkpoint.rst
|
Solid State
-----------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
S-R Latch (Transistors)
^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q1 := elm.BjtNpn(circle=True).reverse().label('Q1', 'left'))
d += (Q2 := elm.BjtNpn(circle=True).at((d.unit*2, 0)).label('Q2'))
d += elm.Line().up(d.unit/2).at(Q1.collector)
d += (R1 := elm.Resistor().up().label('R1').hold())
d += elm.Dot().label('V1', 'left')
d += elm.Resistor().right(d.unit*.75).label('R3', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Set', 'right').hold()
d += elm.Line().to(Q2.base)
d += elm.Line().up(d.unit/2).at(Q2.collector)
d += elm.Dot().label('V2', 'right')
d += (R2 := elm.Resistor().up().label('R2', 'bottom').hold())
d += elm.Resistor().left(d.unit*.75).label('R4', 'bottom').dot()
d += elm.Line().up(d.unit/8).dot(open=True).label('Reset', 'right').hold()
d += elm.Line().to(Q1.base)
d += elm.Line().down(d.unit/4).at(Q1.emitter)
d += (BOT := elm.Line().tox(Q2.emitter))
d += elm.Line().to(Q2.emitter)
d += elm.Dot().at(BOT.center)
d += elm.Ground().at(BOT.center)
d += (TOP := elm.Line().endpoints(R1.end, R2.end))
d += elm.Dot().at(TOP.center)
d += elm.Vdd().at(TOP.center).label('+Vcc')
741 Opamp Internal Schematic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12, unit=2.5)
d += (Q1 := elm.BjtNpn().label('Q1').label('+IN', 'left'))
d += (Q3 := elm.BjtPnp().left().at(Q1.emitter).anchor('emitter').flip().label('Q3', 'left'))
d += elm.Line().down().at(Q3.collector).dot()
d.push()
d += elm.Line().right(d.unit/4)
d += (Q7 := elm.BjtNpn().anchor('base').label('Q7'))
d.pop()
d += elm.Line().down(d.unit*1.25)
d += (Q5 := elm.BjtNpn().left().flip().anchor('collector').label('Q5', 'left'))
d += elm.Line().left(d.unit/2).at(Q5.emitter).label('OFST\nNULL', 'left').flip()
d += elm.Resistor().down().at(Q5.emitter).label('R1\n1K')
d += elm.Line().right(d.unit*.75).dot()
d += (R3 := elm.Resistor().up().label('R3\n50K'))
d += elm.Line().toy(Q5.base).dot()
d.push()
d += elm.Line().left().to(Q5.base)
d += elm.Line().at(Q7.emitter).toy(Q5.base).dot()
d.pop()
d += elm.Line().right(d.unit/4)
d += (Q6 := elm.BjtNpn().anchor('base').label('Q6'))
d += elm.Line().at(Q6.emitter).length(d.unit/3).label('\nOFST\nNULL', 'right').hold()
d += elm.Resistor().down().at(Q6.emitter).label('R2\n1K').dot()
d += elm.Line().at(Q6.collector).toy(Q3.collector)
d += (Q4 := elm.BjtPnp().right().anchor('collector').label('Q4'))
d += elm.Line().at(Q4.base).tox(Q3.base)
d += elm.Line().at(Q4.emitter).toy(Q1.emitter)
d += (Q2 := elm.BjtNpn().left().flip().anchor('emitter').label('Q2', 'left').label('$-$IN', 'right'))
d += elm.Line().up(d.unit/3).at(Q2.collector).dot()
d += (Q8 := elm.BjtPnp().left().flip().anchor('base').label('Q8', 'left'))
d += elm.Line().at(Q8.collector).toy(Q2.collector).dot()
d += elm.Line().at(Q2.collector).tox(Q1.collector)
d += elm.Line().up(d.unit/4).at(Q8.emitter)
d += (top := elm.Line().tox(Q7.collector))
d += elm.Line().toy(Q7.collector)
d += elm.Line().right(d.unit*2).at(top.start)
d += elm.Line().down(d.unit/4)
d += (Q9 := elm.BjtPnp().right().anchor('emitter').label('Q9', ofst=-.1))
d += elm.Line().at(Q9.base).tox(Q8.base)
d += elm.Dot().at(Q4.base)
d += elm.Line().down(d.unit/2).at(Q4.base)
d += elm.Line().tox(Q9.collector).dot()
d += elm.Line().at(Q9.collector).toy(Q6.collector)
d += (Q10 := elm.BjtNpn().left().flip().anchor('collector').label('Q10', 'left'))
d += elm.Resistor().at(Q10.emitter).toy(R3.start).label('R4\n5K').dot()
d += (Q11 := elm.BjtNpn().right().at(Q10.base).anchor('base').label('Q11'))
d += elm.Dot().at(Q11.base)
d += elm.Line().up(d.unit/2)
d += elm.Line().tox(Q11.collector).dot()
d += elm.Line().at(Q11.emitter).toy(R3.start).dot()
d += elm.Line().up(d.unit*2).at(Q11.collector)
d += elm.Resistor().toy(Q9.collector).label('R5\n39K')
d += (Q12 := elm.BjtPnp().left().flip().anchor('collector').label('Q12', 'left', ofst=-.1))
d += elm.Line().up(d.unit/4).at(Q12.emitter).dot()
d += elm.Line().tox(Q9.emitter).dot()
d += elm.Line().right(d.unit/4).at(Q12.base).dot()
d += elm.Wire('|-').to(Q12.collector).dot().hold()
d += elm.Line().right(d.unit*1.5)
d += (Q13 := elm.BjtPnp().anchor('base').label('Q13'))
d += elm.Line().up(d.unit/4).dot()
d += elm.Line().tox(Q12.emitter)
d += (K := elm.Line().down(d.unit/5).at(Q13.collector).dot())
d += elm.Line().down()
d += (Q16 := elm.BjtNpn().right().anchor('collector').label('Q16', ofst=-.1))
d += elm.Line().left(d.unit/3).at(Q16.base).dot()
d += (R7 := elm.Resistor().up().toy(K.end).label('R7\n4.5K').dot())
d += elm.Line().tox(Q13.collector).hold()
d += (R8 := elm.Resistor().down().at(R7.start).label('R8\n7.5K').dot())
d += elm.Line().tox(Q16.emitter)
d += (J := elm.Dot())
d += elm.Line().toy(Q16.emitter)
d += (Q15 := elm.BjtNpn().right().at(R8.end).anchor('collector').label('Q15'))
d += elm.Line().left(d.unit/2).at(Q15.base).dot()
d += (C1 := elm.Capacitor().toy(R7.end).label('C1\n30pF'))
d += elm.Line().tox(Q13.collector)
d += elm.Line().at(C1.start).tox(Q6.collector).dot()
d += elm.Line().down(d.unit/2).at(J.center)
d += (Q19 := elm.BjtNpn().right().anchor('collector').label('Q19'))
d += elm.Line().at(Q19.base).tox(Q15.emitter).dot()
d += elm.Line().toy(Q15.emitter).hold()
d += elm.Line().down(d.unit/4).at(Q19.emitter).dot()
d += elm.Line().left()
d += (Q22 := elm.BjtNpn().left().anchor('base').flip().label('Q22', 'left'))
d += elm.Line().at(Q22.collector).toy(Q15.base).dot()
d += elm.Line().at(Q22.emitter).toy(R3.start).dot()
d += elm.Line().tox(R3.start).hold()
d += elm.Line().tox(Q15.emitter).dot()
d.push()
d += elm.Resistor().up().label('R12\n50K')
d += elm.Line().toy(Q19.base)
d.pop()
d += elm.Line().tox(Q19.emitter).dot()
d += (R11 := elm.Resistor().up().label('R11\n50'))
d += elm.Line().toy(Q19.emitter)
d += elm.Line().up(d.unit/4).at(Q13.emitter)
d += elm.Line().right(d.unit*1.5).dot()
d += elm.Line().length(d.unit/4).label('V+', 'right').hold()
d += elm.Line().down(d.unit*.75)
d += (Q14 := elm.BjtNpn().right().anchor('collector').label('Q14'))
d += elm.Line().left(d.unit/2).at(Q14.base)
d.push()
d += elm.Line().down(d.unit/2).idot()
d += (Q17 := elm.BjtNpn().left().anchor('collector').flip().label('Q17', 'left', ofst=-.1))
d += elm.Line().at(Q17.base).tox(Q14.emitter).dot()
d += (J := elm.Line().toy(Q14.emitter))
d.pop()
d += elm.Line().tox(Q13.collector).dot()
d += elm.Resistor().down().at(J.start).label('R9\n25').dot()
d += elm.Wire('-|').to(Q17.emitter).hold()
d += elm.Line().down(d.unit/4).dot()
d += elm.Line().right(d.unit/4).label('OUT', 'right').hold()
d += elm.Resistor().down().label('R10\n50')
d += (Q20 := elm.BjtPnp().right().anchor('emitter').label('Q20'))
d += elm.Wire('c', k=-1).at(Q20.base).to(Q15.collector)
d += elm.Line().at(Q20.collector).toy(R3.start).dot()
d += elm.Line().right(d.unit/4).label('V-', 'right').hold()
d += elm.Line().tox(R11.start)
| 0.648466 | 0.528898 |
Digital Logic
-------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Logic gate definitions are in the :py:mod:`schemdraw.logic.logic` module. Here it was imported with
.. code-block:: python
from schemdraw import logic
Half Adder
^^^^^^^^^^
Notice the half and full adders set the drawing unit to 0.5 so the lines aren't quite as long and look better with logic gates.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (S := logic.Xor().label('S', 'right'))
d += logic.Line().left(d.unit*2).at(S.in1).idot().label('A', 'left')
d += (B := logic.Line().left().at(S.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().down(d.unit*3).at(S.in1)
d += (C := logic.And().right().anchor('in1').label('C', 'right'))
d += logic.Wire('|-').at(B.end).to(C.in2)
Full Adder
^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (X1 := logic.Xor())
d += (A := logic.Line().left(d.unit*2).at(X1.in1).idot().label('A', 'left'))
d += (B := logic.Line().left().at(X1.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().right().at(X1.out).idot()
d += (X2 := logic.Xor().anchor('in1'))
d += (C := logic.Line().down(d.unit*2).at(X2.in2))
d.push()
d += logic.Dot().at(C.center)
d += logic.Line().tox(A.end).label('C$_{in}$', 'left')
d.pop()
d += (A1 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A1.in2).to(X1.out)
d.move_from(A1.in2, dy=-d.unit*2)
d += (A2 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A2.in1).to(A.start)
d += logic.Wire('-|').at(A2.in2).to(B.end)
d.move_from(A1.out, dy=-(A1.out.y-A2.out.y)/2)
d += (O1 := logic.Or().right().label('C$_{out}$', 'right'))
d += logic.Line().at(A1.out).toy(O1.in1)
d += logic.Line().at(A2.out).toy(O1.in2)
d += logic.Line().at(X2.out).tox(O1.out).label('S', 'right')
J-K Flip Flop
^^^^^^^^^^^^^
Note the use of the LaTeX command **overline{Q}** in the label to draw a bar over the inverting output label.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# Two front gates (SR latch)
d += (G1 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('Q', 'right')
d.move_from(G1.in1, dy=-2.5)
d += (G2 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('$\overline{Q}$', 'right')
d += logic.Wire('N', k=.5).at(G2.in1).to(G1.out).dot()
d += logic.Wire('N', k=.5).at(G1.in2).to(G2.out).dot()
# Two back gates
d += logic.Line().left(d.unit/6).at(G1.in1)
d += (J := logic.Nand(inputs=3).anchor('out').right())
d += logic.Wire('n', k=.5).at(J.in1).to(G2.out, dx=1).dot()
d += logic.Line().left(d.unit/4).at(J.in2).label('J', 'left')
d += logic.Line().left(d.unit/6).at(G2.in2)
d += (K := logic.Nand(inputs=3).right().anchor('out'))
d += logic.Wire('n', k=-.5).at(K.in3).to(G1.out, dx=.5).dot()
d += logic.Line().left(d.unit/4).at(K.in2).label('K', 'left')
d += (C := logic.Line().at(J.in3).toy(K.in1))
d += logic.Dot().at(C.center)
d += logic.Line().left(d.unit/4).label('CLK', 'left')
S-R Latch (Gates)
^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (g1 := logic.Nor())
d.move_from(g1.in1, dy=-2.5)
d += (g2 := logic.Nor().anchor('in1'))
d += (g1out := logic.Line().right(.25).at(g1.out))
d += logic.Wire('N', k=.5).at(g2.in1).to(g1out.end).dot()
d += (g2out := logic.Line().right(.25).at(g2.out))
d += logic.Wire('N', k=.5).at(g1.in2).to(g2out.end).dot()
d += logic.Line().at(g1.in1).left(.5).label('R', 'left')
d += logic.Line().at(g2.in2).left(.5).label('S', 'left')
d += logic.Line().at(g1.out).right(.75).label('Q', 'right')
d += logic.Line().at(g2.out).right(.75).label('$\overline{Q}$', 'right')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/logicgate-checkpoint.rst
|
logicgate-checkpoint.rst
|
Digital Logic
-------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Logic gate definitions are in the :py:mod:`schemdraw.logic.logic` module. Here it was imported with
.. code-block:: python
from schemdraw import logic
Half Adder
^^^^^^^^^^
Notice the half and full adders set the drawing unit to 0.5 so the lines aren't quite as long and look better with logic gates.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (S := logic.Xor().label('S', 'right'))
d += logic.Line().left(d.unit*2).at(S.in1).idot().label('A', 'left')
d += (B := logic.Line().left().at(S.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().down(d.unit*3).at(S.in1)
d += (C := logic.And().right().anchor('in1').label('C', 'right'))
d += logic.Wire('|-').at(B.end).to(C.in2)
Full Adder
^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=0.5)
d += (X1 := logic.Xor())
d += (A := logic.Line().left(d.unit*2).at(X1.in1).idot().label('A', 'left'))
d += (B := logic.Line().left().at(X1.in2).dot())
d += logic.Line().left().label('B', 'left')
d += logic.Line().right().at(X1.out).idot()
d += (X2 := logic.Xor().anchor('in1'))
d += (C := logic.Line().down(d.unit*2).at(X2.in2))
d.push()
d += logic.Dot().at(C.center)
d += logic.Line().tox(A.end).label('C$_{in}$', 'left')
d.pop()
d += (A1 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A1.in2).to(X1.out)
d.move_from(A1.in2, dy=-d.unit*2)
d += (A2 := logic.And().right().anchor('in1'))
d += logic.Wire('-|').at(A2.in1).to(A.start)
d += logic.Wire('-|').at(A2.in2).to(B.end)
d.move_from(A1.out, dy=-(A1.out.y-A2.out.y)/2)
d += (O1 := logic.Or().right().label('C$_{out}$', 'right'))
d += logic.Line().at(A1.out).toy(O1.in1)
d += logic.Line().at(A2.out).toy(O1.in2)
d += logic.Line().at(X2.out).tox(O1.out).label('S', 'right')
J-K Flip Flop
^^^^^^^^^^^^^
Note the use of the LaTeX command **overline{Q}** in the label to draw a bar over the inverting output label.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# Two front gates (SR latch)
d += (G1 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('Q', 'right')
d.move_from(G1.in1, dy=-2.5)
d += (G2 := logic.Nand(leadout=.75).anchor('in1'))
d += logic.Line().length(d.unit/2).label('$\overline{Q}$', 'right')
d += logic.Wire('N', k=.5).at(G2.in1).to(G1.out).dot()
d += logic.Wire('N', k=.5).at(G1.in2).to(G2.out).dot()
# Two back gates
d += logic.Line().left(d.unit/6).at(G1.in1)
d += (J := logic.Nand(inputs=3).anchor('out').right())
d += logic.Wire('n', k=.5).at(J.in1).to(G2.out, dx=1).dot()
d += logic.Line().left(d.unit/4).at(J.in2).label('J', 'left')
d += logic.Line().left(d.unit/6).at(G2.in2)
d += (K := logic.Nand(inputs=3).right().anchor('out'))
d += logic.Wire('n', k=-.5).at(K.in3).to(G1.out, dx=.5).dot()
d += logic.Line().left(d.unit/4).at(K.in2).label('K', 'left')
d += (C := logic.Line().at(J.in3).toy(K.in1))
d += logic.Dot().at(C.center)
d += logic.Line().left(d.unit/4).label('CLK', 'left')
S-R Latch (Gates)
^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (g1 := logic.Nor())
d.move_from(g1.in1, dy=-2.5)
d += (g2 := logic.Nor().anchor('in1'))
d += (g1out := logic.Line().right(.25).at(g1.out))
d += logic.Wire('N', k=.5).at(g2.in1).to(g1out.end).dot()
d += (g2out := logic.Line().right(.25).at(g2.out))
d += logic.Wire('N', k=.5).at(g1.in2).to(g2out.end).dot()
d += logic.Line().at(g1.in1).left(.5).label('R', 'left')
d += logic.Line().at(g2.in2).left(.5).label('S', 'left')
d += logic.Line().at(g1.out).right(.75).label('Q', 'right')
d += logic.Line().at(g2.out).right(.75).label('$\overline{Q}$', 'right')
| 0.806548 | 0.70044 |
.. _galleryflow:
Flowcharting
------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import flow
Flowchart elements are defined in the :py:mod:`flow` module.
.. code-block:: python
from schemdraw import flow
It's a Trap!
^^^^^^^^^^^^
Recreation of `XKCD 1195 <https://xkcd.com/1195/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += flow.Start().label('START')
d += flow.Arrow().down(d.unit/3)
d += (h := flow.Decision(w=5.5, h=4, S='YES').label('Hey, wait,\nthis flowchart\nis a trap!'))
d += flow.Line().down(d.unit/4)
d += flow.Wire('c', k=3.5, arrow='->').to(h.E)
Flowchart for flowcharts
^^^^^^^^^^^^^^^^^^^^^^^^
Recreation of `XKCD 518 <https://xkcd.com/518/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=11)
d += (b := flow.Start().label('START'))
d += flow.Arrow().down(d.unit/2)
d += (d1 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('DO YOU\nUNDERSTAND\nFLOW CHARTS?'))
d += flow.Arrow().length(d.unit/2)
d += (d2 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('OKAY,\nYOU SEE THE\nLINE LABELED\n"YES"?'))
d += flow.Arrow().length(d.unit/2)
d += (d3 := flow.Decision(w=5.2, h=3.9, E='YES', S='NO').label('BUT YOU\nSEE THE ONES\nLABELED "NO".'))
d += flow.Arrow().right(d.unit/2).at(d3.E)
d += flow.Box(w=2, h=1.25).anchor('W').label('WAIT,\nWHAT?')
d += flow.Arrow().down(d.unit/2).at(d3.S)
d += (listen := flow.Box(w=2, h=1).label('LISTEN.'))
d += flow.Arrow().right(d.unit/2).at(listen.E)
d += (hate := flow.Box(w=2, h=1.25).anchor('W').label('I HATE\nYOU.'))
d += flow.Arrow().right(d.unit*3.5).at(d1.E)
d += (good := flow.Box(w=2, h=1).anchor('W').label('GOOD'))
d += flow.Arrow().right(d.unit*1.5).at(d2.E)
d += (d4 := flow.Decision(w=5.3, h=4.0, E='YES', S='NO').anchor('W').label('...AND YOU CAN\nSEE THE ONES\nLABELED "NO"?'))
d += flow.Wire('-|', arrow='->').at(d4.E).to(good.S)
d += flow.Arrow().down(d.unit/2).at(d4.S)
d += (d5 := flow.Decision(w=5, h=3.6, E='YES', S='NO').label('BUT YOU\nJUST FOLLOWED\nTHEM TWICE!'))
d += flow.Arrow().right().at(d5.E)
d += (question := flow.Box(w=3.5, h=1.75).anchor('W').label("(THAT WASN'T\nA QUESTION.)"))
d += flow.Wire('n', k=-1, arrow='->').at(d5.S).to(question.S)
d += flow.Line().at(good.E).tox(question.S)
d += flow.Arrow().down()
d += (drink := flow.Box(w=2.5, h=1.5).label("LET'S GO\nDRINK."))
d += flow.Arrow().right().at(drink.E).label('6 DRINKS')
d += flow.Box(w=3.7, h=2).anchor('W').label('HEY, I SHOULD\nTRY INSTALLING\nFREEBSD!')
d += flow.Arrow().up(d.unit*.75).at(question.N)
d += (screw := flow.Box(w=2.5, h=1).anchor('S').label('SCREW IT.'))
d += flow.Arrow().at(screw.N).toy(drink.S)
State Machine Acceptor
^^^^^^^^^^^^^^^^^^^^^^
`Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:DFAexample.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Arrow().length(1)
d += (s1 := flow.StateEnd().anchor('W').label('$S_1$'))
d += elm.Arc2(arrow='<-').at(s1.NE).label('0')
d += (s2 := flow.State().anchor('NW').label('$S_2$'))
d += elm.Arc2(arrow='<-').at(s2.SW).to(s1.SE).label('0')
d += elm.ArcLoop(arrow='<-').at(s2.NE).to(s2.E).label('1')
d += elm.ArcLoop(arrow='<-').at(s1.NW).to(s1.N).label('1')
Door Controller
^^^^^^^^^^^^^^^
`Diagram Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:Fsm_Moore_model_door_control.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
delta = 4
d += (c4 := flow.Circle(r=1).label('4\nopening'))
d += (c1 := flow.Circle(r=1).at((delta, delta)).label('1\nopened'))
d += (c2 := flow.Circle(r=1).at((2*delta, 0)).label('2\nclosing'))
d += (c3 := flow.Circle(r=1).at((delta, -delta)).label('3\nclosed'))
d += elm.Arc2(arrow='->', k=.3).at(c4.NNE).to(c1.WSW).label('sensor\nopened')
d += elm.Arc2(arrow='->', k=.3).at(c1.ESE).to(c2.NNW).label('close')
d += elm.Arc2(arrow='->', k=.3).at(c2.SSW).to(c3.ENE).label('sensor\nclosed')
d += elm.Arc2(arrow='->', k=.3).at(c3.WNW).to(c4.SSE).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c4.ENE).to(c2.WNW).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c2.WSW).to(c4.ESE).label('close')
Another State Machine
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as dwg:
dwg += (a := flow.Circle().label('a').fill('lightblue'))
dwg += (b := flow.Circle().at((4, 0)).label('b').fill('lightblue'))
dwg += (c := flow.Circle().at((8, 0)).label('c').fill('lightblue'))
dwg += (f := flow.Circle().at((0, -4)).label('f').fill('lightblue'))
dwg += (e := flow.Circle().at((4, -6)).label('e').fill('lightblue'))
dwg += (d := flow.Circle().at((8, -4)).label('d').fill('lightblue'))
dwg += elm.ArcLoop(arrow='->').at(a.NW).to(a.NNE).label('00/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(b.NNW).to(b.NE).label('01/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(c.NNW).to(c.NE).label('11/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(d.E).to(d.SE).label('10/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(e.SSE).to(e.SW).label('11/1', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(f.S).to(f.SW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ENE).to(b.WNW).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.W).to(a.E).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.ENE).to(c.WNW).label('11/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.W).to(b.E).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ESE).to(d.NW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(d.WNW).to(a.SE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.ENE).to(e.NW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(e.WNW).to(f.ESE).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(e.NE).to(d.WSW).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(d.SSW).to(e.ENE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.NNW).to(a.SSW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.SSE).to(d.NNE).label('10/0', fontsize=10)
Logical Flow Diagram
^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(unit=1) as dwg:
dwg += (a := flow.Circle(r=.5).label('a'))
dwg += (x := flow.Decision(w=1.5, h=1.5).label('$X$').at(a.S).anchor('N'))
dwg += elm.RightLines(arrow='->').at(x.E).label('$\overline{X}$')
dwg += (y1 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg.move_from(y1.N, dx=-5)
dwg += (y2 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg += elm.RightLines(arrow='->').at(x.W).to(y2.N).label('$X$')
dwg += elm.Arrow().at(y2.S).label('$Y$')
dwg += (b := flow.Circle(r=.5).label('b'))
dwg.move_from(b.N, dx=2)
dwg += (c := flow.Circle(r=.5).label('c'))
dwg += elm.RightLines(arrow='->').at(y2.E).to(c.N).label('$\overline{Y}$')
dwg += elm.Arrow().at(y1.S).label('$Y$')
dwg += (d := flow.Circle(r=.5).label('d'))
dwg.move_from(d.N, dx=2)
dwg += (e := flow.Circle(r=.5).label('e'))
dwg += elm.RightLines(arrow='->').at(y1.E).to(e.N).label('$\overline{Y}$')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/flowcharting-checkpoint.rst
|
flowcharting-checkpoint.rst
|
.. _galleryflow:
Flowcharting
------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
from schemdraw import flow
Flowchart elements are defined in the :py:mod:`flow` module.
.. code-block:: python
from schemdraw import flow
It's a Trap!
^^^^^^^^^^^^
Recreation of `XKCD 1195 <https://xkcd.com/1195/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += flow.Start().label('START')
d += flow.Arrow().down(d.unit/3)
d += (h := flow.Decision(w=5.5, h=4, S='YES').label('Hey, wait,\nthis flowchart\nis a trap!'))
d += flow.Line().down(d.unit/4)
d += flow.Wire('c', k=3.5, arrow='->').to(h.E)
Flowchart for flowcharts
^^^^^^^^^^^^^^^^^^^^^^^^
Recreation of `XKCD 518 <https://xkcd.com/518/>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=11)
d += (b := flow.Start().label('START'))
d += flow.Arrow().down(d.unit/2)
d += (d1 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('DO YOU\nUNDERSTAND\nFLOW CHARTS?'))
d += flow.Arrow().length(d.unit/2)
d += (d2 := flow.Decision(w=5, h=3.9, E='YES', S='NO').label('OKAY,\nYOU SEE THE\nLINE LABELED\n"YES"?'))
d += flow.Arrow().length(d.unit/2)
d += (d3 := flow.Decision(w=5.2, h=3.9, E='YES', S='NO').label('BUT YOU\nSEE THE ONES\nLABELED "NO".'))
d += flow.Arrow().right(d.unit/2).at(d3.E)
d += flow.Box(w=2, h=1.25).anchor('W').label('WAIT,\nWHAT?')
d += flow.Arrow().down(d.unit/2).at(d3.S)
d += (listen := flow.Box(w=2, h=1).label('LISTEN.'))
d += flow.Arrow().right(d.unit/2).at(listen.E)
d += (hate := flow.Box(w=2, h=1.25).anchor('W').label('I HATE\nYOU.'))
d += flow.Arrow().right(d.unit*3.5).at(d1.E)
d += (good := flow.Box(w=2, h=1).anchor('W').label('GOOD'))
d += flow.Arrow().right(d.unit*1.5).at(d2.E)
d += (d4 := flow.Decision(w=5.3, h=4.0, E='YES', S='NO').anchor('W').label('...AND YOU CAN\nSEE THE ONES\nLABELED "NO"?'))
d += flow.Wire('-|', arrow='->').at(d4.E).to(good.S)
d += flow.Arrow().down(d.unit/2).at(d4.S)
d += (d5 := flow.Decision(w=5, h=3.6, E='YES', S='NO').label('BUT YOU\nJUST FOLLOWED\nTHEM TWICE!'))
d += flow.Arrow().right().at(d5.E)
d += (question := flow.Box(w=3.5, h=1.75).anchor('W').label("(THAT WASN'T\nA QUESTION.)"))
d += flow.Wire('n', k=-1, arrow='->').at(d5.S).to(question.S)
d += flow.Line().at(good.E).tox(question.S)
d += flow.Arrow().down()
d += (drink := flow.Box(w=2.5, h=1.5).label("LET'S GO\nDRINK."))
d += flow.Arrow().right().at(drink.E).label('6 DRINKS')
d += flow.Box(w=3.7, h=2).anchor('W').label('HEY, I SHOULD\nTRY INSTALLING\nFREEBSD!')
d += flow.Arrow().up(d.unit*.75).at(question.N)
d += (screw := flow.Box(w=2.5, h=1).anchor('S').label('SCREW IT.'))
d += flow.Arrow().at(screw.N).toy(drink.S)
State Machine Acceptor
^^^^^^^^^^^^^^^^^^^^^^
`Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:DFAexample.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Arrow().length(1)
d += (s1 := flow.StateEnd().anchor('W').label('$S_1$'))
d += elm.Arc2(arrow='<-').at(s1.NE).label('0')
d += (s2 := flow.State().anchor('NW').label('$S_2$'))
d += elm.Arc2(arrow='<-').at(s2.SW).to(s1.SE).label('0')
d += elm.ArcLoop(arrow='<-').at(s2.NE).to(s2.E).label('1')
d += elm.ArcLoop(arrow='<-').at(s1.NW).to(s1.N).label('1')
Door Controller
^^^^^^^^^^^^^^^
`Diagram Source <https://en.wikipedia.org/wiki/Finite-state_machine#/media/File:Fsm_Moore_model_door_control.svg>`_
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
delta = 4
d += (c4 := flow.Circle(r=1).label('4\nopening'))
d += (c1 := flow.Circle(r=1).at((delta, delta)).label('1\nopened'))
d += (c2 := flow.Circle(r=1).at((2*delta, 0)).label('2\nclosing'))
d += (c3 := flow.Circle(r=1).at((delta, -delta)).label('3\nclosed'))
d += elm.Arc2(arrow='->', k=.3).at(c4.NNE).to(c1.WSW).label('sensor\nopened')
d += elm.Arc2(arrow='->', k=.3).at(c1.ESE).to(c2.NNW).label('close')
d += elm.Arc2(arrow='->', k=.3).at(c2.SSW).to(c3.ENE).label('sensor\nclosed')
d += elm.Arc2(arrow='->', k=.3).at(c3.WNW).to(c4.SSE).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c4.ENE).to(c2.WNW).label('open')
d += elm.Arc2(arrow='<-', k=.3).at(c2.WSW).to(c4.ESE).label('close')
Another State Machine
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as dwg:
dwg += (a := flow.Circle().label('a').fill('lightblue'))
dwg += (b := flow.Circle().at((4, 0)).label('b').fill('lightblue'))
dwg += (c := flow.Circle().at((8, 0)).label('c').fill('lightblue'))
dwg += (f := flow.Circle().at((0, -4)).label('f').fill('lightblue'))
dwg += (e := flow.Circle().at((4, -6)).label('e').fill('lightblue'))
dwg += (d := flow.Circle().at((8, -4)).label('d').fill('lightblue'))
dwg += elm.ArcLoop(arrow='->').at(a.NW).to(a.NNE).label('00/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(b.NNW).to(b.NE).label('01/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(c.NNW).to(c.NE).label('11/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(d.E).to(d.SE).label('10/0', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(e.SSE).to(e.SW).label('11/1', fontsize=10)
dwg += elm.ArcLoop(arrow='->').at(f.S).to(f.SW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ENE).to(b.WNW).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.W).to(a.E).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(b.ENE).to(c.WNW).label('11/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.W).to(b.E).label('01/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(a.ESE).to(d.NW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(d.WNW).to(a.SE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.ENE).to(e.NW).label('01/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(e.WNW).to(f.ESE).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(e.NE).to(d.WSW).label('11/1', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='->').at(d.SSW).to(e.ENE).label('10/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(f.NNW).to(a.SSW).label('00/0', fontsize=10)
dwg += elm.Arc2(k=.1, arrow='<-').at(c.SSE).to(d.NNE).label('10/0', fontsize=10)
Logical Flow Diagram
^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(unit=1) as dwg:
dwg += (a := flow.Circle(r=.5).label('a'))
dwg += (x := flow.Decision(w=1.5, h=1.5).label('$X$').at(a.S).anchor('N'))
dwg += elm.RightLines(arrow='->').at(x.E).label('$\overline{X}$')
dwg += (y1 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg.move_from(y1.N, dx=-5)
dwg += (y2 := flow.Decision(w=1.5, h=1.5).label('$Y$'))
dwg += elm.RightLines(arrow='->').at(x.W).to(y2.N).label('$X$')
dwg += elm.Arrow().at(y2.S).label('$Y$')
dwg += (b := flow.Circle(r=.5).label('b'))
dwg.move_from(b.N, dx=2)
dwg += (c := flow.Circle(r=.5).label('c'))
dwg += elm.RightLines(arrow='->').at(y2.E).to(c.N).label('$\overline{Y}$')
dwg += elm.Arrow().at(y1.S).label('$Y$')
dwg += (d := flow.Circle(r=.5).label('d'))
dwg.move_from(d.N, dx=2)
dwg += (e := flow.Circle(r=.5).label('e'))
dwg += elm.RightLines(arrow='->').at(y1.E).to(e.N).label('$\overline{Y}$')
| 0.642545 | 0.50238 |
.. _gallery:
Circuit Gallery
===============
.. toctree::
analog
opamp
logicgate
timing
solidstate
ic
signalproc
flowcharting
styles
-------
Need more circuit examples? Check out the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/index-checkpoint.rst
|
index-checkpoint.rst
|
.. _gallery:
Circuit Gallery
===============
.. toctree::
analog
opamp
logicgate
timing
solidstate
ic
signalproc
flowcharting
styles
-------
Need more circuit examples? Check out the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.79854 | 0.30691 |
Integrated Circuits
-------------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
555 LED Blinker Circuit
^^^^^^^^^^^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.intcircuits.Ic` class to define a custom integrated circuit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
IC555def = elm.Ic(pins=[elm.IcPin(name='TRG', side='left', pin='2'),
elm.IcPin(name='THR', side='left', pin='6'),
elm.IcPin(name='DIS', side='left', pin='7'),
elm.IcPin(name='CTL', side='right', pin='5'),
elm.IcPin(name='OUT', side='right', pin='3'),
elm.IcPin(name='RST', side='top', pin='4'),
elm.IcPin(name='Vcc', side='top', pin='8'),
elm.IcPin(name='GND', side='bot', pin='1'),],
edgepadW=.5,
edgepadH=1,
pinspacing=1.5,
leadlen=1,
label='555')
d += (T := IC555def)
d += (BOT := elm.Ground().at(T.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(T.DIS, T.THR).label('Rb').idot()
d += elm.Resistor().up().at(T.DIS).label('Ra').label('+Vcc', 'right')
d += elm.Line().endpoints(T.THR, T.TRG)
d += elm.Capacitor().at(T.TRG).toy(BOT.start).label('C')
d += elm.Line().tox(BOT.start)
d += elm.Capacitor().at(T.CTL).toy(BOT.start).label('.01$\mu$F', 'bottom').dot()
d += elm.Dot().at(T.DIS)
d += elm.Dot().at(T.THR)
d += elm.Dot().at(T.TRG)
d += elm.Line().endpoints(T.RST,T.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Resistor().right().at(T.OUT).label('330')
d += elm.LED().flip().toy(BOT.start)
d += elm.Line().tox(BOT.start)
Seven-Segment Display Counter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (IC555 := elm.Ic555())
d += (gnd := elm.Ground(xy=IC555.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(IC555.DIS, IC555.THR).label('100 kΩ')
d += elm.Resistor().up().at(IC555.DIS).label('1 kΩ').label('+Vcc', 'right')
d += elm.Line().endpoints(IC555.THR, IC555.TRG)
d += elm.Capacitor(polar=True).at(IC555.TRG).toy(gnd.start).label('10 μF')
d += elm.Line().tox(gnd.start)
d += elm.Capacitor().at(IC555.CTL).toy(gnd.start).label('.01 μF', 'bottom')
d += elm.Line().tox(gnd.start)
d += elm.Dot().at(IC555.DIS)
d += elm.Dot().at(IC555.THR)
d += elm.Dot().at(IC555.TRG)
d += elm.Line().endpoints(IC555.RST,IC555.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
IC4026 = elm.Ic(pins=[elm.IcPin('CLK', pin='1', side='left'),
elm.IcPin('INH', pin='2', side='left'), # Inhibit
elm.IcPin('RST', pin='15', side='left'),
elm.IcPin('DEI', pin='3', side='left'), # Display Enable In
elm.IcPin('Vss', pin='8', side='bot'),
elm.IcPin('Vdd', pin='16', side='top'),
elm.IcPin('UCS', pin='14', side='bot'), # Ungated C Segment
elm.IcPin('DEO', pin='4', side='bot'), # Display Enable Out
elm.IcPin('Co', pin='4', side='bot'), # Carry out
elm.IcPin('g', pin='7', side='right'),
elm.IcPin('f', pin='6', side='right'),
elm.IcPin('e', pin='11', side='right'),
elm.IcPin('d', pin='9', side='right'),
elm.IcPin('c', pin='13', side='right'),
elm.IcPin('b', pin='12', side='right'),
elm.IcPin('a', pin='10', side='right'),
],
w=4, leadlen=.8).label('4026').right()
d.move_from(IC555.OUT, dx=5, dy=-1)
d += IC4026.anchor('center')
d += elm.Wire('c').at(IC555.OUT).to(IC4026.CLK)
d += elm.Line().endpoints(IC4026.INH, IC4026.RST).dot()
d += elm.Line().left(d.unit/4)
d += elm.Ground()
d += elm.Wire('|-').at(IC4026.DEI).to(IC4026.Vdd).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Line().at(IC4026.Vss).tox(IC4026.UCS).dot()
d += elm.Ground()
d += elm.Line().tox(IC4026.DEO).dot()
d += elm.Line().tox(IC4026.Co)
d += elm.Resistor().right().at(IC4026.a)
d += (disp := elm.SevenSegment(cathode=True).anchor('a'))
d += elm.Resistor().at(IC4026.b)
d += elm.Resistor().at(IC4026.c)
d += elm.Resistor().at(IC4026.d)
d += elm.Resistor().at(IC4026.e)
d += elm.Resistor().at(IC4026.f)
d += elm.Resistor().at(IC4026.g).label('7 x 330', loc='bottom')
d += elm.Ground(lead=False).at(disp.cathode)
Arduino Board
^^^^^^^^^^^^^
The Arduino board uses :py:class:`schemdraw.elements.connectors.OrthoLines` to easily add all connections between data bus and headers.
.. jupyter-execute::
:code-below:
class Atmega328(elm.Ic):
def __init__(self, *args, **kwargs):
pins=[elm.IcPin(name='PD0', pin='2', side='r', slot='1/22'),
elm.IcPin(name='PD1', pin='3', side='r', slot='2/22'),
elm.IcPin(name='PD2', pin='4', side='r', slot='3/22'),
elm.IcPin(name='PD3', pin='5', side='r', slot='4/22'),
elm.IcPin(name='PD4', pin='6', side='r', slot='5/22'),
elm.IcPin(name='PD5', pin='11', side='r', slot='6/22'),
elm.IcPin(name='PD6', pin='12', side='r', slot='7/22'),
elm.IcPin(name='PD7', pin='13', side='r', slot='8/22'),
elm.IcPin(name='PC0', pin='23', side='r', slot='10/22'),
elm.IcPin(name='PC1', pin='24', side='r', slot='11/22'),
elm.IcPin(name='PC2', pin='25', side='r', slot='12/22'),
elm.IcPin(name='PC3', pin='26', side='r', slot='13/22'),
elm.IcPin(name='PC4', pin='27', side='r', slot='14/22'),
elm.IcPin(name='PC5', pin='28', side='r', slot='15/22'),
elm.IcPin(name='PB0', pin='14', side='r', slot='17/22'),
elm.IcPin(name='PB1', pin='15', side='r', slot='18/22'),
elm.IcPin(name='PB2', pin='16', side='r', slot='19/22'),
elm.IcPin(name='PB3', pin='17', side='r', slot='20/22'),
elm.IcPin(name='PB4', pin='18', side='r', slot='21/22'),
elm.IcPin(name='PB5', pin='19', side='r', slot='22/22'),
elm.IcPin(name='RESET', side='l', slot='22/22', invert=True, pin='1'),
elm.IcPin(name='XTAL2', side='l', slot='19/22', pin='10'),
elm.IcPin(name='XTAL1', side='l', slot='17/22', pin='9'),
elm.IcPin(name='AREF', side='l', slot='15/22', pin='21'),
elm.IcPin(name='AVCC', side='l', slot='14/22', pin='20'),
elm.IcPin(name='AGND', side='l', slot='13/22', pin='22'),
elm.IcPin(name='VCC', side='l', slot='11/22', pin='7'),
elm.IcPin(name='GND', side='l', slot='10/22', pin='8')]
super().__init__(pins=pins, w=5, plblofst=.05, botlabel='ATMEGA328', **kwargs)
with schemdraw.Drawing() as d:
d.config(fontsize=11, inches_per_unit=.4)
d += (Q1 := Atmega328())
d += (JP4 := elm.Header(rows=10, shownumber=True, pinsright=['D8', 'D9', 'D10', 'D11', 'D12', 'D13', '', '', '', ''], pinalignright='center')
.flip().at(Q1.PB5, dx=4, dy=1).anchor('pin6').label('JP4', fontsize=10))
d += (JP3 := elm.Header(rows=6, shownumber=True, pinsright=['A0', 'A1', 'A2', 'A3', 'A4', 'A5'], pinalignright='center')
.flip().at(Q1.PC5, dx=4).anchor('pin6').label('JP3', fontsize=10))
d += (JP2 := elm.Header(rows=8, shownumber=True, pinsright=['D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7'],
pinalignright='center')).at(Q1.PD7, dx=3).flip().anchor('pin8').label('JP2', fontsize=10)
d += elm.OrthoLines(n=6).at(Q1.PB5).to(JP4.pin6)
d += elm.OrthoLines(n=6).at(Q1.PC5).to(JP3.pin6)
d += elm.OrthoLines(n=8).at(Q1.PD7).to(JP2.pin8)
d += elm.Line().left(.9).at(JP4.pin7).label('GND', 'left')
d += elm.Line().left(.9).at(JP4.pin8).label('AREF', 'left')
d += elm.Line().left(.9).at(JP4.pin9).label('AD4/SDA', 'left')
d += elm.Line().left(.9).at(JP4.pin10).label('AD5/SCL', 'left')
d += (JP1 := elm.Header(rows=6, shownumber=True, pinsright=['VCC', 'RXD', 'TXD', 'DTR', 'RTS', 'GND'],
pinalignright='center').right().at(Q1.PD0, dx=4, dy=-2).anchor('pin1'))
d += elm.Line().left(d.unit/2).at(JP1.pin1)
d += elm.Vdd().label('+5V')
d += elm.Line().left().at(JP1.pin2)
d += elm.Line().toy(Q1.PD0).dot()
d += elm.Line().left(d.unit+.6).at(JP1.pin3)
d += elm.Line().toy(Q1.PD1).dot()
d += elm.Line().left(d.unit/2).at(JP1.pin6)
d += elm.Ground()
d += elm.Line().left(d.unit*2).at(Q1.XTAL2).dot()
d.push()
d += elm.Capacitor().left(d.unit/2).scale(.75)
d += elm.Line().toy(Q1.XTAL1).dot()
d += elm.Ground()
d += elm.Capacitor().right(d.unit/2).scale(.75).dot()
d.pop()
d += elm.Crystal().toy(Q1.XTAL1).label('16MHz', 'bottom')
d += elm.Line().tox(Q1.XTAL1)
d += elm.Line().left(d.unit/3).at(Q1.AREF).label('AREF', 'left')
d += elm.Line().left(1.5*d.unit).at(Q1.AVCC)
d += elm.Vdd().label('+5V')
d += elm.Line().toy(Q1.VCC).dot().idot()
d += elm.Line().tox(Q1.VCC).hold()
d += elm.Capacitor().down().label('100n')
d += (GND := elm.Ground())
d += elm.Line().left().at(Q1.AGND)
d += elm.Line().toy(Q1.GND).dot()
d += elm.Line().tox(Q1.GND).hold()
d += elm.Wire('|-').to(GND.center).dot()
d += elm.Line().left().at(Q1.RESET).dot()
d.push()
d += elm.RBox().up().label('10K')
d += elm.Vdd().label('+5V')
d.pop()
d += elm.Line().left().dot()
d.push()
d += (RST := elm.Button().up().label('Reset'))
d += elm.Line().left(d.unit/2)
d += elm.Ground()
d.pop()
d += elm.Capacitor().left().at(JP1.pin4).label('100n', 'bottom')
d += elm.Wire('c', k=-16).to(RST.start)
.. _dip741:
741 Opamp, DIP Layout
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q := elm.IcDIP(pins=8)
.label('Offset Null', loc='p1', fontsize=10)
.label('Inverting Input', loc='p2', fontsize=10)
.label('Non-inverting Input', loc='p3', fontsize=10)
.label('V-', loc='p4', fontsize=10)
.label('Offset Null', loc='p5', fontsize=10)
.label('Output', loc='p6', fontsize=10)
.label('V+', loc='p7', fontsize=10)
.label('NC', loc='p8', fontsize=10))
d += elm.Line().at(Q.p2_in).length(d.unit/5)
d += (op := elm.Opamp().anchor('in1').scale(.8))
d += elm.Line().at(Q.p3_in).length(d.unit/5)
d += elm.Wire('c', k=.3).at(op.out).to(Q.p6_in)
d += elm.Wire('-|').at(Q.p4_in).to(op.n1)
d += elm.Wire('-|').at(Q.p7_in).to(op.n2)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/ic-checkpoint.rst
|
ic-checkpoint.rst
|
Integrated Circuits
-------------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
555 LED Blinker Circuit
^^^^^^^^^^^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.intcircuits.Ic` class to define a custom integrated circuit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
IC555def = elm.Ic(pins=[elm.IcPin(name='TRG', side='left', pin='2'),
elm.IcPin(name='THR', side='left', pin='6'),
elm.IcPin(name='DIS', side='left', pin='7'),
elm.IcPin(name='CTL', side='right', pin='5'),
elm.IcPin(name='OUT', side='right', pin='3'),
elm.IcPin(name='RST', side='top', pin='4'),
elm.IcPin(name='Vcc', side='top', pin='8'),
elm.IcPin(name='GND', side='bot', pin='1'),],
edgepadW=.5,
edgepadH=1,
pinspacing=1.5,
leadlen=1,
label='555')
d += (T := IC555def)
d += (BOT := elm.Ground().at(T.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(T.DIS, T.THR).label('Rb').idot()
d += elm.Resistor().up().at(T.DIS).label('Ra').label('+Vcc', 'right')
d += elm.Line().endpoints(T.THR, T.TRG)
d += elm.Capacitor().at(T.TRG).toy(BOT.start).label('C')
d += elm.Line().tox(BOT.start)
d += elm.Capacitor().at(T.CTL).toy(BOT.start).label('.01$\mu$F', 'bottom').dot()
d += elm.Dot().at(T.DIS)
d += elm.Dot().at(T.THR)
d += elm.Dot().at(T.TRG)
d += elm.Line().endpoints(T.RST,T.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Resistor().right().at(T.OUT).label('330')
d += elm.LED().flip().toy(BOT.start)
d += elm.Line().tox(BOT.start)
Seven-Segment Display Counter
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (IC555 := elm.Ic555())
d += (gnd := elm.Ground(xy=IC555.GND))
d += elm.Dot()
d += elm.Resistor().endpoints(IC555.DIS, IC555.THR).label('100 kΩ')
d += elm.Resistor().up().at(IC555.DIS).label('1 kΩ').label('+Vcc', 'right')
d += elm.Line().endpoints(IC555.THR, IC555.TRG)
d += elm.Capacitor(polar=True).at(IC555.TRG).toy(gnd.start).label('10 μF')
d += elm.Line().tox(gnd.start)
d += elm.Capacitor().at(IC555.CTL).toy(gnd.start).label('.01 μF', 'bottom')
d += elm.Line().tox(gnd.start)
d += elm.Dot().at(IC555.DIS)
d += elm.Dot().at(IC555.THR)
d += elm.Dot().at(IC555.TRG)
d += elm.Line().endpoints(IC555.RST,IC555.Vcc).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
IC4026 = elm.Ic(pins=[elm.IcPin('CLK', pin='1', side='left'),
elm.IcPin('INH', pin='2', side='left'), # Inhibit
elm.IcPin('RST', pin='15', side='left'),
elm.IcPin('DEI', pin='3', side='left'), # Display Enable In
elm.IcPin('Vss', pin='8', side='bot'),
elm.IcPin('Vdd', pin='16', side='top'),
elm.IcPin('UCS', pin='14', side='bot'), # Ungated C Segment
elm.IcPin('DEO', pin='4', side='bot'), # Display Enable Out
elm.IcPin('Co', pin='4', side='bot'), # Carry out
elm.IcPin('g', pin='7', side='right'),
elm.IcPin('f', pin='6', side='right'),
elm.IcPin('e', pin='11', side='right'),
elm.IcPin('d', pin='9', side='right'),
elm.IcPin('c', pin='13', side='right'),
elm.IcPin('b', pin='12', side='right'),
elm.IcPin('a', pin='10', side='right'),
],
w=4, leadlen=.8).label('4026').right()
d.move_from(IC555.OUT, dx=5, dy=-1)
d += IC4026.anchor('center')
d += elm.Wire('c').at(IC555.OUT).to(IC4026.CLK)
d += elm.Line().endpoints(IC4026.INH, IC4026.RST).dot()
d += elm.Line().left(d.unit/4)
d += elm.Ground()
d += elm.Wire('|-').at(IC4026.DEI).to(IC4026.Vdd).dot()
d += elm.Line().up(d.unit/4).label('+Vcc', 'right')
d += elm.Line().at(IC4026.Vss).tox(IC4026.UCS).dot()
d += elm.Ground()
d += elm.Line().tox(IC4026.DEO).dot()
d += elm.Line().tox(IC4026.Co)
d += elm.Resistor().right().at(IC4026.a)
d += (disp := elm.SevenSegment(cathode=True).anchor('a'))
d += elm.Resistor().at(IC4026.b)
d += elm.Resistor().at(IC4026.c)
d += elm.Resistor().at(IC4026.d)
d += elm.Resistor().at(IC4026.e)
d += elm.Resistor().at(IC4026.f)
d += elm.Resistor().at(IC4026.g).label('7 x 330', loc='bottom')
d += elm.Ground(lead=False).at(disp.cathode)
Arduino Board
^^^^^^^^^^^^^
The Arduino board uses :py:class:`schemdraw.elements.connectors.OrthoLines` to easily add all connections between data bus and headers.
.. jupyter-execute::
:code-below:
class Atmega328(elm.Ic):
def __init__(self, *args, **kwargs):
pins=[elm.IcPin(name='PD0', pin='2', side='r', slot='1/22'),
elm.IcPin(name='PD1', pin='3', side='r', slot='2/22'),
elm.IcPin(name='PD2', pin='4', side='r', slot='3/22'),
elm.IcPin(name='PD3', pin='5', side='r', slot='4/22'),
elm.IcPin(name='PD4', pin='6', side='r', slot='5/22'),
elm.IcPin(name='PD5', pin='11', side='r', slot='6/22'),
elm.IcPin(name='PD6', pin='12', side='r', slot='7/22'),
elm.IcPin(name='PD7', pin='13', side='r', slot='8/22'),
elm.IcPin(name='PC0', pin='23', side='r', slot='10/22'),
elm.IcPin(name='PC1', pin='24', side='r', slot='11/22'),
elm.IcPin(name='PC2', pin='25', side='r', slot='12/22'),
elm.IcPin(name='PC3', pin='26', side='r', slot='13/22'),
elm.IcPin(name='PC4', pin='27', side='r', slot='14/22'),
elm.IcPin(name='PC5', pin='28', side='r', slot='15/22'),
elm.IcPin(name='PB0', pin='14', side='r', slot='17/22'),
elm.IcPin(name='PB1', pin='15', side='r', slot='18/22'),
elm.IcPin(name='PB2', pin='16', side='r', slot='19/22'),
elm.IcPin(name='PB3', pin='17', side='r', slot='20/22'),
elm.IcPin(name='PB4', pin='18', side='r', slot='21/22'),
elm.IcPin(name='PB5', pin='19', side='r', slot='22/22'),
elm.IcPin(name='RESET', side='l', slot='22/22', invert=True, pin='1'),
elm.IcPin(name='XTAL2', side='l', slot='19/22', pin='10'),
elm.IcPin(name='XTAL1', side='l', slot='17/22', pin='9'),
elm.IcPin(name='AREF', side='l', slot='15/22', pin='21'),
elm.IcPin(name='AVCC', side='l', slot='14/22', pin='20'),
elm.IcPin(name='AGND', side='l', slot='13/22', pin='22'),
elm.IcPin(name='VCC', side='l', slot='11/22', pin='7'),
elm.IcPin(name='GND', side='l', slot='10/22', pin='8')]
super().__init__(pins=pins, w=5, plblofst=.05, botlabel='ATMEGA328', **kwargs)
with schemdraw.Drawing() as d:
d.config(fontsize=11, inches_per_unit=.4)
d += (Q1 := Atmega328())
d += (JP4 := elm.Header(rows=10, shownumber=True, pinsright=['D8', 'D9', 'D10', 'D11', 'D12', 'D13', '', '', '', ''], pinalignright='center')
.flip().at(Q1.PB5, dx=4, dy=1).anchor('pin6').label('JP4', fontsize=10))
d += (JP3 := elm.Header(rows=6, shownumber=True, pinsright=['A0', 'A1', 'A2', 'A3', 'A4', 'A5'], pinalignright='center')
.flip().at(Q1.PC5, dx=4).anchor('pin6').label('JP3', fontsize=10))
d += (JP2 := elm.Header(rows=8, shownumber=True, pinsright=['D0', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7'],
pinalignright='center')).at(Q1.PD7, dx=3).flip().anchor('pin8').label('JP2', fontsize=10)
d += elm.OrthoLines(n=6).at(Q1.PB5).to(JP4.pin6)
d += elm.OrthoLines(n=6).at(Q1.PC5).to(JP3.pin6)
d += elm.OrthoLines(n=8).at(Q1.PD7).to(JP2.pin8)
d += elm.Line().left(.9).at(JP4.pin7).label('GND', 'left')
d += elm.Line().left(.9).at(JP4.pin8).label('AREF', 'left')
d += elm.Line().left(.9).at(JP4.pin9).label('AD4/SDA', 'left')
d += elm.Line().left(.9).at(JP4.pin10).label('AD5/SCL', 'left')
d += (JP1 := elm.Header(rows=6, shownumber=True, pinsright=['VCC', 'RXD', 'TXD', 'DTR', 'RTS', 'GND'],
pinalignright='center').right().at(Q1.PD0, dx=4, dy=-2).anchor('pin1'))
d += elm.Line().left(d.unit/2).at(JP1.pin1)
d += elm.Vdd().label('+5V')
d += elm.Line().left().at(JP1.pin2)
d += elm.Line().toy(Q1.PD0).dot()
d += elm.Line().left(d.unit+.6).at(JP1.pin3)
d += elm.Line().toy(Q1.PD1).dot()
d += elm.Line().left(d.unit/2).at(JP1.pin6)
d += elm.Ground()
d += elm.Line().left(d.unit*2).at(Q1.XTAL2).dot()
d.push()
d += elm.Capacitor().left(d.unit/2).scale(.75)
d += elm.Line().toy(Q1.XTAL1).dot()
d += elm.Ground()
d += elm.Capacitor().right(d.unit/2).scale(.75).dot()
d.pop()
d += elm.Crystal().toy(Q1.XTAL1).label('16MHz', 'bottom')
d += elm.Line().tox(Q1.XTAL1)
d += elm.Line().left(d.unit/3).at(Q1.AREF).label('AREF', 'left')
d += elm.Line().left(1.5*d.unit).at(Q1.AVCC)
d += elm.Vdd().label('+5V')
d += elm.Line().toy(Q1.VCC).dot().idot()
d += elm.Line().tox(Q1.VCC).hold()
d += elm.Capacitor().down().label('100n')
d += (GND := elm.Ground())
d += elm.Line().left().at(Q1.AGND)
d += elm.Line().toy(Q1.GND).dot()
d += elm.Line().tox(Q1.GND).hold()
d += elm.Wire('|-').to(GND.center).dot()
d += elm.Line().left().at(Q1.RESET).dot()
d.push()
d += elm.RBox().up().label('10K')
d += elm.Vdd().label('+5V')
d.pop()
d += elm.Line().left().dot()
d.push()
d += (RST := elm.Button().up().label('Reset'))
d += elm.Line().left(d.unit/2)
d += elm.Ground()
d.pop()
d += elm.Capacitor().left().at(JP1.pin4).label('100n', 'bottom')
d += elm.Wire('c', k=-16).to(RST.start)
.. _dip741:
741 Opamp, DIP Layout
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (Q := elm.IcDIP(pins=8)
.label('Offset Null', loc='p1', fontsize=10)
.label('Inverting Input', loc='p2', fontsize=10)
.label('Non-inverting Input', loc='p3', fontsize=10)
.label('V-', loc='p4', fontsize=10)
.label('Offset Null', loc='p5', fontsize=10)
.label('Output', loc='p6', fontsize=10)
.label('V+', loc='p7', fontsize=10)
.label('NC', loc='p8', fontsize=10))
d += elm.Line().at(Q.p2_in).length(d.unit/5)
d += (op := elm.Opamp().anchor('in1').scale(.8))
d += elm.Line().at(Q.p3_in).length(d.unit/5)
d += elm.Wire('c', k=.3).at(op.out).to(Q.p6_in)
d += elm.Wire('-|').at(Q.p4_in).to(op.n1)
d += elm.Wire('-|').at(Q.p7_in).to(op.n2)
| 0.772959 | 0.365315 |
Opamp Circuits
--------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Inverting Opamp
^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down(d.unit/4).at(op.in2)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up(d.unit/2).at(op.in1)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right(d.unit/4).at(op.out).label('$v_{o}$', loc='right')
Non-inverting Opamp
^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += (out := elm.Line(at=op.out).length(.75))
d += elm.Line().up().at(op.in1).length(1.5).dot()
d.push()
d += elm.Resistor().left().label('$R_1$')
d += elm.Ground()
d.pop()
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Resistor().left().at(op.in2).idot().label('$R_2$')
d += elm.SourceV().down().reverse().label('$v_{in}$')
d += elm.Line().right().dot()
d += elm.Resistor().up().label('$R_3$').hold()
d += elm.Line().tox(out.end)
d += elm.Gap().toy(op.out).label(['–','$v_o$','+'])
Multi-stage amplifier
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Ground(lead=False)
d += elm.SourceV().label('500mV')
d += elm.Resistor().right().label('20k$\Omega$').dot()
d += (O1 := elm.Opamp(leads=True).anchor('in1'))
d += elm.Ground().at(O1.in2)
d += elm.Line().up(2).at(O1.in1)
d += elm.Resistor().tox(O1.out).label('100k$\Omega$')
d += elm.Line().toy(O1.out).dot()
d += elm.Line().right(5).at(O1.out)
d += (O2 := elm.Opamp(leads=True).anchor('in2'))
d += elm.Resistor().left().at(O2.in1).idot().label('30k$\Omega$')
d += elm.Ground()
d += elm.Line().up(1.5).at(O2.in1)
d += elm.Resistor().tox(O2.out).label('90k$\Omega$')
d += elm.Line().toy(O2.out).dot()
d += elm.Line().right(1).at(O2.out).label('$v_{out}$', loc='rgt')
Opamp pin labeling
^^^^^^^^^^^^^^^^^^
This example shows how to label pin numbers on a 741 opamp, and connect to the offset anchors.
Pin labels are somewhat manually placed; without the `ofst` and `align` keywords they
will be drawn directly over the anchor position.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
op = (elm.Opamp().label('741', loc='center', ofst=0)
.label('1', 'n1', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('5', 'n1a', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('4', 'vs', fontsize=9, ofst=(-.1, -.2), halign='right', valign='top')
.label('7', 'vd', fontsize=9, ofst=(-.1, .2), halign='right', valign='bottom')
.label('2', 'in1', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('3', 'in2', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('6', 'out', fontsize=9, ofst=(-.1, .1), halign='left', valign='bottom'))
d += op
d += elm.Line().left(.5).at(op.in1)
d += elm.Line().down(d.unit/2)
d += elm.Ground(lead=False)
d += elm.Line().left(.5).at(op.in2)
d += elm.Line().right(.5).at(op.out).label('$V_o$', 'right')
d += elm.Line().up(1).at(op.vd).label('$+V_s$', 'right')
d += (trim := elm.Potentiometer().down().at(op.n1).flip().scale(0.7))
d += elm.Line().tox(op.n1a)
d += elm.Line().up().to(op.n1a)
d += elm.Line().at(trim.tap).tox(op.vs).dot()
d.push()
d += elm.Line().down(d.unit/3)
d += elm.Ground()
d.pop()
d += elm.Line().toy(op.vs)
Triaxial Cable Driver
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=10)
d += elm.Line().length(d.unit/5).label('V', 'left')
d += (smu := elm.Opamp(sign=False).anchor('in2')
.label('SMU', 'center', ofst=[-.4, 0], halign='center', valign='center'))
d += elm.Line().at(smu.out).length(.3)
d.push()
d += elm.Line().length(d.unit/4)
d += (triax := elm.Triax(length=5, shieldofststart=.75))
d.pop()
d += elm.Resistor().up().scale(0.6).idot()
d += elm.Line().left().dot()
d += elm.Wire('|-').to(smu.in1).hold()
d += elm.Wire('|-').delta(d.unit/5, d.unit/5)
d += (buf := elm.Opamp(sign=False).anchor('in2').scale(0.6)
.label('BUF', 'center', ofst=(-.4, 0), halign='center', valign='center'))
d += elm.Line().left(d.unit/5).at(buf.in1)
d += elm.Wire('n').to(buf.out, dx=.5).dot()
d += elm.Wire('-|').at(buf.out).to(triax.guardstart_top)
d += elm.GroundChassis().at(triax.shieldcenter)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/opamp-checkpoint.rst
|
opamp-checkpoint.rst
|
Opamp Circuits
--------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Inverting Opamp
^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down(d.unit/4).at(op.in2)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up(d.unit/2).at(op.in1)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right(d.unit/4).at(op.out).label('$v_{o}$', loc='right')
Non-inverting Opamp
^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += (out := elm.Line(at=op.out).length(.75))
d += elm.Line().up().at(op.in1).length(1.5).dot()
d.push()
d += elm.Resistor().left().label('$R_1$')
d += elm.Ground()
d.pop()
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Resistor().left().at(op.in2).idot().label('$R_2$')
d += elm.SourceV().down().reverse().label('$v_{in}$')
d += elm.Line().right().dot()
d += elm.Resistor().up().label('$R_3$').hold()
d += elm.Line().tox(out.end)
d += elm.Gap().toy(op.out).label(['–','$v_o$','+'])
Multi-stage amplifier
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += elm.Ground(lead=False)
d += elm.SourceV().label('500mV')
d += elm.Resistor().right().label('20k$\Omega$').dot()
d += (O1 := elm.Opamp(leads=True).anchor('in1'))
d += elm.Ground().at(O1.in2)
d += elm.Line().up(2).at(O1.in1)
d += elm.Resistor().tox(O1.out).label('100k$\Omega$')
d += elm.Line().toy(O1.out).dot()
d += elm.Line().right(5).at(O1.out)
d += (O2 := elm.Opamp(leads=True).anchor('in2'))
d += elm.Resistor().left().at(O2.in1).idot().label('30k$\Omega$')
d += elm.Ground()
d += elm.Line().up(1.5).at(O2.in1)
d += elm.Resistor().tox(O2.out).label('90k$\Omega$')
d += elm.Line().toy(O2.out).dot()
d += elm.Line().right(1).at(O2.out).label('$v_{out}$', loc='rgt')
Opamp pin labeling
^^^^^^^^^^^^^^^^^^
This example shows how to label pin numbers on a 741 opamp, and connect to the offset anchors.
Pin labels are somewhat manually placed; without the `ofst` and `align` keywords they
will be drawn directly over the anchor position.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
op = (elm.Opamp().label('741', loc='center', ofst=0)
.label('1', 'n1', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('5', 'n1a', fontsize=9, ofst=(-.1, -.25), halign='right', valign='top')
.label('4', 'vs', fontsize=9, ofst=(-.1, -.2), halign='right', valign='top')
.label('7', 'vd', fontsize=9, ofst=(-.1, .2), halign='right', valign='bottom')
.label('2', 'in1', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('3', 'in2', fontsize=9, ofst=(-.1, .1), halign='right', valign='bottom')
.label('6', 'out', fontsize=9, ofst=(-.1, .1), halign='left', valign='bottom'))
d += op
d += elm.Line().left(.5).at(op.in1)
d += elm.Line().down(d.unit/2)
d += elm.Ground(lead=False)
d += elm.Line().left(.5).at(op.in2)
d += elm.Line().right(.5).at(op.out).label('$V_o$', 'right')
d += elm.Line().up(1).at(op.vd).label('$+V_s$', 'right')
d += (trim := elm.Potentiometer().down().at(op.n1).flip().scale(0.7))
d += elm.Line().tox(op.n1a)
d += elm.Line().up().to(op.n1a)
d += elm.Line().at(trim.tap).tox(op.vs).dot()
d.push()
d += elm.Line().down(d.unit/3)
d += elm.Ground()
d.pop()
d += elm.Line().toy(op.vs)
Triaxial Cable Driver
^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=10)
d += elm.Line().length(d.unit/5).label('V', 'left')
d += (smu := elm.Opamp(sign=False).anchor('in2')
.label('SMU', 'center', ofst=[-.4, 0], halign='center', valign='center'))
d += elm.Line().at(smu.out).length(.3)
d.push()
d += elm.Line().length(d.unit/4)
d += (triax := elm.Triax(length=5, shieldofststart=.75))
d.pop()
d += elm.Resistor().up().scale(0.6).idot()
d += elm.Line().left().dot()
d += elm.Wire('|-').to(smu.in1).hold()
d += elm.Wire('|-').delta(d.unit/5, d.unit/5)
d += (buf := elm.Opamp(sign=False).anchor('in2').scale(0.6)
.label('BUF', 'center', ofst=(-.4, 0), halign='center', valign='center'))
d += elm.Line().left(d.unit/5).at(buf.in1)
d += elm.Wire('n').to(buf.out, dx=.5).dot()
d += elm.Wire('-|').at(buf.out).to(triax.guardstart_top)
d += elm.GroundChassis().at(triax.shieldcenter)
| 0.749362 | 0.514034 |
.. _gallerytiming:
Timing Diagrams
---------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Timing diagrams, based on `WaveDrom <https://wavedrom.com/>`_, are drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` class.
.. code-block:: python
from schemdraw import logic
SRAM read/write cycle
^^^^^^^^^^^^^^^^^^^^^
The SRAM examples make use of Schemdraw's extended 'edge' notation for labeling
timings just above and below the wave.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0.....1.'},
{'name': 'Out Enable', 'wave': '1.0.....1.'},
{'name': 'Data Out', 'wave': 'z...x6...z', 'data': ['Valid data']},
],
'edge': ['[0^:1.2]+[0^:8] $t_{WC}$',
'[0v:1]+[0v:5] $t_{AQ}$',
'[1:2]+[1:5] $t_{EQ}$',
'[2:2]+[2:5] $t_{GQ}$',
'[0^:5]-[3v:5]{lightgray,:}',
]
}, ygap=.5, grid=False)
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0......1'},
{'name': 'Write Enable', 'wave': '1..0...1..'},
{'name': 'Data In', 'wave': 'x...5....x', 'data': ['Valid data']},
],
'edge': ['[0^:1]+[0^:8] $t_{WC}$',
'[2:1]+[2:3] $t_{SA}$',
'[3^:4]+[3^:7] $t_{WD}$',
'[3^:7]+[3^:9] $t_{HD}$',
'[0^:1]-[2:1]{lightgray,:}'],
}, ygap=.4, grid=False)
J-K Flip Flop
^^^^^^^^^^^^^
Timing diagram for a J-K flip flop taken from `here <https://commons.wikimedia.org/wiki/File:JK_timing_diagram.svg>`_.
Notice the use of the `async` dictionary parameter on the J and K signals, and the color parameters for the output signals.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'J', 'wave': '0101', 'async': [0, .8, 1.3, 3.7, 7]},
{'name': 'K', 'wave': '010101', 'async': [0, 1.2, 2.3, 2.8, 3.2, 3.7, 7]},
{'name': 'Q', 'wave': '010.101', 'color': 'red', 'lw': 1.5},
{'name': '$\overline{Q}$', 'wave': '101.010', 'color': 'blue', 'lw': 1.5}],
'config': {'hscale': 1.5}}, risetime=.05)
Tutorial Examples
^^^^^^^^^^^^^^^^^
These examples were copied from `WaveDrom Tutorial <https://wavedrom.com/tutorial.html>`_.
They use the `from_json` class method so the examples can be pasted directly as a string. Otherwise, the setup must be converted to a proper Python dictionary.
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [{ name: "Alfa", wave: "01.zx=ud.23.456789" }] }''')
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "p.....|..." },
{ name: "Data", wave: "x.345x|=.x", data: ["head", "body", "tail", "data"] },
{ name: "Request", wave: "0.1..0|1.0" },
{},
{ name: "Acknowledge", wave: "1.....|01." }
]}''')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/timing-checkpoint.rst
|
timing-checkpoint.rst
|
.. _gallerytiming:
Timing Diagrams
---------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import logic
Timing diagrams, based on `WaveDrom <https://wavedrom.com/>`_, are drawn using the :py:class:`schemdraw.logic.timing.TimingDiagram` class.
.. code-block:: python
from schemdraw import logic
SRAM read/write cycle
^^^^^^^^^^^^^^^^^^^^^
The SRAM examples make use of Schemdraw's extended 'edge' notation for labeling
timings just above and below the wave.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0.....1.'},
{'name': 'Out Enable', 'wave': '1.0.....1.'},
{'name': 'Data Out', 'wave': 'z...x6...z', 'data': ['Valid data']},
],
'edge': ['[0^:1.2]+[0^:8] $t_{WC}$',
'[0v:1]+[0v:5] $t_{AQ}$',
'[1:2]+[1:5] $t_{EQ}$',
'[2:2]+[2:5] $t_{GQ}$',
'[0^:5]-[3v:5]{lightgray,:}',
]
}, ygap=.5, grid=False)
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'Address', 'wave': 'x4......x.', 'data': ['Valid address']},
{'name': 'Chip Select', 'wave': '1.0......1'},
{'name': 'Write Enable', 'wave': '1..0...1..'},
{'name': 'Data In', 'wave': 'x...5....x', 'data': ['Valid data']},
],
'edge': ['[0^:1]+[0^:8] $t_{WC}$',
'[2:1]+[2:3] $t_{SA}$',
'[3^:4]+[3^:7] $t_{WD}$',
'[3^:7]+[3^:9] $t_{HD}$',
'[0^:1]-[2:1]{lightgray,:}'],
}, ygap=.4, grid=False)
J-K Flip Flop
^^^^^^^^^^^^^
Timing diagram for a J-K flip flop taken from `here <https://commons.wikimedia.org/wiki/File:JK_timing_diagram.svg>`_.
Notice the use of the `async` dictionary parameter on the J and K signals, and the color parameters for the output signals.
.. jupyter-execute::
:code-below:
logic.TimingDiagram(
{'signal': [
{'name': 'clk', 'wave': 'P......'},
{'name': 'J', 'wave': '0101', 'async': [0, .8, 1.3, 3.7, 7]},
{'name': 'K', 'wave': '010101', 'async': [0, 1.2, 2.3, 2.8, 3.2, 3.7, 7]},
{'name': 'Q', 'wave': '010.101', 'color': 'red', 'lw': 1.5},
{'name': '$\overline{Q}$', 'wave': '101.010', 'color': 'blue', 'lw': 1.5}],
'config': {'hscale': 1.5}}, risetime=.05)
Tutorial Examples
^^^^^^^^^^^^^^^^^
These examples were copied from `WaveDrom Tutorial <https://wavedrom.com/tutorial.html>`_.
They use the `from_json` class method so the examples can be pasted directly as a string. Otherwise, the setup must be converted to a proper Python dictionary.
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [{ name: "Alfa", wave: "01.zx=ud.23.456789" }] }''')
.. jupyter-execute::
:code-below:
logic.TimingDiagram.from_json('''{ signal: [
{ name: "clk", wave: "p.....|..." },
{ name: "Data", wave: "x.345x|=.x", data: ["head", "body", "tail", "data"] },
{ name: "Request", wave: "0.1..0|1.0" },
{},
{ name: "Acknowledge", wave: "1.....|01." }
]}''')
| 0.794425 | 0.589096 |
Styles
------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Circuit elements can be styled using Matplotlib colors, line-styles, and line widths.
Resistor circle
^^^^^^^^^^^^^^^
Uses named colors in a loop.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
for i, color in enumerate(['red', 'orange', 'yellow', 'yellowgreen', 'green', 'blue', 'indigo', 'violet']):
d += elm.Resistor().theta(45*i+20).color(color).label('R{}'.format(i))
Hand-drawn
^^^^^^^^^^
And for a change of pace, activate Matplotlib's XKCD mode for "hand-drawn" look!
.. jupyter-execute::
:code-below:
import matplotlib.pyplot as plt
plt.xkcd()
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down().at(op.in2).length(d.unit/4)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up().at(op.in1).length(d.unit/2)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right().at(op.out).length(d.unit/4).label('$v_{o}$', loc='right')
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/styles-checkpoint.rst
|
styles-checkpoint.rst
|
Styles
------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Circuit elements can be styled using Matplotlib colors, line-styles, and line widths.
Resistor circle
^^^^^^^^^^^^^^^
Uses named colors in a loop.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
for i, color in enumerate(['red', 'orange', 'yellow', 'yellowgreen', 'green', 'blue', 'indigo', 'violet']):
d += elm.Resistor().theta(45*i+20).color(color).label('R{}'.format(i))
Hand-drawn
^^^^^^^^^^
And for a change of pace, activate Matplotlib's XKCD mode for "hand-drawn" look!
.. jupyter-execute::
:code-below:
import matplotlib.pyplot as plt
plt.xkcd()
with schemdraw.Drawing() as d:
d += (op := elm.Opamp(leads=True))
d += elm.Line().down().at(op.in2).length(d.unit/4)
d += elm.Ground(lead=False)
d += (Rin := elm.Resistor().at(op.in1).left().idot().label('$R_{in}$', loc='bot').label('$v_{in}$', loc='left'))
d += elm.Line().up().at(op.in1).length(d.unit/2)
d += elm.Resistor().tox(op.out).label('$R_f$')
d += elm.Line().toy(op.out).dot()
d += elm.Line().right().at(op.out).length(d.unit/4).label('$v_{o}$', loc='right')
| 0.70477 | 0.456955 |
Analog Circuits
---------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
Discharging capacitor
^^^^^^^^^^^^^^^^^^^^^
Shows how to connect to a switch with anchors.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (V1 := elm.SourceV().label('5V'))
d += elm.Line().right(d.unit*.75)
d += (S1 := elm.SwitchSpdt2(action='close').up().anchor('b').label('$t=0$', loc='rgt'))
d += elm.Line().right(d.unit*.75).at(S1.c)
d += elm.Resistor().down().label('$100\Omega$').label(['+','$v_o$','-'], loc='bot')
d += elm.Line().to(V1.start)
d += elm.Capacitor().at(S1.a).toy(V1.start).label('1$\mu$F').dot()
Capacitor Network
^^^^^^^^^^^^^^^^^
Shows how to use endpoints to specify exact start and end placement.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (C1 := elm.Capacitor().label('8nF').idot().label('a', 'left'))
d += (C2 := elm.Capacitor().label('18nF'))
d += (C3 := elm.Capacitor().down().label('8nF', loc='bottom'))
d += (C4 := elm.Capacitor().left().label('32nF'))
d += (C5 := elm.Capacitor().label('40nF', loc='bottom').dot().label('b', 'left'))
d += (C6 := elm.Capacitor().endpoints(C1.end, C5.start).label('2.8nF'))
d += (C7 := elm.Capacitor().endpoints(C2.end, C5.start)
.label('5.6nF', loc='center', ofst=(-.3, -.1), halign='right', valign='bottom'))
ECE201-Style Circuit
^^^^^^^^^^^^^^^^^^^^
This example demonstrate use of `push()` and `pop()` and using the 'tox' and 'toy' methods.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=2) # unit=2 makes elements have shorter than normal leads
d.push()
d += (R1 := elm.Resistor().down().label('20Ω'))
d += (V1 := elm.SourceV().down().reverse().label('120V'))
d += elm.Line().right(3).dot()
d.pop()
d += elm.Line().right(3).dot()
d += elm.SourceV().down().reverse().label('60V')
d += elm.Resistor().label('5Ω').dot()
d += elm.Line().right(3).dot()
d += elm.SourceI().up().label('36A')
d += elm.Resistor().label('10Ω').dot()
d += elm.Line().left(3).hold()
d += elm.Line().right(3).dot()
d += (R6 := elm.Resistor().toy(V1.end).label('6Ω').dot())
d += elm.Line().left(3).hold()
d += elm.Resistor().right().at(R6.start).label('1.6Ω').dot(open=True).label('a', 'right')
d += elm.Line().right().at(R6.end).dot(open=True).label('b', 'right')
Loop Currents
^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.lines.LoopCurrent` element to add loop currents, and rotating a label to make it fit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=5)
d += (V1 := elm.SourceV().label('20V'))
d += (R1 := elm.Resistor().right().label('400Ω'))
d += elm.Dot()
d.push()
d += (R2 := elm.Resistor().down().label('100Ω', loc='bot', rotate=True))
d += elm.Dot()
d.pop()
d += (L1 := elm.Line())
d += (I1 := elm.SourceI().down().label('1A', loc='bot'))
d += (L2 := elm.Line().tox(V1.start))
d += elm.LoopCurrent([R1,R2,L2,V1], pad=1.25).label('$I_1$')
d += elm.LoopCurrent([R1,I1,L2,R2], pad=1.25).label('$I_2$') # Use R1 as top element for both so they get the same height
AC Loop Analysis
^^^^^^^^^^^^^^^^
Another good problem for ECE students...
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (I1 := elm.SourceI().label('5∠0° A').dot())
d.push()
d += elm.Capacitor().right().label('-j3Ω').dot()
d += elm.Inductor().down().label('j2Ω').dot().hold()
d += elm.Resistor().right().label('5Ω').dot()
d += (V1 := elm.SourceV().down().reverse().label('5∠-90° V', loc='bot'))
d += elm.Line().tox(I1.start)
d.pop()
d += elm.Line().up(d.unit*.8)
d += (L1 := elm.Inductor().tox(V1.start).label('j3Ω'))
d += elm.Line().down(d.unit*.8)
d += elm.CurrentLabel(top=False, ofst=.3).at(L1).label('$i_g$')
Infinite Transmission Line
^^^^^^^^^^^^^^^^^^^^^^^^^^
Elements can be added inside for-loops if you need multiples.
The ellipsis is just another circuit element, called `DotDotDot` since Ellipsis is a reserved keyword in Python.
This also demonstrates the :py:class:`schemdraw.elements.ElementDrawing` class to merge multiple elements into a single definition.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2:
for i in range(3):
d2 += elm.ElementDrawing(d1)
d2.push()
d2 += elm.Line().length(d2.unit/6)
d2 += elm.DotDotDot()
d2 += elm.ElementDrawing(d1)
d2.pop()
d2.here = (d2.here[0], d2.here[1]-d2.unit)
d2 += elm.Line().right().length(d2.unit/6)
d2 += elm.DotDotDot()
Power supply
^^^^^^^^^^^^
Notice the diodes could be added individually, but here the built-in `Rectifier` element is used instead.
Also note the use of newline characters inside resistor and capacitor labels.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(inches_per_unit=.5, unit=3)
d += (D := elm.Rectifier())
d += elm.Line().left(d.unit*1.5).at(D.N).dot(open=True).idot()
d += elm.Line().left(d.unit*1.5).at(D.S).dot(open=True).idot()
d += (G := elm.Gap().toy(D.N).label(['–', 'AC IN', '+']))
d += (top := elm.Line().right(d.unit*3).at(D.E).idot())
d += (Q2 := elm.BjtNpn(circle=True).up().anchor('collector').label('Q2\n2n3055'))
d += elm.Line().down(d.unit/2).at(Q2.base)
d += (Q2b := elm.Dot())
d += elm.Line().left(d.unit/3)
d += (Q1 := elm.BjtNpn(circle=True).up().anchor('emitter').label('Q1\n 2n3054'))
d += elm.Line().at(Q1.collector).toy(top.center).dot()
d += elm.Line().down(d.unit/2).at(Q1.base).dot()
d += elm.Zener().down().reverse().label('D2\n500mA', loc='bot').dot()
d += (G := elm.Ground())
d += elm.Line().left().dot()
d += elm.Capacitor(polar=True).up().reverse().label('C2\n100$\mu$F\n50V', loc='bot').dot()
d += elm.Line().right().hold()
d += elm.Resistor().toy(top.end).label('R1\n2.2K\n50V', loc='bot').dot()
d.move(dx=-d.unit, dy=0)
d += elm.Capacitor(polar=True).toy(G.start).flip().label('C1\n 1000$\mu$F\n50V').dot().idot()
d += elm.Line().at(G.start).tox(D.W)
d += elm.Line().toy(D.W).dot()
d += elm.Resistor().right().at(Q2b.center).label('R2').label('56$\Omega$ 1W', loc='bot').dot()
d.push()
d += elm.Line().toy(top.start).dot()
d += elm.Line().tox(Q2.emitter)
d.pop()
d += elm.Capacitor(polar=True).toy(G.start).label('C3\n470$\mu$F\n50V', loc='bot').dot()
d += elm.Line().tox(G.start).hold()
d += elm.Line().right().dot()
d += elm.Resistor().toy(top.center).label('R3\n10K\n1W', loc='bot').dot()
d += elm.Line().left().hold()
d += elm.Line().right()
d += elm.Dot(open=True)
d += elm.Gap().toy(G.start).label(['+', '$V_{out}$', '–'])
d += elm.Dot(open=True)
d += elm.Line().left()
5-transistor Operational Transconductance Amplifer (OTA)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the use of current labels to show the bias currents.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# tail transistor
d += (Q1 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Line().down().length(0.5)
ground = d.here
d += elm.Ground()
# input pair
d += elm.Line().left().length(1).at(Q1.drain)
d += (Q2 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Dot().at(Q1.drain)
d += elm.Line().right().length(1)
d += (Q3 := elm.AnalogNFet()).anchor('source').theta(0)
# current mirror
d += (Q4 := elm.AnalogPFet()).anchor('drain').at(Q2.drain).theta(0)
d += (Q5 := elm.AnalogPFet()).anchor('drain').at(Q3.drain).theta(0).reverse()
d += elm.Line().right().at(Q4.gate).to(Q5.gate)
d += elm.Dot().at(0.5*(Q4.gate + Q5.gate))
d += elm.Line().down().toy(Q4.drain)
d += elm.Line().left().tox(Q4.drain)
d += elm.Dot()
# vcc connection
d += elm.Line().right().at(Q4.source).to(Q5.source)
d += elm.Dot().at(0.5*(Q4.source + Q5.source))
d += elm.Vdd()
# bias source
d += elm.Line().left().length(0.25).at(Q1.gate)
d += elm.SourceV().down().toy(ground).reverse().scale(0.5).label("Bias")
d += elm.Ground()
# signal labels
d += elm.Tag().at(Q2.gate).label("In+").left()
d += elm.Tag().at(Q3.gate).label("In−").right()
d += elm.Dot().at(Q3.drain)
d += elm.Line().right().tox(Q3.gate)
d += elm.Tag().right().label("Out").reverse()
# bias currents
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q1).label("20µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q4).label("10µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q5).label("10µA")
Quadruple loop negative feedback amplifier
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# place twoports
d += (N1 := elm.Nullor()).anchor('center')
d += (T1 := elm.TransimpedanceTransactor(reverse_output=True)).reverse().flip().anchor('center').at([0,-3]).label("B")
d += (T2 := elm.CurrentTransactor()).reverse().flip().anchor('center').at([0,-6]).label("D")
d += (T3 := elm.VoltageTransactor()).reverse().anchor('center').at([0,-9]).label("A")
d += (T4 := elm.TransadmittanceTransactor(reverse_output=True)).reverse().anchor('center').at([0,-12]).label("C")
## make connections
# right side
d += elm.Line().at(N1.out_n).to(T1.in_n)
d += elm.Line().at(T1.in_p).to(T2.in_n)
d += elm.Line().at(T3.in_n).to(T4.in_n)
d += elm.Line().right().length(1).at(N1.out_p)
pre_out = d.here
d += (outline := elm.Line()).right().length(1).dot(open=True)
out = d.here
d += elm.Gap().down().label(('+','$V_o$','–')).toy(N1.out_n)
d += elm.Line().idot(open=True).down().toy(T4.in_n)
d += elm.Line().left().to(T4.in_n)
d += elm.Dot()
d += elm.CurrentLabelInline(direction='in', ofst=-0.15).at(outline).label('$I_o$')
d += elm.Line().at(T2.in_p).right().tox(out)
d += elm.Dot()
d += elm.Line().right().at(T4.in_p).tox(pre_out)
d += elm.Line().up().toy(pre_out)
d += elm.Dot()
d += elm.Line().right().at(T3.in_p).tox(pre_out)
d += elm.Dot()
# left side
d += elm.Line().down().at(N1.in_n).to(T1.out_n)
d += elm.Line().up().at(T3.out_p).to(T1.out_p)
d += elm.Line().left().at(N1.in_p).length(1)
pre_in = d.here
d += (inline := elm.Line()).length(1).dot(open=True).left()
in_node = d.here
d += elm.Gap().down().label(('+','$V_i$','–')).toy(N1.in_n)
d += elm.Line().idot(open=True).down().toy(T4.out_n)
d += elm.Line().right().to(T4.out_n)
d += elm.CurrentLabelInline(direction='out', ofst=-0.15).at(inline).label('$I_i$')
d += elm.Line().left().at(T2.out_p).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T3.out_n).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T4.out_p).tox(pre_in)
d += elm.Line().up().toy(pre_in)
d += elm.Dot()
d += elm.Line().left().at(T2.out_n).tox(pre_in)
d += elm.Dot()
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/analog-checkpoint.rst
|
analog-checkpoint.rst
|
Analog Circuits
---------------
.. jupyter-execute::
:hide-code:
%config InlineBackend.figure_format = 'svg'
import schemdraw
from schemdraw import elements as elm
Discharging capacitor
^^^^^^^^^^^^^^^^^^^^^
Shows how to connect to a switch with anchors.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (V1 := elm.SourceV().label('5V'))
d += elm.Line().right(d.unit*.75)
d += (S1 := elm.SwitchSpdt2(action='close').up().anchor('b').label('$t=0$', loc='rgt'))
d += elm.Line().right(d.unit*.75).at(S1.c)
d += elm.Resistor().down().label('$100\Omega$').label(['+','$v_o$','-'], loc='bot')
d += elm.Line().to(V1.start)
d += elm.Capacitor().at(S1.a).toy(V1.start).label('1$\mu$F').dot()
Capacitor Network
^^^^^^^^^^^^^^^^^
Shows how to use endpoints to specify exact start and end placement.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += (C1 := elm.Capacitor().label('8nF').idot().label('a', 'left'))
d += (C2 := elm.Capacitor().label('18nF'))
d += (C3 := elm.Capacitor().down().label('8nF', loc='bottom'))
d += (C4 := elm.Capacitor().left().label('32nF'))
d += (C5 := elm.Capacitor().label('40nF', loc='bottom').dot().label('b', 'left'))
d += (C6 := elm.Capacitor().endpoints(C1.end, C5.start).label('2.8nF'))
d += (C7 := elm.Capacitor().endpoints(C2.end, C5.start)
.label('5.6nF', loc='center', ofst=(-.3, -.1), halign='right', valign='bottom'))
ECE201-Style Circuit
^^^^^^^^^^^^^^^^^^^^
This example demonstrate use of `push()` and `pop()` and using the 'tox' and 'toy' methods.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=2) # unit=2 makes elements have shorter than normal leads
d.push()
d += (R1 := elm.Resistor().down().label('20Ω'))
d += (V1 := elm.SourceV().down().reverse().label('120V'))
d += elm.Line().right(3).dot()
d.pop()
d += elm.Line().right(3).dot()
d += elm.SourceV().down().reverse().label('60V')
d += elm.Resistor().label('5Ω').dot()
d += elm.Line().right(3).dot()
d += elm.SourceI().up().label('36A')
d += elm.Resistor().label('10Ω').dot()
d += elm.Line().left(3).hold()
d += elm.Line().right(3).dot()
d += (R6 := elm.Resistor().toy(V1.end).label('6Ω').dot())
d += elm.Line().left(3).hold()
d += elm.Resistor().right().at(R6.start).label('1.6Ω').dot(open=True).label('a', 'right')
d += elm.Line().right().at(R6.end).dot(open=True).label('b', 'right')
Loop Currents
^^^^^^^^^^^^^
Using the :py:class:`schemdraw.elements.lines.LoopCurrent` element to add loop currents, and rotating a label to make it fit.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=5)
d += (V1 := elm.SourceV().label('20V'))
d += (R1 := elm.Resistor().right().label('400Ω'))
d += elm.Dot()
d.push()
d += (R2 := elm.Resistor().down().label('100Ω', loc='bot', rotate=True))
d += elm.Dot()
d.pop()
d += (L1 := elm.Line())
d += (I1 := elm.SourceI().down().label('1A', loc='bot'))
d += (L2 := elm.Line().tox(V1.start))
d += elm.LoopCurrent([R1,R2,L2,V1], pad=1.25).label('$I_1$')
d += elm.LoopCurrent([R1,I1,L2,R2], pad=1.25).label('$I_2$') # Use R1 as top element for both so they get the same height
AC Loop Analysis
^^^^^^^^^^^^^^^^
Another good problem for ECE students...
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += (I1 := elm.SourceI().label('5∠0° A').dot())
d.push()
d += elm.Capacitor().right().label('-j3Ω').dot()
d += elm.Inductor().down().label('j2Ω').dot().hold()
d += elm.Resistor().right().label('5Ω').dot()
d += (V1 := elm.SourceV().down().reverse().label('5∠-90° V', loc='bot'))
d += elm.Line().tox(I1.start)
d.pop()
d += elm.Line().up(d.unit*.8)
d += (L1 := elm.Inductor().tox(V1.start).label('j3Ω'))
d += elm.Line().down(d.unit*.8)
d += elm.CurrentLabel(top=False, ofst=.3).at(L1).label('$i_g$')
Infinite Transmission Line
^^^^^^^^^^^^^^^^^^^^^^^^^^
Elements can be added inside for-loops if you need multiples.
The ellipsis is just another circuit element, called `DotDotDot` since Ellipsis is a reserved keyword in Python.
This also demonstrates the :py:class:`schemdraw.elements.ElementDrawing` class to merge multiple elements into a single definition.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing(show=False) as d1:
d1 += elm.Resistor()
d1.push()
d1 += elm.Capacitor().down()
d1 += elm.Line().left()
d1.pop()
with schemdraw.Drawing() as d2:
for i in range(3):
d2 += elm.ElementDrawing(d1)
d2.push()
d2 += elm.Line().length(d2.unit/6)
d2 += elm.DotDotDot()
d2 += elm.ElementDrawing(d1)
d2.pop()
d2.here = (d2.here[0], d2.here[1]-d2.unit)
d2 += elm.Line().right().length(d2.unit/6)
d2 += elm.DotDotDot()
Power supply
^^^^^^^^^^^^
Notice the diodes could be added individually, but here the built-in `Rectifier` element is used instead.
Also note the use of newline characters inside resistor and capacitor labels.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(inches_per_unit=.5, unit=3)
d += (D := elm.Rectifier())
d += elm.Line().left(d.unit*1.5).at(D.N).dot(open=True).idot()
d += elm.Line().left(d.unit*1.5).at(D.S).dot(open=True).idot()
d += (G := elm.Gap().toy(D.N).label(['–', 'AC IN', '+']))
d += (top := elm.Line().right(d.unit*3).at(D.E).idot())
d += (Q2 := elm.BjtNpn(circle=True).up().anchor('collector').label('Q2\n2n3055'))
d += elm.Line().down(d.unit/2).at(Q2.base)
d += (Q2b := elm.Dot())
d += elm.Line().left(d.unit/3)
d += (Q1 := elm.BjtNpn(circle=True).up().anchor('emitter').label('Q1\n 2n3054'))
d += elm.Line().at(Q1.collector).toy(top.center).dot()
d += elm.Line().down(d.unit/2).at(Q1.base).dot()
d += elm.Zener().down().reverse().label('D2\n500mA', loc='bot').dot()
d += (G := elm.Ground())
d += elm.Line().left().dot()
d += elm.Capacitor(polar=True).up().reverse().label('C2\n100$\mu$F\n50V', loc='bot').dot()
d += elm.Line().right().hold()
d += elm.Resistor().toy(top.end).label('R1\n2.2K\n50V', loc='bot').dot()
d.move(dx=-d.unit, dy=0)
d += elm.Capacitor(polar=True).toy(G.start).flip().label('C1\n 1000$\mu$F\n50V').dot().idot()
d += elm.Line().at(G.start).tox(D.W)
d += elm.Line().toy(D.W).dot()
d += elm.Resistor().right().at(Q2b.center).label('R2').label('56$\Omega$ 1W', loc='bot').dot()
d.push()
d += elm.Line().toy(top.start).dot()
d += elm.Line().tox(Q2.emitter)
d.pop()
d += elm.Capacitor(polar=True).toy(G.start).label('C3\n470$\mu$F\n50V', loc='bot').dot()
d += elm.Line().tox(G.start).hold()
d += elm.Line().right().dot()
d += elm.Resistor().toy(top.center).label('R3\n10K\n1W', loc='bot').dot()
d += elm.Line().left().hold()
d += elm.Line().right()
d += elm.Dot(open=True)
d += elm.Gap().toy(G.start).label(['+', '$V_{out}$', '–'])
d += elm.Dot(open=True)
d += elm.Line().left()
5-transistor Operational Transconductance Amplifer (OTA)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the use of current labels to show the bias currents.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# tail transistor
d += (Q1 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Line().down().length(0.5)
ground = d.here
d += elm.Ground()
# input pair
d += elm.Line().left().length(1).at(Q1.drain)
d += (Q2 := elm.AnalogNFet()).anchor('source').theta(0).reverse()
d += elm.Dot().at(Q1.drain)
d += elm.Line().right().length(1)
d += (Q3 := elm.AnalogNFet()).anchor('source').theta(0)
# current mirror
d += (Q4 := elm.AnalogPFet()).anchor('drain').at(Q2.drain).theta(0)
d += (Q5 := elm.AnalogPFet()).anchor('drain').at(Q3.drain).theta(0).reverse()
d += elm.Line().right().at(Q4.gate).to(Q5.gate)
d += elm.Dot().at(0.5*(Q4.gate + Q5.gate))
d += elm.Line().down().toy(Q4.drain)
d += elm.Line().left().tox(Q4.drain)
d += elm.Dot()
# vcc connection
d += elm.Line().right().at(Q4.source).to(Q5.source)
d += elm.Dot().at(0.5*(Q4.source + Q5.source))
d += elm.Vdd()
# bias source
d += elm.Line().left().length(0.25).at(Q1.gate)
d += elm.SourceV().down().toy(ground).reverse().scale(0.5).label("Bias")
d += elm.Ground()
# signal labels
d += elm.Tag().at(Q2.gate).label("In+").left()
d += elm.Tag().at(Q3.gate).label("In−").right()
d += elm.Dot().at(Q3.drain)
d += elm.Line().right().tox(Q3.gate)
d += elm.Tag().right().label("Out").reverse()
# bias currents
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q1).label("20µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q4).label("10µA")
d += elm.CurrentLabel(length=1.25, ofst=0.25).at(Q5).label("10µA")
Quadruple loop negative feedback amplifier
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
# place twoports
d += (N1 := elm.Nullor()).anchor('center')
d += (T1 := elm.TransimpedanceTransactor(reverse_output=True)).reverse().flip().anchor('center').at([0,-3]).label("B")
d += (T2 := elm.CurrentTransactor()).reverse().flip().anchor('center').at([0,-6]).label("D")
d += (T3 := elm.VoltageTransactor()).reverse().anchor('center').at([0,-9]).label("A")
d += (T4 := elm.TransadmittanceTransactor(reverse_output=True)).reverse().anchor('center').at([0,-12]).label("C")
## make connections
# right side
d += elm.Line().at(N1.out_n).to(T1.in_n)
d += elm.Line().at(T1.in_p).to(T2.in_n)
d += elm.Line().at(T3.in_n).to(T4.in_n)
d += elm.Line().right().length(1).at(N1.out_p)
pre_out = d.here
d += (outline := elm.Line()).right().length(1).dot(open=True)
out = d.here
d += elm.Gap().down().label(('+','$V_o$','–')).toy(N1.out_n)
d += elm.Line().idot(open=True).down().toy(T4.in_n)
d += elm.Line().left().to(T4.in_n)
d += elm.Dot()
d += elm.CurrentLabelInline(direction='in', ofst=-0.15).at(outline).label('$I_o$')
d += elm.Line().at(T2.in_p).right().tox(out)
d += elm.Dot()
d += elm.Line().right().at(T4.in_p).tox(pre_out)
d += elm.Line().up().toy(pre_out)
d += elm.Dot()
d += elm.Line().right().at(T3.in_p).tox(pre_out)
d += elm.Dot()
# left side
d += elm.Line().down().at(N1.in_n).to(T1.out_n)
d += elm.Line().up().at(T3.out_p).to(T1.out_p)
d += elm.Line().left().at(N1.in_p).length(1)
pre_in = d.here
d += (inline := elm.Line()).length(1).dot(open=True).left()
in_node = d.here
d += elm.Gap().down().label(('+','$V_i$','–')).toy(N1.in_n)
d += elm.Line().idot(open=True).down().toy(T4.out_n)
d += elm.Line().right().to(T4.out_n)
d += elm.CurrentLabelInline(direction='out', ofst=-0.15).at(inline).label('$I_i$')
d += elm.Line().left().at(T2.out_p).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T3.out_n).tox(in_node)
d += elm.Dot()
d += elm.Line().left().at(T4.out_p).tox(pre_in)
d += elm.Line().up().toy(pre_in)
d += elm.Dot()
d += elm.Line().left().at(T2.out_n).tox(pre_in)
d += elm.Dot()
| 0.877069 | 0.469095 |
Signal Processing
-----------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import dsp
Signal processing elements are in the :py:mod:`schemdraw.dsp.dsp` module.
.. code-block:: python
from schemdraw import dsp
Various Networks
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Line().length(d.unit/3).label('in')
d += (inpt := dsp.Dot())
d += dsp.Arrow().length(d.unit/3)
d += (delay := dsp.Box(w=2, h=2).anchor('W').label('Delay\nT'))
d += dsp.Arrow().right(d.unit/2).at(delay.E)
d += (sm := dsp.SumSigma())
d += dsp.Arrow().at(sm.E).length(d.unit/2)
d += (intg := dsp.Box(w=2, h=2).anchor('W').label('$\int$'))
d += dsp.Arrow().right(d.unit/2).at(intg.E).label('out', loc='right')
d += dsp.Line().down(d.unit/2).at(inpt.center)
d += dsp.Line().tox(sm.S)
d += dsp.Arrow().toy(sm.S).label('+', loc='bot')
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=14)
d += dsp.Line().length(d.unit/2).label('F(s)').dot()
d.push()
d += dsp.Line().up(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h1 := dsp.Box(w=2, h=2).anchor('W').label('$H_1(s)$'))
d.pop()
d += dsp.Line().down(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h2 := dsp.Box(w=2, h=2).anchor('W').label('$H_2(s)$'))
d += (sm := dsp.SumSigma().right().at((h1.E[0] + d.unit/2, 0)).anchor('center'))
d += dsp.Line().at(h1.E).tox(sm.N)
d += dsp.Arrow().toy(sm.N)
d += dsp.Line().at(h2.E).tox(sm.S)
d += dsp.Arrow().toy(sm.S)
d += dsp.Arrow().right(d.unit/3).at(sm.E).label('Y(s)', 'right')
Superheterodyne Receiver
^^^^^^^^^^^^^^^^^^^^^^^^
`Source <https://www.electronicdesign.com/adc/high-speed-rf-sampling-adc-boosts-bandwidth-dynamic-range>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += dsp.Antenna()
d += dsp.Line().right(d.unit/4)
d += dsp.Filter(response='bp').fill('thistle').anchor('W').label('RF filter\n#1', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/4)
d += dsp.Amp().fill('lightblue').label('LNA')
d += dsp.Line().length(d.unit/4)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('RF filter\n#2', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/3)
d += (mix := dsp.Mixer().fill('navajowhite').label('Mixer'))
d += dsp.Line().at(mix.S).down(d.unit/3)
d += dsp.Oscillator().right().anchor('N').fill('navajowhite').label('Local\nOscillator', 'right', ofst=.2)
d += dsp.Line().at(mix.E).right(d.unit/3)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('IF filter', 'bottom', ofst=.2)
d += dsp.Line().right(d.unit/4)
d += dsp.Amp().fill('lightblue').label('IF\namplifier')
d += dsp.Line().length(d.unit/4)
d += dsp.Demod().anchor('W').fill('navajowhite').label('Demodulator', 'bottom', ofst=.2)
d += dsp.Arrow().right(d.unit/3)
Direct Conversion Receiver
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Antenna()
d += dsp.Arrow().right(d.unit/2).label('$f_{RF}$', 'bot')
d += dsp.Amp().label('LNA')
d += dsp.Line().right(d.unit/5).dot()
d.push()
d += dsp.Line().length(d.unit/4)
d += (mix1 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().length(d.unit/2)
d += (lpf1 := dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2))
d += dsp.Line().length(d.unit/6)
d += (adc1 := dsp.Adc().label('ADC'))
d += dsp.Arrow().length(d.unit/3)
d += (dsp1 := dsp.Ic(pins=[dsp.IcPin(side='L'), dsp.IcPin(side='L'), dsp.IcPin(side='R')],
size=(2.75, 5), leadlen=0).anchor('inL2').label('DSP'))
d += dsp.Arrow().at(dsp1.inR1).length(d.unit/3)
d.pop()
d += dsp.Line().toy(dsp1.inL1)
d += dsp.Arrow().tox(mix1.W)
d += (mix2 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().tox(lpf1.W)
d += dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2)
d += dsp.Line().tox(adc1.W)
d += dsp.Adc().label('ADC')
d += dsp.Arrow().to(dsp1.inL1)
d += dsp.Arrow().down(d.unit/6).reverse().at(mix1.S)
d += dsp.Line().left(d.unit*1.25)
d += dsp.Line().down(d.unit*.75)
d += (flo := dsp.Dot().label('$f_{LO}$', 'left'))
d.push()
d += dsp.Line().down(d.unit/5)
d += dsp.Oscillator().right().anchor('N').label('LO', 'left', ofst=.15)
d.pop()
d += dsp.Arrow().down(d.unit/4).reverse().at(mix2.S)
d += (b1 := dsp.Square().right().label('90°').anchor('N'))
d += dsp.Arrow().left(d.unit/4).reverse().at(b1.W)
d += dsp.Line().toy(flo.center)
d += dsp.Line().tox(flo.center)
Digital Filter
^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=1, fontsize=14)
d += dsp.Line().length(d.unit*2).label('x[n]', 'left').dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_0$', 'bottom')
d += dsp.Arrow()
d += (s0 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down()
d += (z1 := dsp.Square(label='$z^{-1}$'))
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_1$', 'bottom')
d += dsp.Arrow()
d += (s1 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().right()
d += dsp.Amp().label('$b_2$', 'bottom')
d += dsp.Arrow()
d += (s2 := dsp.Sum().anchor('W'))
d += dsp.Arrow().at(s2.N).toy(s1.S)
d += dsp.Arrow().at(s1.N).toy(s0.S)
d += dsp.Line().right(d.unit*2.75).at(s0.E).dot()
d += dsp.Arrow().right().label('y[n]', 'right').hold()
d += dsp.Arrow().down()
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().left()
d += (a1 := dsp.Amp().label('$-a_1$', 'bottom'))
d += dsp.Arrow().at(a1.out).tox(s1.E)
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().left()
d += (a2 := dsp.Amp().label('$-a_2$', 'bottom'))
d += dsp.Arrow().at(a2.out).tox(s2.E)
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/gallery/.ipynb_checkpoints/signalproc-checkpoint.rst
|
signalproc-checkpoint.rst
|
Signal Processing
-----------------
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
from schemdraw import dsp
Signal processing elements are in the :py:mod:`schemdraw.dsp.dsp` module.
.. code-block:: python
from schemdraw import dsp
Various Networks
^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Line().length(d.unit/3).label('in')
d += (inpt := dsp.Dot())
d += dsp.Arrow().length(d.unit/3)
d += (delay := dsp.Box(w=2, h=2).anchor('W').label('Delay\nT'))
d += dsp.Arrow().right(d.unit/2).at(delay.E)
d += (sm := dsp.SumSigma())
d += dsp.Arrow().at(sm.E).length(d.unit/2)
d += (intg := dsp.Box(w=2, h=2).anchor('W').label('$\int$'))
d += dsp.Arrow().right(d.unit/2).at(intg.E).label('out', loc='right')
d += dsp.Line().down(d.unit/2).at(inpt.center)
d += dsp.Line().tox(sm.S)
d += dsp.Arrow().toy(sm.S).label('+', loc='bot')
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=14)
d += dsp.Line().length(d.unit/2).label('F(s)').dot()
d.push()
d += dsp.Line().up(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h1 := dsp.Box(w=2, h=2).anchor('W').label('$H_1(s)$'))
d.pop()
d += dsp.Line().down(d.unit/2)
d += dsp.Arrow().right(d.unit/2)
d += (h2 := dsp.Box(w=2, h=2).anchor('W').label('$H_2(s)$'))
d += (sm := dsp.SumSigma().right().at((h1.E[0] + d.unit/2, 0)).anchor('center'))
d += dsp.Line().at(h1.E).tox(sm.N)
d += dsp.Arrow().toy(sm.N)
d += dsp.Line().at(h2.E).tox(sm.S)
d += dsp.Arrow().toy(sm.S)
d += dsp.Arrow().right(d.unit/3).at(sm.E).label('Y(s)', 'right')
Superheterodyne Receiver
^^^^^^^^^^^^^^^^^^^^^^^^
`Source <https://www.electronicdesign.com/adc/high-speed-rf-sampling-adc-boosts-bandwidth-dynamic-range>`_.
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(fontsize=12)
d += dsp.Antenna()
d += dsp.Line().right(d.unit/4)
d += dsp.Filter(response='bp').fill('thistle').anchor('W').label('RF filter\n#1', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/4)
d += dsp.Amp().fill('lightblue').label('LNA')
d += dsp.Line().length(d.unit/4)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('RF filter\n#2', 'bottom', ofst=.2)
d += dsp.Line().length(d.unit/3)
d += (mix := dsp.Mixer().fill('navajowhite').label('Mixer'))
d += dsp.Line().at(mix.S).down(d.unit/3)
d += dsp.Oscillator().right().anchor('N').fill('navajowhite').label('Local\nOscillator', 'right', ofst=.2)
d += dsp.Line().at(mix.E).right(d.unit/3)
d += dsp.Filter(response='bp').anchor('W').fill('thistle').label('IF filter', 'bottom', ofst=.2)
d += dsp.Line().right(d.unit/4)
d += dsp.Amp().fill('lightblue').label('IF\namplifier')
d += dsp.Line().length(d.unit/4)
d += dsp.Demod().anchor('W').fill('navajowhite').label('Demodulator', 'bottom', ofst=.2)
d += dsp.Arrow().right(d.unit/3)
Direct Conversion Receiver
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d += dsp.Antenna()
d += dsp.Arrow().right(d.unit/2).label('$f_{RF}$', 'bot')
d += dsp.Amp().label('LNA')
d += dsp.Line().right(d.unit/5).dot()
d.push()
d += dsp.Line().length(d.unit/4)
d += (mix1 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().length(d.unit/2)
d += (lpf1 := dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2))
d += dsp.Line().length(d.unit/6)
d += (adc1 := dsp.Adc().label('ADC'))
d += dsp.Arrow().length(d.unit/3)
d += (dsp1 := dsp.Ic(pins=[dsp.IcPin(side='L'), dsp.IcPin(side='L'), dsp.IcPin(side='R')],
size=(2.75, 5), leadlen=0).anchor('inL2').label('DSP'))
d += dsp.Arrow().at(dsp1.inR1).length(d.unit/3)
d.pop()
d += dsp.Line().toy(dsp1.inL1)
d += dsp.Arrow().tox(mix1.W)
d += (mix2 := dsp.Mixer().label('Mixer', ofst=0))
d += dsp.Arrow().tox(lpf1.W)
d += dsp.Filter(response='lp').label('LPF', 'bot', ofst=.2)
d += dsp.Line().tox(adc1.W)
d += dsp.Adc().label('ADC')
d += dsp.Arrow().to(dsp1.inL1)
d += dsp.Arrow().down(d.unit/6).reverse().at(mix1.S)
d += dsp.Line().left(d.unit*1.25)
d += dsp.Line().down(d.unit*.75)
d += (flo := dsp.Dot().label('$f_{LO}$', 'left'))
d.push()
d += dsp.Line().down(d.unit/5)
d += dsp.Oscillator().right().anchor('N').label('LO', 'left', ofst=.15)
d.pop()
d += dsp.Arrow().down(d.unit/4).reverse().at(mix2.S)
d += (b1 := dsp.Square().right().label('90°').anchor('N'))
d += dsp.Arrow().left(d.unit/4).reverse().at(b1.W)
d += dsp.Line().toy(flo.center)
d += dsp.Line().tox(flo.center)
Digital Filter
^^^^^^^^^^^^^^
.. jupyter-execute::
:code-below:
with schemdraw.Drawing() as d:
d.config(unit=1, fontsize=14)
d += dsp.Line().length(d.unit*2).label('x[n]', 'left').dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_0$', 'bottom')
d += dsp.Arrow()
d += (s0 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down()
d += (z1 := dsp.Square(label='$z^{-1}$'))
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().right()
d += dsp.Amp().label('$b_1$', 'bottom')
d += dsp.Arrow()
d += (s1 := dsp.Sum().anchor('W'))
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().right()
d += dsp.Amp().label('$b_2$', 'bottom')
d += dsp.Arrow()
d += (s2 := dsp.Sum().anchor('W'))
d += dsp.Arrow().at(s2.N).toy(s1.S)
d += dsp.Arrow().at(s1.N).toy(s0.S)
d += dsp.Line().right(d.unit*2.75).at(s0.E).dot()
d += dsp.Arrow().right().label('y[n]', 'right').hold()
d += dsp.Arrow().down()
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit/2).dot()
d.push()
d += dsp.Line().left()
d += (a1 := dsp.Amp().label('$-a_1$', 'bottom'))
d += dsp.Arrow().at(a1.out).tox(s1.E)
d.pop()
d += dsp.Arrow().down(d.unit*.75)
d += dsp.Square().label('$z^{-1}$')
d += dsp.Line().length(d.unit*.75)
d += dsp.Line().left()
d += (a2 := dsp.Amp().label('$-a_2$', 'bottom'))
d += dsp.Arrow().at(a2.out).tox(s2.E)
| 0.705684 | 0.579341 |
Drawing
=======
.. autoclass:: schemdraw.Drawing
:members:
:exclude-members: labelI, labelI_inline, loopI
Element
=======
.. autoclass:: schemdraw.elements.Element
:members:
:exclude-members: add_label
Element2Term
============
.. autoclass:: schemdraw.elements.Element2Term
:members:
ElementDrawing
==============
.. autoclass:: schemdraw.elements.ElementDrawing
:members:
Element Style
=============
.. py:function:: schemdraw.elements.style(style)
Set global element style
:param style: dictionary of {elementname: Element} to change the element module namespace. Use `elements.STYLE_US` or `elements.STYLE_IEC` to define U.S. or European/IEC element styles.
.. autofunction:: schemdraw.config
.. autofunction:: schemdraw.theme
.. autofunction:: schemdraw.use
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/classes/drawing.rst
|
drawing.rst
|
Drawing
=======
.. autoclass:: schemdraw.Drawing
:members:
:exclude-members: labelI, labelI_inline, loopI
Element
=======
.. autoclass:: schemdraw.elements.Element
:members:
:exclude-members: add_label
Element2Term
============
.. autoclass:: schemdraw.elements.Element2Term
:members:
ElementDrawing
==============
.. autoclass:: schemdraw.elements.ElementDrawing
:members:
Element Style
=============
.. py:function:: schemdraw.elements.style(style)
Set global element style
:param style: dictionary of {elementname: Element} to change the element module namespace. Use `elements.STYLE_US` or `elements.STYLE_IEC` to define U.S. or European/IEC element styles.
.. autofunction:: schemdraw.config
.. autofunction:: schemdraw.theme
.. autofunction:: schemdraw.use
| 0.847369 | 0.302224 |
.. _elecelements:
Electrical Elements
===================
Two-Terminal Elements
---------------------
.. automodule:: schemdraw.elements.twoterm
:members:
:exclude-members: cycloid
.. automodule:: schemdraw.elements.sources
:members:
One-terminal Elements
---------------------
.. automodule:: schemdraw.elements.oneterm
:members:
Switches
--------
.. automodule:: schemdraw.elements.switches
:members:
Lines
-----
.. automodule:: schemdraw.elements.lines
:members:
Cables and Connectors
---------------------
.. automodule:: schemdraw.elements.cables
:members:
.. automodule:: schemdraw.elements.connectors
:members:
Transistors
-----------
.. automodule:: schemdraw.elements.transistors
:members:
Transformers
------------
.. automodule:: schemdraw.elements.xform
:members:
Opamp and Integrated Circuits
-----------------------------
.. automodule:: schemdraw.elements.opamp
:members:
.. automodule:: schemdraw.elements.intcircuits
:members:
Other
-----
.. automodule:: schemdraw.elements.misc
:members:
.. automodule:: schemdraw.elements.compound
:members:
.. automodule:: schemdraw.elements.twoports
:members:
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/classes/electrical.rst
|
electrical.rst
|
.. _elecelements:
Electrical Elements
===================
Two-Terminal Elements
---------------------
.. automodule:: schemdraw.elements.twoterm
:members:
:exclude-members: cycloid
.. automodule:: schemdraw.elements.sources
:members:
One-terminal Elements
---------------------
.. automodule:: schemdraw.elements.oneterm
:members:
Switches
--------
.. automodule:: schemdraw.elements.switches
:members:
Lines
-----
.. automodule:: schemdraw.elements.lines
:members:
Cables and Connectors
---------------------
.. automodule:: schemdraw.elements.cables
:members:
.. automodule:: schemdraw.elements.connectors
:members:
Transistors
-----------
.. automodule:: schemdraw.elements.transistors
:members:
Transformers
------------
.. automodule:: schemdraw.elements.xform
:members:
Opamp and Integrated Circuits
-----------------------------
.. automodule:: schemdraw.elements.opamp
:members:
.. automodule:: schemdraw.elements.intcircuits
:members:
Other
-----
.. automodule:: schemdraw.elements.misc
:members:
.. automodule:: schemdraw.elements.compound
:members:
.. automodule:: schemdraw.elements.twoports
:members:
| 0.821653 | 0.284873 |
.. _elecelements:
Electrical Elements
===================
Two-Terminal Elements
---------------------
.. automodule:: schemdraw.elements.twoterm
:members:
:exclude-members: cycloid
.. automodule:: schemdraw.elements.sources
:members:
One-terminal Elements
---------------------
.. automodule:: schemdraw.elements.oneterm
:members:
Switches
--------
.. automodule:: schemdraw.elements.switches
:members:
Lines
-----
.. automodule:: schemdraw.elements.lines
:members:
Cables and Connectors
---------------------
.. automodule:: schemdraw.elements.cables
:members:
.. automodule:: schemdraw.elements.connectors
:members:
Transistors
-----------
.. automodule:: schemdraw.elements.transistors
:members:
Transformers
------------
.. automodule:: schemdraw.elements.xform
:members:
Opamp and Integrated Circuits
-----------------------------
.. automodule:: schemdraw.elements.opamp
:members:
.. automodule:: schemdraw.elements.intcircuits
:members:
Other
-----
.. automodule:: schemdraw.elements.misc
:members:
.. automodule:: schemdraw.elements.compound
:members:
.. automodule:: schemdraw.elements.twoports
:members:
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/classes/.ipynb_checkpoints/electrical-checkpoint.rst
|
electrical-checkpoint.rst
|
.. _elecelements:
Electrical Elements
===================
Two-Terminal Elements
---------------------
.. automodule:: schemdraw.elements.twoterm
:members:
:exclude-members: cycloid
.. automodule:: schemdraw.elements.sources
:members:
One-terminal Elements
---------------------
.. automodule:: schemdraw.elements.oneterm
:members:
Switches
--------
.. automodule:: schemdraw.elements.switches
:members:
Lines
-----
.. automodule:: schemdraw.elements.lines
:members:
Cables and Connectors
---------------------
.. automodule:: schemdraw.elements.cables
:members:
.. automodule:: schemdraw.elements.connectors
:members:
Transistors
-----------
.. automodule:: schemdraw.elements.transistors
:members:
Transformers
------------
.. automodule:: schemdraw.elements.xform
:members:
Opamp and Integrated Circuits
-----------------------------
.. automodule:: schemdraw.elements.opamp
:members:
.. automodule:: schemdraw.elements.intcircuits
:members:
Other
-----
.. automodule:: schemdraw.elements.misc
:members:
.. automodule:: schemdraw.elements.compound
:members:
.. automodule:: schemdraw.elements.twoports
:members:
| 0.821653 | 0.284873 |
Schemdraw documentation
=======================
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Schemdraw is a Python package for producing high-quality electrical circuit schematic diagrams.
Circuit elements are added, one at a time, similar to how you might draw them by hand, using Python methods.
For example,
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
creates a new schemdraw drawing with a resistor going to the right with a label of "1Ω".
The next element added to the drawing will start at the endpoint of the resistor.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
d += elm.Capacitor().down().label('10μF')
d += elm.Line().left()
d += elm.SourceSin().up().label('10V')
|
.. toctree::
:maxdepth: 1
:caption: Contents:
usage/start
usage/index
elements/elements
gallery/index
usage/customizing
classes/index
changes
contributing
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/.ipynb_checkpoints/index-checkpoint.rst
|
index-checkpoint.rst
|
Schemdraw documentation
=======================
.. jupyter-execute::
:hide-code:
import schemdraw
from schemdraw import elements as elm
Schemdraw is a Python package for producing high-quality electrical circuit schematic diagrams.
Circuit elements are added, one at a time, similar to how you might draw them by hand, using Python methods.
For example,
.. code-block:: python
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
creates a new schemdraw drawing with a resistor going to the right with a label of "1Ω".
The next element added to the drawing will start at the endpoint of the resistor.
.. jupyter-execute::
with schemdraw.Drawing() as d:
d += elm.Resistor().right().label('1Ω')
d += elm.Capacitor().down().label('10μF')
d += elm.Line().left()
d += elm.SourceSin().up().label('10V')
|
.. toctree::
:maxdepth: 1
:caption: Contents:
usage/start
usage/index
elements/elements
gallery/index
usage/customizing
classes/index
changes
contributing
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.742515 | 0.41561 |
Development
===========
Report bugs and feature requests on the `Issue Tracker <https://github.com/cdelker/schemdraw/issues>`_.
Code contributions are welcome, especially with new circuit elements (and we'd be happy to expand beyond electrical elements too). To contribute code, please fork the `source code repository <https://github.com/cdelker/schemdraw/>`_ and issue a pull request. Make sure to include any new elements somewhere in the test Jupyter notebooks and in the documentation.
- `Source Code <https://github.com/cdelker/schemdraw>`_
|
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
|
schemdraw
|
/schemdraw-0.17.tar.gz/schemdraw-0.17/docs/.ipynb_checkpoints/contributing-checkpoint.rst
|
contributing-checkpoint.rst
|
Development
===========
Report bugs and feature requests on the `Issue Tracker <https://github.com/cdelker/schemdraw/issues>`_.
Code contributions are welcome, especially with new circuit elements (and we'd be happy to expand beyond electrical elements too). To contribute code, please fork the `source code repository <https://github.com/cdelker/schemdraw/>`_ and issue a pull request. Make sure to include any new elements somewhere in the test Jupyter notebooks and in the documentation.
- `Source Code <https://github.com/cdelker/schemdraw>`_
|
----------
Want to support Schemdraw development? Need more circuit examples? Pick up the Schemdraw Examples Pack on buymeacoffee.com:
.. raw:: html
<a href="https://www.buymeacoffee.com/cdelker/e/55648" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
| 0.694406 | 0.571229 |
# schemdule-extensions-audioplay
[](https://github.com/StardustDL/schemdule)
  [](https://pypi.org/project/schemdule-extensions-audioplay/) [](https://pepy.tech/project/schemdule-extensions-audioplay)
A audio player extension for
[Schemdule](https://github.com/StardustDL/schemdule).
- Platform    
- Python   
- [All extensions](https://pypi.org/search/?q=schemdule)
## Install
Install dependencies:
```sh
# Install dependencies on Linux (only)
sudo apt-get install -y python3-dev libasound2-dev
# Install ffmpeg
choco install ffmpeg # Windows
apt-get install -y ffmpeg # Linux
brew install ffmpeg # MacOS
```
Use pip:
```sh
pip install schemdule-extensions-audioplay
```
Or use pipx:
```sh
pipx inject schemdule schemdule-extensions-audioplay
# Upgrade
pipx upgrade schemdule --include-injected
```
Check if the extension installed:
```sh
schemdule ext
```
## Usage
This extension provide a `AudioPlayerPrompter` and add the following extension methods on `PrompterBuilder` and `PayloadBuilder`.
```python
class PrompterBuilder:
def useAudioPlayer(self: PrompterBuilder, endSpace: Optional[timedelta] = None, final: bool = False) -> PrompterBuilder:
"""
endSpace: Stop audio before next event, default 10 seconds. The empty space leads to the next event outdated.
"""
...
class PayloadBuilder:
def useAudio(self, files: Iterable[str]) -> "PayloadBuilder":
...
```
Use the extension in the schema script.
```python
# schema.py
ext("audioplay")
at(..., payloads().useAudio(["file1"]))
prompter.useAudioPlayer()
```
|
schemdule-extensions-audioplay
|
/schemdule-extensions-audioplay-0.1.0.tar.gz/schemdule-extensions-audioplay-0.1.0/README.md
|
README.md
|
# Install dependencies on Linux (only)
sudo apt-get install -y python3-dev libasound2-dev
# Install ffmpeg
choco install ffmpeg # Windows
apt-get install -y ffmpeg # Linux
brew install ffmpeg # MacOS
pip install schemdule-extensions-audioplay
pipx inject schemdule schemdule-extensions-audioplay
# Upgrade
pipx upgrade schemdule --include-injected
schemdule ext
class PrompterBuilder:
def useAudioPlayer(self: PrompterBuilder, endSpace: Optional[timedelta] = None, final: bool = False) -> PrompterBuilder:
"""
endSpace: Stop audio before next event, default 10 seconds. The empty space leads to the next event outdated.
"""
...
class PayloadBuilder:
def useAudio(self, files: Iterable[str]) -> "PayloadBuilder":
...
# schema.py
ext("audioplay")
at(..., payloads().useAudio(["file1"]))
prompter.useAudioPlayer()
| 0.443118 | 0.706558 |
import glob
import logging
import random
from dataclasses import dataclass, field
from datetime import datetime, time, timedelta
from enum import Enum
from time import sleep
from typing import Any, Callable, Iterable, Iterator, List
import simpleaudio
from pydub import AudioSegment, playback
from schemdule.configurations.globals import globalConfiguration
from schemdule.prompters import (Payload, PayloadCollection, Prompter,
PromptResult, SchedulePayload)
__version__ = "0.1.0"
@dataclass
class AudioPayload(Payload):
files: List[str] = field(default_factory=list)
class AudioPlayerPrompter(Prompter):
_logger = logging.getLogger("AudioPlayerPrompter")
def __init__(self, endSpace: timedelta, final: bool = False) -> None:
super().__init__(final)
self.endSpace = endSpace
def _needStop(self, schedule: SchedulePayload) -> bool:
return datetime.now() + self.endSpace + globalConfiguration.timeslice >= schedule.endTime
def prompt(self, payloads: PayloadCollection) -> PromptResult:
schedule = payloads.getSchedule()
audios: List[AudioPayload] = list(payloads.tryGet(AudioPayload))
if len(audios) == 0:
return PromptResult.Unsupported
for audio in audios:
if self._needStop(schedule):
break
for file in audio.files:
if self._needStop(schedule):
break
self._logger.debug(f"Load file {file}...")
sound = AudioSegment.from_file(file)
self._logger.info(
f"Play audio {file} ({timedelta(seconds=sound.duration_seconds)})...")
play_obj = simpleaudio.play_buffer(
sound.raw_data,
num_channels=sound.channels,
bytes_per_sample=sound.sample_width,
sample_rate=sound.frame_rate
)
while play_obj.is_playing():
sleep(globalConfiguration.timeslice.total_seconds())
if self._needStop(schedule):
self._logger.info(f"Stop audio {file}.")
play_obj.stop()
return self.success()
|
schemdule-extensions-audioplay
|
/schemdule-extensions-audioplay-0.1.0.tar.gz/schemdule-extensions-audioplay-0.1.0/schemdule/extensions/audioplay/__init__.py
|
__init__.py
|
import glob
import logging
import random
from dataclasses import dataclass, field
from datetime import datetime, time, timedelta
from enum import Enum
from time import sleep
from typing import Any, Callable, Iterable, Iterator, List
import simpleaudio
from pydub import AudioSegment, playback
from schemdule.configurations.globals import globalConfiguration
from schemdule.prompters import (Payload, PayloadCollection, Prompter,
PromptResult, SchedulePayload)
__version__ = "0.1.0"
@dataclass
class AudioPayload(Payload):
files: List[str] = field(default_factory=list)
class AudioPlayerPrompter(Prompter):
_logger = logging.getLogger("AudioPlayerPrompter")
def __init__(self, endSpace: timedelta, final: bool = False) -> None:
super().__init__(final)
self.endSpace = endSpace
def _needStop(self, schedule: SchedulePayload) -> bool:
return datetime.now() + self.endSpace + globalConfiguration.timeslice >= schedule.endTime
def prompt(self, payloads: PayloadCollection) -> PromptResult:
schedule = payloads.getSchedule()
audios: List[AudioPayload] = list(payloads.tryGet(AudioPayload))
if len(audios) == 0:
return PromptResult.Unsupported
for audio in audios:
if self._needStop(schedule):
break
for file in audio.files:
if self._needStop(schedule):
break
self._logger.debug(f"Load file {file}...")
sound = AudioSegment.from_file(file)
self._logger.info(
f"Play audio {file} ({timedelta(seconds=sound.duration_seconds)})...")
play_obj = simpleaudio.play_buffer(
sound.raw_data,
num_channels=sound.channels,
bytes_per_sample=sound.sample_width,
sample_rate=sound.frame_rate
)
while play_obj.is_playing():
sleep(globalConfiguration.timeslice.total_seconds())
if self._needStop(schedule):
self._logger.info(f"Stop audio {file}.")
play_obj.stop()
return self.success()
| 0.62223 | 0.076236 |
# schemdule-extensions-miaotixing
[](https://github.com/StardustDL/schemdule)
  [](https://pypi.org/project/schemdule-extensions-miaotixing/) [](https://pepy.tech/project/schemdule-extensions-miaotixing)
A [miaotixing](https://miaotixing.com/) extension for
[Schemdule](https://github.com/StardustDL/schemdule).
- Platform    
- Python   
- [All extensions](https://pypi.org/search/?q=schemdule)
## Install
Use pip:
```sh
pip install schemdule-extensions-miaotixing
```
Or use pipx:
```sh
pipx inject schemdule schemdule-extensions-miaotixing
# Upgrade
pipx upgrade schemdule --include-injected
```
Check if the extension installed:
```sh
schemdule ext
```
## Usage
This extension provide a `MiaotixingPrompter` and add the following extension methods on `PrompterBuilder`.
```python
class PrompterBuilder:
def useMiaotixing(self, code: str, final: bool = False) -> "PrompterBuilder":
...
```
Use the extension in the schema script.
```python
# schema.py
ext("miaotixing")
prompter.useMiaotixing()
```
|
schemdule-extensions-miaotixing
|
/schemdule-extensions-miaotixing-0.1.0.tar.gz/schemdule-extensions-miaotixing-0.1.0/README.md
|
README.md
|
pip install schemdule-extensions-miaotixing
pipx inject schemdule schemdule-extensions-miaotixing
# Upgrade
pipx upgrade schemdule --include-injected
schemdule ext
class PrompterBuilder:
def useMiaotixing(self, code: str, final: bool = False) -> "PrompterBuilder":
...
# schema.py
ext("miaotixing")
prompter.useMiaotixing()
| 0.489992 | 0.712482 |
# schemdule-extensions-simplegui
[](https://github.com/StardustDL/schemdule)
  [](https://pypi.org/project/schemdule-extensions-simplegui/) [](https://pepy.tech/project/schemdule-extensions-simplegui)
A simple GUI extension for
[Schemdule](https://github.com/StardustDL/schemdule).
- Platform    
- Python   
- [All extensions](https://pypi.org/search/?q=schemdule)
## Install
Use pip:
```sh
pip install schemdule-extensions-simplegui
```
Or use pipx:
```sh
pipx inject schemdule schemdule-extensions-simplegui
# Upgrade
pipx upgrade schemdule --include-injected
```
Check if the extension installed:
```sh
schemdule ext
```
## Usage
This extension provide a `MessageBoxPrompter` and add the following extension methods on `PrompterBuilder`.
```python
class PrompterBuilder:
def useMessageBox(self, autoClose: bool = False, maxKeep: Optional[timedelta] = None, final: bool = False) -> PrompterBuilder:
"""
maxKeep: The maximum duration to keep opening messagebox if autoClose is True, default 1 minute.
"""
...
```
Use the extension in the schema script.
```python
# schema.py
ext("simplegui")
prompter.useMessageBox()
```
|
schemdule-extensions-simplegui
|
/schemdule-extensions-simplegui-0.1.0.tar.gz/schemdule-extensions-simplegui-0.1.0/README.md
|
README.md
|
pip install schemdule-extensions-simplegui
pipx inject schemdule schemdule-extensions-simplegui
# Upgrade
pipx upgrade schemdule --include-injected
schemdule ext
class PrompterBuilder:
def useMessageBox(self, autoClose: bool = False, maxKeep: Optional[timedelta] = None, final: bool = False) -> PrompterBuilder:
"""
maxKeep: The maximum duration to keep opening messagebox if autoClose is True, default 1 minute.
"""
...
# schema.py
ext("simplegui")
prompter.useMessageBox()
| 0.60964 | 0.686035 |
Scheme: Declarative Schema Framework
====================================
.. image:: https://badge.fury.io/py/scheme.svg
:target: http://badge.fury.io/py/scheme
**Homepage:** `https://github.com/arterial-io/scheme <https://github.com/arterial-io/scheme>`_
Scheme is a declarative, general-purpose data schema framework for Python. It provides a simple approach to defining data schemas, and with those schemas enables serialization and unserialization to and from a variety of data formats, rich validation with descriptive error handling, hierarchical variable interpolation, and other interesting means of interacting with data.
Scheme can be used wherever incoming and outgoing structured data needs to be well-defined and validated: APIs, configuration files, complex user input, workflow and process user cases, and so on.
.. code-block:: python
>>> from scheme import *
>>> from datetime import date
>>> account = Structure({
'name': Text(nonempty=True),
'email': Email(nonempty=True),
'role': Enumeration('guest user admin', required=True, default='user'),
'active': Boolean(required=True, default=True),
'interests': Sequence(Text(nonempty=True), unique=True),
'logins': Integer(minimum=0, default=0),
'birthday': Date(),
}, name='account')
>>> json = '{"name": "Johnny Doe", "email": "[email protected]",
"interests": ["baseball", "basketball"], "birthday": "1980-03-05"}'
>>> account.unserialize(json, 'json')
{'name': 'Johnny Doe', 'email': '[email protected]', 'role': 'user',
'active': True, 'interests': ['baseball', 'basketball'], 'logins': 0,
'birthday': datetime.date(1980, 3, 5)}
>>> suzy = {'name': 'Suzy Queue', 'email': '[email protected]',
'role': 'admin', 'active': False, 'logins': 324,
'birthday': date(1985, 12, 2)}
>>> print(account.serialize(suzy, 'yaml'))
active: false
birthday: 1985-12-02
email: [email protected]
logins: 324
name: Suzy Queue
role: admin
>>> account.unserialize('{}', 'json')
Traceback (most recent call last):
...
scheme.exceptions.ValidationError: validation failed
[01] Required field error at (structure): account is missing required field 'name'
Field: Structure(name='account', ...)
[02] Required field error at (structure): account is missing required field 'email'
Field: Structure(name='account', ...)
>>> account.serialize({'name': 'Johnny Doe', 'email': '[email protected]',
'logins': -34}, 'json')
Traceback (most recent call last):
...
scheme.exceptions.ValidationError: validation failed
[01] Required field error at (structure): account is missing required field 'active'
Field: Structure(name='account', ...)
[02] Minimum value error at (structure).logins: logins must be greater then or equal to 0
Field: Integer(name='logins', minimum=0, default=0)
Value: -34
[03] Invalid value error at (structure).role: role must be one of 'guest', 'user', 'admin'
Field: Enumeration(name='role', ...)
Value: 'invalid'
Features
--------
- Simple, declarative schema definition
- Rich set of field types: *binary, boolean, date, datetime, decimal, email, enumeration, float integer, map, object, sequence, structure, text, time, token, tuple, uuid*
- Support for various serialization formats: *csv, json, structured text, xml, yaml*
- Rich validation with descriptive error reporting: *minimum/maximum length/value, pattern matching, etc.*
- Hierarchical variable interpolation
- Schema-mediated extraction of values from arbitrary objects
- Support for schema-based objects
- Serialization and unserialization of schemas, for dynamic use cases
Get it
------
::
$ pip install -U scheme
Requirements
------------
Python 2.6+ or 3.3+
License
-------
BSD licensed. See `LICENSE <https://github.com/arterial-io/scheme/blob/master/LICENSE>`_ for more details.
|
scheme
|
/scheme-2.0.2.tar.gz/scheme-2.0.2/README.rst
|
README.rst
|
Scheme: Declarative Schema Framework
====================================
.. image:: https://badge.fury.io/py/scheme.svg
:target: http://badge.fury.io/py/scheme
**Homepage:** `https://github.com/arterial-io/scheme <https://github.com/arterial-io/scheme>`_
Scheme is a declarative, general-purpose data schema framework for Python. It provides a simple approach to defining data schemas, and with those schemas enables serialization and unserialization to and from a variety of data formats, rich validation with descriptive error handling, hierarchical variable interpolation, and other interesting means of interacting with data.
Scheme can be used wherever incoming and outgoing structured data needs to be well-defined and validated: APIs, configuration files, complex user input, workflow and process user cases, and so on.
.. code-block:: python
>>> from scheme import *
>>> from datetime import date
>>> account = Structure({
'name': Text(nonempty=True),
'email': Email(nonempty=True),
'role': Enumeration('guest user admin', required=True, default='user'),
'active': Boolean(required=True, default=True),
'interests': Sequence(Text(nonempty=True), unique=True),
'logins': Integer(minimum=0, default=0),
'birthday': Date(),
}, name='account')
>>> json = '{"name": "Johnny Doe", "email": "[email protected]",
"interests": ["baseball", "basketball"], "birthday": "1980-03-05"}'
>>> account.unserialize(json, 'json')
{'name': 'Johnny Doe', 'email': '[email protected]', 'role': 'user',
'active': True, 'interests': ['baseball', 'basketball'], 'logins': 0,
'birthday': datetime.date(1980, 3, 5)}
>>> suzy = {'name': 'Suzy Queue', 'email': '[email protected]',
'role': 'admin', 'active': False, 'logins': 324,
'birthday': date(1985, 12, 2)}
>>> print(account.serialize(suzy, 'yaml'))
active: false
birthday: 1985-12-02
email: [email protected]
logins: 324
name: Suzy Queue
role: admin
>>> account.unserialize('{}', 'json')
Traceback (most recent call last):
...
scheme.exceptions.ValidationError: validation failed
[01] Required field error at (structure): account is missing required field 'name'
Field: Structure(name='account', ...)
[02] Required field error at (structure): account is missing required field 'email'
Field: Structure(name='account', ...)
>>> account.serialize({'name': 'Johnny Doe', 'email': '[email protected]',
'logins': -34}, 'json')
Traceback (most recent call last):
...
scheme.exceptions.ValidationError: validation failed
[01] Required field error at (structure): account is missing required field 'active'
Field: Structure(name='account', ...)
[02] Minimum value error at (structure).logins: logins must be greater then or equal to 0
Field: Integer(name='logins', minimum=0, default=0)
Value: -34
[03] Invalid value error at (structure).role: role must be one of 'guest', 'user', 'admin'
Field: Enumeration(name='role', ...)
Value: 'invalid'
Features
--------
- Simple, declarative schema definition
- Rich set of field types: *binary, boolean, date, datetime, decimal, email, enumeration, float integer, map, object, sequence, structure, text, time, token, tuple, uuid*
- Support for various serialization formats: *csv, json, structured text, xml, yaml*
- Rich validation with descriptive error reporting: *minimum/maximum length/value, pattern matching, etc.*
- Hierarchical variable interpolation
- Schema-mediated extraction of values from arbitrary objects
- Support for schema-based objects
- Serialization and unserialization of schemas, for dynamic use cases
Get it
------
::
$ pip install -U scheme
Requirements
------------
Python 2.6+ or 3.3+
License
-------
BSD licensed. See `LICENSE <https://github.com/arterial-io/scheme/blob/master/LICENSE>`_ for more details.
| 0.942546 | 0.647199 |
Tutorial
========
Create a schema
---------------
Let's start by creating a fairly simple schema. Our running example will be an API for a simple account management system.
>>> from scheme import *
>>> account = Structure({
'name': Text(description='the name for the account', nonempty=True),
'email': Email(),
'gender': Enumeration('male female'),
'active': Boolean(default=True),
'interests': Sequence(Text(nonempty=True), unique=True),
'logins': Integer(minimum=0, default=0),
}, name='account')
|
scheme
|
/scheme-2.0.2.tar.gz/scheme-2.0.2/docs/tutorial.rst
|
tutorial.rst
|
Tutorial
========
Create a schema
---------------
Let's start by creating a fairly simple schema. Our running example will be an API for a simple account management system.
>>> from scheme import *
>>> account = Structure({
'name': Text(description='the name for the account', nonempty=True),
'email': Email(),
'gender': Enumeration('male female'),
'active': Boolean(default=True),
'interests': Sequence(Text(nonempty=True), unique=True),
'logins': Integer(minimum=0, default=0),
}, name='account')
| 0.850127 | 0.918261 |
Fields
======
.. module:: scheme.field
Field
-----
.. autoclass:: scheme.field.Field
:members:
.. module:: scheme.fields
Binary
------
.. autoclass:: scheme.fields.Binary
:show-inheritance:
Boolean
-------
.. autoclass:: scheme.fields.Boolean
:show-inheritance:
Date
----
.. autoclass:: scheme.fields.Date
:show-inheritance:
DateTime
--------
.. autoclass:: scheme.fields.DateTime
:show-inheritance:
Decimal
-------
.. autoclass:: scheme.fields.Decimal
:show-inheritance:
Definition
----------
.. autoclass:: scheme.fields.Definition
:show-inheritance:
Email
-----
.. autoclass:: scheme.fields.Email
:show-inheritance:
Enumeration
-----------
.. autoclass:: scheme.fields.Enumeration
:show-inheritance:
Error
-----
.. autoclass:: scheme.fields.Error
:show-inheritance:
Float
-----
.. autoclass:: scheme.fields.Float
:show-inheritance:
Integer
-------
.. autoclass:: scheme.fields.Integer
:show-inheritance:
Map
---
.. autoclass:: scheme.fields.Map
:show-inheritance:
Object
------
.. autoclass:: scheme.fields.Object
:show-inheritance:
Sequence
--------
.. autoclass:: scheme.fields.Sequence
:show-inheritance:
Structure
---------
.. autoclass:: scheme.fields.Structure
:show-inheritance:
:members: has_required_fields, polymorphic, extend, generate_defaults, get, insert,
merge, process, remove, replace
Surrogate
---------
.. autoclass:: scheme.fields.Surrogate
:show-inheritance:
Text
----
.. autoclass:: scheme.fields.Text
:show-inheritance:
Time
----
.. autoclass:: scheme.fields.Time
:show-inheritance:
Token
-----
.. autoclass:: scheme.fields.Token
:show-inheritance:
Tuple
-----
.. autoclass:: scheme.fields.Tuple
:show-inheritance:
Union
-----
.. autoclass:: scheme.fields.Union
:show-inheritance:
UUID
----
.. autoclass:: scheme.fields.UUID
:show-inheritance:
|
scheme
|
/scheme-2.0.2.tar.gz/scheme-2.0.2/docs/fields.rst
|
fields.rst
|
Fields
======
.. module:: scheme.field
Field
-----
.. autoclass:: scheme.field.Field
:members:
.. module:: scheme.fields
Binary
------
.. autoclass:: scheme.fields.Binary
:show-inheritance:
Boolean
-------
.. autoclass:: scheme.fields.Boolean
:show-inheritance:
Date
----
.. autoclass:: scheme.fields.Date
:show-inheritance:
DateTime
--------
.. autoclass:: scheme.fields.DateTime
:show-inheritance:
Decimal
-------
.. autoclass:: scheme.fields.Decimal
:show-inheritance:
Definition
----------
.. autoclass:: scheme.fields.Definition
:show-inheritance:
Email
-----
.. autoclass:: scheme.fields.Email
:show-inheritance:
Enumeration
-----------
.. autoclass:: scheme.fields.Enumeration
:show-inheritance:
Error
-----
.. autoclass:: scheme.fields.Error
:show-inheritance:
Float
-----
.. autoclass:: scheme.fields.Float
:show-inheritance:
Integer
-------
.. autoclass:: scheme.fields.Integer
:show-inheritance:
Map
---
.. autoclass:: scheme.fields.Map
:show-inheritance:
Object
------
.. autoclass:: scheme.fields.Object
:show-inheritance:
Sequence
--------
.. autoclass:: scheme.fields.Sequence
:show-inheritance:
Structure
---------
.. autoclass:: scheme.fields.Structure
:show-inheritance:
:members: has_required_fields, polymorphic, extend, generate_defaults, get, insert,
merge, process, remove, replace
Surrogate
---------
.. autoclass:: scheme.fields.Surrogate
:show-inheritance:
Text
----
.. autoclass:: scheme.fields.Text
:show-inheritance:
Time
----
.. autoclass:: scheme.fields.Time
:show-inheritance:
Token
-----
.. autoclass:: scheme.fields.Token
:show-inheritance:
Tuple
-----
.. autoclass:: scheme.fields.Tuple
:show-inheritance:
Union
-----
.. autoclass:: scheme.fields.Union
:show-inheritance:
UUID
----
.. autoclass:: scheme.fields.UUID
:show-inheritance:
| 0.923087 | 0.151812 |
=======
Schemes
=======
Schemes is a library for validating and deserializing input obtained via JSON,
XML, msgpack or other similar formats, and for preparing data for serialization
for output to the same formats and/or for persistence (typically, but not
exclusively, to a cache or a NoSQL data store).
Overview
--------
In order to use Schemes, you need at first to define one or more schemas::
user_schema = Schema({'id': ReadOnly(Long()),
'username': String(min_length=3, max_length=16),
'fullname': Optional(String()),
'password': WriteOnly(String(min_length=8))})
You can then use the schema definition to create a document from input data::
try:
user = user_schema.create(
{'username': u'tawmas', 'password': u'supersecret'})
except ValidationError as error:
print(error.reason)
All fields are implicitly treated as mandatory, unless marked with a modifier
such as ``Optional``, ``ReadOnly`` or ``Internal``. If one or more validation
errors occurr, Schemes will report all validation errors in a friendly
dictionary structure.
You can update an existing document from new input data::
try:
user = user_schema.patch(user, {'password': u'verysecure'})
except ValidationError as error:
print(error.reason)
``patch()`` accepts partial inputs, and it only overwrites the fields which are
actually present in the input data.
Finally, you can leverage the schema to prepare a document for output::
representation = user_schema.emit(user)
This gives you a dictionary representation of your document suitable to be
serialized. Non-public fields are omitted, and some field types are converted
to a serialization friendly formats (for example, datetimes are emitted as RFC
3339 strings).
Early prerelease warning
------------------------
Schemes is at an early prerelease stage. As such, the public interface may well
change, and no documentation is available yet except for the Overview_ above.
Full documentation will be made available when the project reaches the beta
stage. In the meanwhile, you can have a look at the tests, especially the
integration tests in ``tests/integration``.
Initial development is on Python 2.7. The code is expected, and periodically
tested, to work on pypy, and it is expected to break on Python 3. Full support
for pypy and Python 3.3+ are planned for a later alpha stage.
Features and roadmap
--------------------
* Validation and conversion from a serialized format for document creation
and update.
* Conversion to a serializable external representation.
* Conversion to a serializable internal representation (PLANNED).
* Coercion of raw data (e.g. from a database or a cache) without triggering
full validation (PROVISIONAL IMPLEMENTATION).
* Easily extensible.
* Many field types supported out of the box:
* booleans
* integers
* longs
* floats
* decimals (PLANNED)
* unicode strings
* encoded bytestrings (PLANNED)
* datetimes
* dates
* lists
* embedded schemas
* Many field modifiers supported out of the box: optional (with or without a
default value), read-only (with optional automatic creation and update
values), write-only, internal.
* Support custom rules on existing field types (PLANNED).
* Alternate declarative syntax (PLANNED).
* Versioned schemas with automatic upgrade and downgrade of documents (PLANNED).
Installing Schemes
------------------
You can install Schemes with pip::
pip install schemes
If you want to hack on Schemes or run the test suite, you will also need to
install ``pytest``, and optionally the ``pytest-cov`` extension. You can
automatically install Schemes and its testing dependencies with pip::
pip install schemes[testing]
License
-------
Schemes is an open source project by `Tommaso R. Donnarumma`_, distributed under
the MIT license. See the ``LICENSE`` file for details.
Schemes comes with an embedded copy of the `python-rfc3339`_ library by LShift
Ltd., which is also distributed under the MIT license.
.. _Tommaso R. Donnarumma: http://www.tawmas.net/
.. _python-rfc3339: https://github.com/tonyg/python-rfc3339
|
schemes
|
/schemes-0.1.tar.gz/schemes-0.1/README.rst
|
README.rst
|
=======
Schemes
=======
Schemes is a library for validating and deserializing input obtained via JSON,
XML, msgpack or other similar formats, and for preparing data for serialization
for output to the same formats and/or for persistence (typically, but not
exclusively, to a cache or a NoSQL data store).
Overview
--------
In order to use Schemes, you need at first to define one or more schemas::
user_schema = Schema({'id': ReadOnly(Long()),
'username': String(min_length=3, max_length=16),
'fullname': Optional(String()),
'password': WriteOnly(String(min_length=8))})
You can then use the schema definition to create a document from input data::
try:
user = user_schema.create(
{'username': u'tawmas', 'password': u'supersecret'})
except ValidationError as error:
print(error.reason)
All fields are implicitly treated as mandatory, unless marked with a modifier
such as ``Optional``, ``ReadOnly`` or ``Internal``. If one or more validation
errors occurr, Schemes will report all validation errors in a friendly
dictionary structure.
You can update an existing document from new input data::
try:
user = user_schema.patch(user, {'password': u'verysecure'})
except ValidationError as error:
print(error.reason)
``patch()`` accepts partial inputs, and it only overwrites the fields which are
actually present in the input data.
Finally, you can leverage the schema to prepare a document for output::
representation = user_schema.emit(user)
This gives you a dictionary representation of your document suitable to be
serialized. Non-public fields are omitted, and some field types are converted
to a serialization friendly formats (for example, datetimes are emitted as RFC
3339 strings).
Early prerelease warning
------------------------
Schemes is at an early prerelease stage. As such, the public interface may well
change, and no documentation is available yet except for the Overview_ above.
Full documentation will be made available when the project reaches the beta
stage. In the meanwhile, you can have a look at the tests, especially the
integration tests in ``tests/integration``.
Initial development is on Python 2.7. The code is expected, and periodically
tested, to work on pypy, and it is expected to break on Python 3. Full support
for pypy and Python 3.3+ are planned for a later alpha stage.
Features and roadmap
--------------------
* Validation and conversion from a serialized format for document creation
and update.
* Conversion to a serializable external representation.
* Conversion to a serializable internal representation (PLANNED).
* Coercion of raw data (e.g. from a database or a cache) without triggering
full validation (PROVISIONAL IMPLEMENTATION).
* Easily extensible.
* Many field types supported out of the box:
* booleans
* integers
* longs
* floats
* decimals (PLANNED)
* unicode strings
* encoded bytestrings (PLANNED)
* datetimes
* dates
* lists
* embedded schemas
* Many field modifiers supported out of the box: optional (with or without a
default value), read-only (with optional automatic creation and update
values), write-only, internal.
* Support custom rules on existing field types (PLANNED).
* Alternate declarative syntax (PLANNED).
* Versioned schemas with automatic upgrade and downgrade of documents (PLANNED).
Installing Schemes
------------------
You can install Schemes with pip::
pip install schemes
If you want to hack on Schemes or run the test suite, you will also need to
install ``pytest``, and optionally the ``pytest-cov`` extension. You can
automatically install Schemes and its testing dependencies with pip::
pip install schemes[testing]
License
-------
Schemes is an open source project by `Tommaso R. Donnarumma`_, distributed under
the MIT license. See the ``LICENSE`` file for details.
Schemes comes with an embedded copy of the `python-rfc3339`_ library by LShift
Ltd., which is also distributed under the MIT license.
.. _Tommaso R. Donnarumma: http://www.tawmas.net/
.. _python-rfc3339: https://github.com/tonyg/python-rfc3339
| 0.885916 | 0.630358 |
from schemey.factory.any_of_schema_factory import AnyOfSchemaFactory
from schemey.factory.array_schema_factory import ArraySchemaFactory
from schemey.factory.dataclass_schema_factory import DataclassSchemaFactory
from schemey.factory.datetime_factory import DatetimeFactory
from schemey.factory.enum_schema_factory import EnumSchemaFactory
from schemey.factory.external_type_factory import ExternalTypeFactory
from schemey.factory.factory_schema_factory import FactorySchemaFactory
from schemey.factory.impl_schema_factory import ImplSchemaFactory
from schemey.factory.ref_schema_factory import RefSchemaFactory
from schemey.factory.simple_type_factory import SimpleTypeFactory
from schemey.factory.tuple_schema_factory import TupleSchemaFactory
from schemey.factory.uuid_factory import UuidFactory
from schemey.schema_context import SchemaContext
from schemey.json_schema import register_custom_json_schema_validator
from schemey.json_schema.ranges import ranges
from schemey.json_schema.timestamp import timestamp
priority = 100
def configure(context: SchemaContext):
context.register_factory(RefSchemaFactory())
context.register_factory(SimpleTypeFactory(bool, "boolean"))
context.register_factory(SimpleTypeFactory(int, "integer"))
context.register_factory(SimpleTypeFactory(type(None), "null"))
context.register_factory(SimpleTypeFactory(float, "number"))
context.register_factory(SimpleTypeFactory(str, "string"))
context.register_factory(DatetimeFactory())
context.register_factory(UuidFactory())
context.register_factory(ArraySchemaFactory())
context.register_factory(TupleSchemaFactory())
context.register_factory(ExternalTypeFactory())
context.register_factory(DataclassSchemaFactory())
context.register_factory(EnumSchemaFactory())
context.register_factory(FactorySchemaFactory())
context.register_factory(ImplSchemaFactory())
context.register_factory(AnyOfSchemaFactory())
register_custom_json_schema_validator("timestamp", timestamp)
register_custom_json_schema_validator("ranges", ranges)
|
schemey
|
/schemey-6.0.2.tar.gz/schemey-6.0.2/schemey_config_default/__init__.py
|
__init__.py
|
from schemey.factory.any_of_schema_factory import AnyOfSchemaFactory
from schemey.factory.array_schema_factory import ArraySchemaFactory
from schemey.factory.dataclass_schema_factory import DataclassSchemaFactory
from schemey.factory.datetime_factory import DatetimeFactory
from schemey.factory.enum_schema_factory import EnumSchemaFactory
from schemey.factory.external_type_factory import ExternalTypeFactory
from schemey.factory.factory_schema_factory import FactorySchemaFactory
from schemey.factory.impl_schema_factory import ImplSchemaFactory
from schemey.factory.ref_schema_factory import RefSchemaFactory
from schemey.factory.simple_type_factory import SimpleTypeFactory
from schemey.factory.tuple_schema_factory import TupleSchemaFactory
from schemey.factory.uuid_factory import UuidFactory
from schemey.schema_context import SchemaContext
from schemey.json_schema import register_custom_json_schema_validator
from schemey.json_schema.ranges import ranges
from schemey.json_schema.timestamp import timestamp
priority = 100
def configure(context: SchemaContext):
context.register_factory(RefSchemaFactory())
context.register_factory(SimpleTypeFactory(bool, "boolean"))
context.register_factory(SimpleTypeFactory(int, "integer"))
context.register_factory(SimpleTypeFactory(type(None), "null"))
context.register_factory(SimpleTypeFactory(float, "number"))
context.register_factory(SimpleTypeFactory(str, "string"))
context.register_factory(DatetimeFactory())
context.register_factory(UuidFactory())
context.register_factory(ArraySchemaFactory())
context.register_factory(TupleSchemaFactory())
context.register_factory(ExternalTypeFactory())
context.register_factory(DataclassSchemaFactory())
context.register_factory(EnumSchemaFactory())
context.register_factory(FactorySchemaFactory())
context.register_factory(ImplSchemaFactory())
context.register_factory(AnyOfSchemaFactory())
register_custom_json_schema_validator("timestamp", timestamp)
register_custom_json_schema_validator("ranges", ranges)
| 0.747708 | 0.086671 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from functools import wraps
from enum import Enum
from flask import request
from jsonschema import Draft4Validator, ValidationError
from werkzeug.exceptions import UnprocessableEntity
try:
import ujson as json
except ImportError:
import json
__author__ = 'Tim Martin'
__email__ = '[email protected]'
__version__ = '0.2.0'
class SchemaValidationError(UnprocessableEntity):
"""
Wraps a ValidationException in a format
that returns something useful to the frontend
"""
def __init__(self, exc, *args, **kwargs):
self.validation_exception = exc
super(SchemaValidationError, self).__init__(str(exc), *args, **kwargs)
class SchemaLoad(Enum):
"""
An Enum that indicates when the jsonschema should be loaded
"""
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
self_name = self.__class__.__name__
other_name = other.__class__.__name__
raise NotImplementedError(
'Cannot compare {0} '
'to {1}'.format(self_name, other_name))
def __gt__(self, other):
return not self.__lt__(other) and not self == other
def __ge__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self == other
ALWAYS_RELOAD = 0
ON_FIRST_USE = 1
ON_INIT = 2
ON_DECORATE = 3
def _request_loader():
return request.get_json()
class FlaskSchema(object):
"""
Used to wrap flask routes so that the
incoming JSON is validated using jsonschema
"""
def __init__(self,
schema_dir=None,
load_on=SchemaLoad.ON_INIT,
validator=Draft4Validator,
json_loader=json,
request_loader=_request_loader):
"""
:param str schema_dir: The directory which contains
the jsonschemas
:param SchemaLoad load_on: When to load the schemas
by default
:param DraftV4Validator validator: The validator class
to use. DraftV3Validator is also a valid class.
Any class with a classmethod `check_schema(json)`,
and instance methods `validate(json)` and `__init__(json)`
:param json_loader: By default ujson or json. Any drop in
replacement for `json` stdlib should work.
"""
self._schema_dir = schema_dir or '.'
self._schema_load = load_on
self._validator_builder = validator
self._schemas = {}
self._schema_load_ons = {}
self._json_loader = json_loader
self._request_loader = request_loader
@property
def schema_dir(self):
"""
:return: The directory where the json schemas are stored
"""
if callable(self._schema_dir):
return self._schema_dir()
return self._schema_dir
def init_app(self, schema_dir=None):
"""
Initialize all of the schemas where load_on is SchemaLoad.ON_INIT
:param str schema_dir: Override the schema directory
"""
self._schema_dir = schema_dir or self._schema_dir
for schema_name, load_on in self._schema_load_ons.items():
if load_on == SchemaLoad.ON_INIT:
self._schemas[schema_name] = self._build_schema(
schema_name, self._validator_builder)
def validate(
self,
schema_name,
load_on=None,
validator=None,
request_loader=None
):
"""
Returns a decorator for validating flask json requests
..code-block:: python
app = Flask('my-app')
validator = FlaskSchema('schema_dir/')
@app.route('/')
@validator.validate('my-schema.json')
def my_view():
# Everything has been validated at this point
:param str schema_name: The name of the file in the schemas
directory
:param SchemaLoad load_on: When to load the schema
:param validator:
:return: A decorator
"""
load_on = load_on or self._schema_load
validator = validator or self._validator_builder
self._schema_load_ons[schema_name] = load_on
if load_on >= SchemaLoad.ON_DECORATE:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
request_loader = request_loader or self._request_loader
def _decorator(func):
@wraps(func)
def _wrapper(*args, **kwargs):
if load_on <= SchemaLoad.ALWAYS_RELOAD:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
elif self._schemas.get(schema_name) is None:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
schema = self._schemas[schema_name]
try:
schema.validate(request_loader())
except ValidationError as exc:
raise SchemaValidationError(exc)
return func(*args, **kwargs)
return _wrapper
return _decorator
def _build_schema(self, schema_filename, validator):
schema_path = os.path.join(self.schema_dir, schema_filename)
with open(schema_path) as schema_file:
schema_data = self._json_loader.load(schema_file)
validator.check_schema(schema_data)
return validator(schema_data)
|
scheming-flask
|
/scheming-flask-0.2.0.tar.gz/scheming-flask-0.2.0/scheming_flask.py
|
scheming_flask.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
from functools import wraps
from enum import Enum
from flask import request
from jsonschema import Draft4Validator, ValidationError
from werkzeug.exceptions import UnprocessableEntity
try:
import ujson as json
except ImportError:
import json
__author__ = 'Tim Martin'
__email__ = '[email protected]'
__version__ = '0.2.0'
class SchemaValidationError(UnprocessableEntity):
"""
Wraps a ValidationException in a format
that returns something useful to the frontend
"""
def __init__(self, exc, *args, **kwargs):
self.validation_exception = exc
super(SchemaValidationError, self).__init__(str(exc), *args, **kwargs)
class SchemaLoad(Enum):
"""
An Enum that indicates when the jsonschema should be loaded
"""
def __lt__(self, other):
if self.__class__ is other.__class__:
return self.value < other.value
self_name = self.__class__.__name__
other_name = other.__class__.__name__
raise NotImplementedError(
'Cannot compare {0} '
'to {1}'.format(self_name, other_name))
def __gt__(self, other):
return not self.__lt__(other) and not self == other
def __ge__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self == other
ALWAYS_RELOAD = 0
ON_FIRST_USE = 1
ON_INIT = 2
ON_DECORATE = 3
def _request_loader():
return request.get_json()
class FlaskSchema(object):
"""
Used to wrap flask routes so that the
incoming JSON is validated using jsonschema
"""
def __init__(self,
schema_dir=None,
load_on=SchemaLoad.ON_INIT,
validator=Draft4Validator,
json_loader=json,
request_loader=_request_loader):
"""
:param str schema_dir: The directory which contains
the jsonschemas
:param SchemaLoad load_on: When to load the schemas
by default
:param DraftV4Validator validator: The validator class
to use. DraftV3Validator is also a valid class.
Any class with a classmethod `check_schema(json)`,
and instance methods `validate(json)` and `__init__(json)`
:param json_loader: By default ujson or json. Any drop in
replacement for `json` stdlib should work.
"""
self._schema_dir = schema_dir or '.'
self._schema_load = load_on
self._validator_builder = validator
self._schemas = {}
self._schema_load_ons = {}
self._json_loader = json_loader
self._request_loader = request_loader
@property
def schema_dir(self):
"""
:return: The directory where the json schemas are stored
"""
if callable(self._schema_dir):
return self._schema_dir()
return self._schema_dir
def init_app(self, schema_dir=None):
"""
Initialize all of the schemas where load_on is SchemaLoad.ON_INIT
:param str schema_dir: Override the schema directory
"""
self._schema_dir = schema_dir or self._schema_dir
for schema_name, load_on in self._schema_load_ons.items():
if load_on == SchemaLoad.ON_INIT:
self._schemas[schema_name] = self._build_schema(
schema_name, self._validator_builder)
def validate(
self,
schema_name,
load_on=None,
validator=None,
request_loader=None
):
"""
Returns a decorator for validating flask json requests
..code-block:: python
app = Flask('my-app')
validator = FlaskSchema('schema_dir/')
@app.route('/')
@validator.validate('my-schema.json')
def my_view():
# Everything has been validated at this point
:param str schema_name: The name of the file in the schemas
directory
:param SchemaLoad load_on: When to load the schema
:param validator:
:return: A decorator
"""
load_on = load_on or self._schema_load
validator = validator or self._validator_builder
self._schema_load_ons[schema_name] = load_on
if load_on >= SchemaLoad.ON_DECORATE:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
request_loader = request_loader or self._request_loader
def _decorator(func):
@wraps(func)
def _wrapper(*args, **kwargs):
if load_on <= SchemaLoad.ALWAYS_RELOAD:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
elif self._schemas.get(schema_name) is None:
self._schemas[schema_name] = self._build_schema(
schema_name, validator)
schema = self._schemas[schema_name]
try:
schema.validate(request_loader())
except ValidationError as exc:
raise SchemaValidationError(exc)
return func(*args, **kwargs)
return _wrapper
return _decorator
def _build_schema(self, schema_filename, validator):
schema_path = os.path.join(self.schema_dir, schema_filename)
with open(schema_path) as schema_file:
schema_data = self._json_loader.load(schema_file)
validator.check_schema(schema_data)
return validator(schema_data)
| 0.773601 | 0.074568 |
===============================
scheming-flask
===============================
.. image:: https://img.shields.io/pypi/v/scheming_flask.svg
:target: https://pypi.python.org/pypi/scheming_flask
.. image:: https://img.shields.io/travis/timmartin19/scheming_flask.svg
:target: https://travis-ci.org/timmartin19/scheming_flask
.. image:: https://readthedocs.org/projects/scheming-flask/badge/?version=latest
:target: https://scheming-flask.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://pyup.io/repos/github/timmartin19/scheming_flask/shield.svg
:target: https://pyup.io/repos/github/timmartin19/scheming_flask/
:alt: Updates
Use JSON Schema to validate incoming requests
* Free software: MIT license
* Documentation: https://scheming-flask.readthedocs.io.
Documentation
-------------
You will need to install the package dependencies first,
see the Installation section for details.
To build and open the documentation simply run:
.. code-block:: bash
bin/build-docs
Installation
------------
If you need to install pyenv/virtualenvwrapper you can run the `bin/setup-osx` command
Please note that this will modify your bash profile
Assuming you have virtualenv wrapper installed
.. code-block:: bash
mkvirtualenv scheming-flask
workon scheming-flask
pip install -r requirements_dev.txt
pip install -e .
Features
--------
* TODO
Credits
---------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
|
scheming-flask
|
/scheming-flask-0.2.0.tar.gz/scheming-flask-0.2.0/README.rst
|
README.rst
|
===============================
scheming-flask
===============================
.. image:: https://img.shields.io/pypi/v/scheming_flask.svg
:target: https://pypi.python.org/pypi/scheming_flask
.. image:: https://img.shields.io/travis/timmartin19/scheming_flask.svg
:target: https://travis-ci.org/timmartin19/scheming_flask
.. image:: https://readthedocs.org/projects/scheming-flask/badge/?version=latest
:target: https://scheming-flask.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://pyup.io/repos/github/timmartin19/scheming_flask/shield.svg
:target: https://pyup.io/repos/github/timmartin19/scheming_flask/
:alt: Updates
Use JSON Schema to validate incoming requests
* Free software: MIT license
* Documentation: https://scheming-flask.readthedocs.io.
Documentation
-------------
You will need to install the package dependencies first,
see the Installation section for details.
To build and open the documentation simply run:
.. code-block:: bash
bin/build-docs
Installation
------------
If you need to install pyenv/virtualenvwrapper you can run the `bin/setup-osx` command
Please note that this will modify your bash profile
Assuming you have virtualenv wrapper installed
.. code-block:: bash
mkvirtualenv scheming-flask
workon scheming-flask
pip install -r requirements_dev.txt
pip install -e .
Features
--------
* TODO
Credits
---------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
| 0.746786 | 0.468608 |
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/timmartin19/scheming_flask/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug"
and "help wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
scheming-flask could always use more documentation, whether as part of the
official scheming-flask docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/timmartin19/scheming_flask/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `scheming_flask` for local development.
1. Fork the `scheming_flask` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/scheming_flask.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv scheming_flask
$ cd scheming_flask/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox::
$ flake8 scheming_flask tests
$ python setup.py test or py.test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check
https://travis-ci.org/timmartin19/scheming_flask/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ python -m unittest tests.test_scheming_flask
|
scheming-flask
|
/scheming-flask-0.2.0.tar.gz/scheming-flask-0.2.0/CONTRIBUTING.rst
|
CONTRIBUTING.rst
|
.. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/timmartin19/scheming_flask/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug"
and "help wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
scheming-flask could always use more documentation, whether as part of the
official scheming-flask docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/timmartin19/scheming_flask/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `scheming_flask` for local development.
1. Fork the `scheming_flask` repo on GitHub.
2. Clone your fork locally::
$ git clone [email protected]:your_name_here/scheming_flask.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv scheming_flask
$ cd scheming_flask/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox::
$ flake8 scheming_flask tests
$ python setup.py test or py.test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 2.6, 2.7, 3.3, 3.4 and 3.5, and for PyPy. Check
https://travis-ci.org/timmartin19/scheming_flask/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ python -m unittest tests.test_scheming_flask
| 0.527317 | 0.45417 |
.. scheming_flask documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to scheming-flask's documentation!
======================================
Contents:
.. toctree::
:maxdepth: 2
installation
usage
contributing
history
.. include:: ../README.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
|
scheming-flask
|
/scheming-flask-0.2.0.tar.gz/scheming-flask-0.2.0/docs/index.rst
|
index.rst
|
.. scheming_flask documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to scheming-flask's documentation!
======================================
Contents:
.. toctree::
:maxdepth: 2
installation
usage
contributing
history
.. include:: ../README.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| 0.556882 | 0.205874 |
.. highlight:: shell
============
Installation
============
Stable release
--------------
To install scheming-flask, run this command in your terminal:
.. code-block:: console
$ pip install scheming_flask
This is the preferred method to install scheming-flask, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for scheming-flask can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/timmartin19/scheming_flask
Or download the `tarball`_:
.. code-block:: console
$ curl -OL https://github.com/timmartin19/scheming_flask/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/timmartin19/scheming_flask
.. _tarball: https://github.com/timmartin19/scheming_flask/tarball/master
|
scheming-flask
|
/scheming-flask-0.2.0.tar.gz/scheming-flask-0.2.0/docs/installation.rst
|
installation.rst
|
.. highlight:: shell
============
Installation
============
Stable release
--------------
To install scheming-flask, run this command in your terminal:
.. code-block:: console
$ pip install scheming_flask
This is the preferred method to install scheming-flask, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for scheming-flask can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/timmartin19/scheming_flask
Or download the `tarball`_:
.. code-block:: console
$ curl -OL https://github.com/timmartin19/scheming_flask/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/timmartin19/scheming_flask
.. _tarball: https://github.com/timmartin19/scheming_flask/tarball/master
| 0.626124 | 0.232877 |
# Installation #
In your terminal (vagrant), do:
```bash
cd [repo]/protected/config
cp db.json.sample db.json
cd [repo]/protected/schema
virtualenv env
. env/bin/activate
pip install -r requirements.txt
```
Next time, when you want to run schemup:
```bash
. env/bin/activate
python update.py commit
```
# General #
Schemup versions a database on a per-table basis. This means that table X can be at version 1, while table Y can be at version 2.
All versioning data is stored in a special table called `schemup_tables`. This table keeps other (versioned) tables' schema history, including what their latest schemas should look like (somewhat similar to git history).
Schemup provides 2 main features: validation (schemas synchronization checking), and migration (schemas updating).
# Version declaration #
This is basically just a map that states what version each table should be at. There are a couple of convenient helpers to build this map.
## Storm ORM
This is achieved by using a decorator, and adding a special attribute `__version__` to model class declarations.
```python
from storm.locals import *
from schemup.orms import storm
# Pass this to validate/upgrade commands. It should be a global
# shared among model files, if there are several of them
stormSchema = storm.StormSchema()
@stormSchema.versioned
class User(Storm):
__storm_table__ = "user"
__version__ = "knn_1"
```
## JSON file
Keep the map in a json file.
**`versions.json`**
```json
{
"users": "nta_6",
"message": "ntd_9"
}
```
**`update.py`**
```python
class DictSchema(object):
def __init__(self, path):
self.versions = json.load(open(path, "r"))
def getExpectedTableVersions(self):
return sorted(self.versions.iteritems())
# Pass this to validate/upgrade commands
dictSchema = DictSchema("versions.json")
```
# Validation #
Schemup helps keeping track, for each table, of the synchronization between 3 things:
- The desired schema, declared in code, or data file (actually only version, no table structure).
- The journaled schema (cached schema, recorded schema) in `schemup_tables` (both version and table structure).
- The actual DB schema (table structure only, obviously).
Full validation happens in 2 steps:
## Checking recorded schema vs. desired schema (version mismatches) ##
This is done by simply comparing the versions declared in code with the latest version recorded in `schemup_tables`. Note that there is not (yet) an actually schema comparison.
Out-of-sync tables detected by this validation indicate that the current schema in `schemup_tables` (and thus the actual schema, provided that they are in sync) need to be brought up-to-date with the desired schema (using Schemup migration feature).
## Checking recorded schema vs. actual schema (schema mismatches) ##
This is done by getting the schema information from the DB (e.g. `information_schema.tables`), and compare them against the last recorded schema in `schemup_tables`.
Mismatches detected by this validation usually means the schema was changed outside of Schemup's control, which should be avoided.
```python
from schemup import validator
from warp import runtime
conn = runtime.store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
errors = validator.findSchemaMismatches(dbSchema)
if errors:
print "Schema mismatches, was the schema changed outside Schemup?"
```
# Migration #
Schemup migration feature attempts to bring the real schema (and `schemup_tables`) up-to-date with the current ORM schema, by applying a series of "upgraders".
Each upgrader is responsible for bringing a table from one version to another, using an upgrading function that will be run on the DB schema.
An upgrader also has dependencies, which are the required versions of some tables before it can be run. For example, a foreign key referencing a table can only be added after the table is created.
There are 2 types of upgraders: those created from decorated Python functions, and those loaded from YAML files. There is a command to load both types from files under a directory.
```python
from schemup import commands
# Load upgraders from .py & .yaml files under "migration" directory
commands.load("migrations")
```
After getting all the necessary upgraders, the `upgrade` command can be used to carry out the migration.
```python
from schemup import commands
from warp import runtime
from models import stormSchema
conn = runtime.store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
commands.upgrade(dbSchema, stormSchema)
```
## Python upgrading functions ##
Note that the logic used by these functions must be immutable over time. Therefore application logic (functions, orm classes...) from other module must not be used directly, but copied for use only in the migrations; otherwise the migrations will be broken once application logic changes.
```python
from schemup.upgraders import upgrader
@upgrader('user', 'bgh_2', 'bgh_3')
def user_add_email(dbSchema):
dbSchema.execute("ALTER TABLE user ADD email VARCHAR")
# Or running arbitrary code here
@upgrader('order', None, 'knn_1', dependencies=[('user', 'bgh_1')])
def order_create(dbSchema):
dbSchema.execute("""
CREATE TABLE order (
id integer NOT NULL PRIMARY KEY,
user_id integer NOT NULL,
CONSTRAINT order_user_id FOREIGN KEY (user_id) REFERENCES user(id)
)
""")
```
## Upgraders loaded from YAML files ##
One file can contain multiple blocks delineated by `---`. Each block corresponds to an upgrader. If a block's `from` key is omitted, it defaults to the previous block's `to` key.
### One table per file ###
**`user.yaml`**
```yaml
---
# Another upgrader
---
table: user
from: bgh_2
to: bgh_3
sql: |
ALTER TABLE user ADD email VARCHAR
---
# Another upgrader
```
**`order.yaml`**
```yaml
---
table: order
from: null
to: knn_1
depends:
- [ user, bgh_1 ]
sql: |
CREATE TABLE order (
id integer NOT NULL PRIMARY KEY,
user_id integer NOT NULL,
CONSTRAINT order_user_id FOREIGN KEY (user_id) REFERENCES user(id)
)
```
### One feature per file ###
**`feature.add-rule-table.yaml`**
```yaml
---
table: questionnaire_rule
from: null
to: nta_1
depends:
- [questionnaire, nta_2]
sql: |
CREATE TABLE questionnaire_rule (
id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW(),
issue TEXT,
requires TEXT[2][],
recommendations INTEGER[],
questionnaire_id INTEGER NOT NULL REFERENCES questionnaire(id) ON DELETE RESTRICT
);
---
table: questionnaire
from: nta_3
to: nta_4
depends:
- [questionnaire_rule, nta_2]
sql: |
ALTER TABLE questionnaire
DROP COLUMN rules;
```
# Snapshoting #
## Whole schema ##
Use this when you have an existing database whose schema changes need to be kept track of with Schemup.
- Add version declarations.
- Add correct schema migrations. This ensures that a new instance can be created from scratch. If there is not enough time, a workaround can be used: put the schema dump in one of the migration, leaving the rest of the migrations no-op (e.g. `SELECT 1;`). For example:
```yaml
---
table: users
from: null
to: nta_1
sql: |
# The whole schema here
---
table: message
from: nul
to: nta_1
sql: |
SELECT 1;
# Other tables
```
- Use the `snapshot` command.
```python
from schemup.dbs import postgres
from schemup import commands
from warp.runtime import store
conn = store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
commands.snapshot(dbSchema, stormSchema)
```
## Single table (aka I mistakenly changed the schema in SQL shell) ##
Use this when you mistakenly chang a table's schema outside of schemup (e.g. trying out DDL in SQL shell without rolling back the transaction). This creates a
schema mismatch
```python
from warp.common.schema import makeSchema
from warp.runtime import store
schema = makeSchema(store)
schema.setSchema("recommendation", "nta_5")
schema.commit()
```
# Workflow #
- When adding to an existing DB, use snapshotting.
- When starting from scratch, provide upgraders with `from` equal to `None` (python) or `null` (yaml).
- Version naming convention: programmer initials and integer id. Example: `bgh_1`, `bgh_2`, `knn_3`, `nta_4`, `knn_5`.
- Migration organization: one-feature-per-file is preferred; initial schema can be in its own file.
## Upgraders ##
- When there are schema changes, bump model classes' `__version__`.
- Put upgraders under `migrations` directory. Upgraders can be yaml files, or python files containing upgrader-decorated functions.
- Test the migration manually on a dev DB.
- Remember that Postgres DDL is transactional. Therefore it is a good idea to try out migration DDL in Postgres shell, wrapped in a transaction that will be rolled back.
```sql
START TRANSACTION;
-- Try CREATE TABLE, ALTER TABLE... here
ROLLBACK;
```
## Migration ##
- Back up the DB before doing migration.
- Migration steps
```python
from schemup.dbs import postgres
from schemup import commands
from warp.runtime import store
# Get current table versions, by ORM
from models import stormSchema
# Get schema
conn = store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
# Make sure the current DB is not "dirty"
validator.findSchemaMismatches(dbSchema)
# Load upgraders
commands.load("migrations")
# Do upgrade
commands.upgrade(schema, stormSchema)
# Check if the schemas are in sync
commands.validate(runtime.schema, stormSchema)
```
## Shared dev machine ##
Schemup works on a forward-only, no-branching (directed acyclic graph) basis. This creates a problem in using shared dev machines:
- Supposed the main branch is at `user:a1`, `message:b1`.
- Developer A add migration `user:a_1` to `user:a_2` on his topic branch and test it on dev.
- Developer B add migration `message:b_1` to `message:b_2` and wants to test it on dev. He checks out his branch and runs the migration. Because `user` is at `a_2`, but the code wants it to be at `a_1`, schemup tries migrating `user` from `a_2` to `a_1` and fails not knowing how.
The best solution is to ensure that the DB's schema is the same before and after you test the code with new schema. For example:
- Make a dump of the whole database before running schema migration.
- Switch back to the branch the code was on previously after testing the new code.
- Replace the current state of the database with the dump.
## Snapshot-less application of schemup to existing DB ##
This method was by proposed Duy.
The idea is to use a dump as the DB's initial state, instead of a blank DB. The process looks like:
- Start with no migrations, blank version declarations.
- New instance are provisioned by the initial dump instead of just a blank DB.
- Continue as normal.
- New migrations should be written with the non-blank initial DB's state in mind. For example if the dump already contains a table `user`, its migrations should look like:
```yaml
---
table: user
from: null
to: lmd_1
sql: |
ALTER TABLE user ADD COLUMN age INTEGER DEFAULT NULL;
```
and not
```yaml
---
table: user
from: null
to: lmd_1
sql: |
CREATE TABLE user (
# ...
)
---
table: user
from: lmd_1
to: lmd_2
sql: |
ALTER TABLE user ADD COLUMN age INTEGER DEFAULT NULL;
```
|
schemup
|
/schemup-1.0.1.zip/schemup-1.0.1/README.md
|
README.md
|
cd [repo]/protected/config
cp db.json.sample db.json
cd [repo]/protected/schema
virtualenv env
. env/bin/activate
pip install -r requirements.txt
. env/bin/activate
python update.py commit
from storm.locals import *
from schemup.orms import storm
# Pass this to validate/upgrade commands. It should be a global
# shared among model files, if there are several of them
stormSchema = storm.StormSchema()
@stormSchema.versioned
class User(Storm):
__storm_table__ = "user"
__version__ = "knn_1"
{
"users": "nta_6",
"message": "ntd_9"
}
class DictSchema(object):
def __init__(self, path):
self.versions = json.load(open(path, "r"))
def getExpectedTableVersions(self):
return sorted(self.versions.iteritems())
# Pass this to validate/upgrade commands
dictSchema = DictSchema("versions.json")
from schemup import validator
from warp import runtime
conn = runtime.store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
errors = validator.findSchemaMismatches(dbSchema)
if errors:
print "Schema mismatches, was the schema changed outside Schemup?"
from schemup import commands
# Load upgraders from .py & .yaml files under "migration" directory
commands.load("migrations")
from schemup import commands
from warp import runtime
from models import stormSchema
conn = runtime.store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
commands.upgrade(dbSchema, stormSchema)
from schemup.upgraders import upgrader
@upgrader('user', 'bgh_2', 'bgh_3')
def user_add_email(dbSchema):
dbSchema.execute("ALTER TABLE user ADD email VARCHAR")
# Or running arbitrary code here
@upgrader('order', None, 'knn_1', dependencies=[('user', 'bgh_1')])
def order_create(dbSchema):
dbSchema.execute("""
CREATE TABLE order (
id integer NOT NULL PRIMARY KEY,
user_id integer NOT NULL,
CONSTRAINT order_user_id FOREIGN KEY (user_id) REFERENCES user(id)
)
""")
---
# Another upgrader
---
table: user
from: bgh_2
to: bgh_3
sql: |
ALTER TABLE user ADD email VARCHAR
---
# Another upgrader
---
table: order
from: null
to: knn_1
depends:
- [ user, bgh_1 ]
sql: |
CREATE TABLE order (
id integer NOT NULL PRIMARY KEY,
user_id integer NOT NULL,
CONSTRAINT order_user_id FOREIGN KEY (user_id) REFERENCES user(id)
)
---
table: questionnaire_rule
from: null
to: nta_1
depends:
- [questionnaire, nta_2]
sql: |
CREATE TABLE questionnaire_rule (
id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW(),
issue TEXT,
requires TEXT[2][],
recommendations INTEGER[],
questionnaire_id INTEGER NOT NULL REFERENCES questionnaire(id) ON DELETE RESTRICT
);
---
table: questionnaire
from: nta_3
to: nta_4
depends:
- [questionnaire_rule, nta_2]
sql: |
ALTER TABLE questionnaire
DROP COLUMN rules;
---
table: users
from: null
to: nta_1
sql: |
# The whole schema here
---
table: message
from: nul
to: nta_1
sql: |
SELECT 1;
# Other tables
from schemup.dbs import postgres
from schemup import commands
from warp.runtime import store
conn = store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
commands.snapshot(dbSchema, stormSchema)
from warp.common.schema import makeSchema
from warp.runtime import store
schema = makeSchema(store)
schema.setSchema("recommendation", "nta_5")
schema.commit()
START TRANSACTION;
-- Try CREATE TABLE, ALTER TABLE... here
ROLLBACK;
from schemup.dbs import postgres
from schemup import commands
from warp.runtime import store
# Get current table versions, by ORM
from models import stormSchema
# Get schema
conn = store.get_database().raw_connect()
dbSchema = postgres.PostgresSchema(conn)
# Make sure the current DB is not "dirty"
validator.findSchemaMismatches(dbSchema)
# Load upgraders
commands.load("migrations")
# Do upgrade
commands.upgrade(schema, stormSchema)
# Check if the schemas are in sync
commands.validate(runtime.schema, stormSchema)
---
table: user
from: null
to: lmd_1
sql: |
ALTER TABLE user ADD COLUMN age INTEGER DEFAULT NULL;
---
table: user
from: null
to: lmd_1
sql: |
CREATE TABLE user (
# ...
)
---
table: user
from: lmd_1
to: lmd_2
sql: |
ALTER TABLE user ADD COLUMN age INTEGER DEFAULT NULL;
| 0.675978 | 0.727806 |
2.1.1 / 2021-08-17
==================
- Update error message for incorrect choices field
`#572 <https://github.com/schematics/schematics/pull/572>`__
(`begor <https://github.com/begor>`__)
- Avoid some deprecation warnings when using Python 3
`#576 <https://github.com/schematics/schematics/pull/576>`__
(`jesuslosada <https://github.com/jesuslosada>`__)
- Fix EnumType enums with value=0 not working with use_values=True
`#594 <https://github.com/schematics/schematics/pull/594>`__
(`nikhilgupta345 <https://github.com/nikhilgupta345>`__)
- Fix syntax warning over comparison of literals using is.
`#611 <https://github.com/schematics/schematics/pull/611>`__
(`tirkarthi <https://github.com/tirkarthi>`__)
- Add help text generation capability to Models
`#543 <https://github.com/schematics/schematics/pull/543>`__
(`MartinHowarth <https://github.com/MartinHowarth>`__)
- Update documentation
`#578 <https://github.com/schematics/schematics/pull/578>`__
(`BobDu <https://github.com/BobDu>`__)
`#604 <https://github.com/schematics/schematics/pull/604>`__
(`BryanChan777 <https://github.com/BryanChan777>`__)
`#605 <https://github.com/schematics/schematics/pull/605>`__
(`timgates42 <https://github.com/timgates42>`__)
`#608 <https://github.com/schematics/schematics/pull/608>`__
(`dasubermanmind <https://github.com/dasubermanmind>`__)
- Add test coverage for model validation inside Dict/List
`#588 <https://github.com/schematics/schematics/pull/588>`__
(`borgstrom <https://github.com/borgstrom>`__)
- Added German translation
`#614 <https://github.com/schematics/schematics/pull/614>`__
(`hkage <https://github.com/hkage>`__)
2.1.0 / 2018-06-25
==================
**[BREAKING CHANGE]**
- Drop Python 2.6 support
`#517 <https://github.com/schematics/schematics/pull/517>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
Other changes:
- Add TimedeltaType
`#540 <https://github.com/schematics/schematics/pull/540>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Allow to create Model fields dynamically
`#512 <https://github.com/schematics/schematics/pull/512>`__
(`lkraider <https://github.com/lkraider>`__)
- Allow ModelOptions to have extra parameters
`#449 <https://github.com/schematics/schematics/pull/449>`__
(`rmb938 <https://github.com/rmb938>`__)
`#506 <https://github.com/schematics/schematics/pull/506>`__
(`ekampf <https://github.com/ekampf>`__)
- Accept callables as serialize roles
`#508 <https://github.com/schematics/schematics/pull/508>`__
(`lkraider <https://github.com/lkraider>`__)
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Simplify PolyModelType.find_model for readability
`#537 <https://github.com/schematics/schematics/pull/537>`__
(`kstrauser <https://github.com/kstrauser>`__)
- Enable PolyModelType recursive validation
`#535 <https://github.com/schematics/schematics/pull/535>`__
(`javiertejero <https://github.com/javiertejero>`__)
- Documentation fixes
`#509 <https://github.com/schematics/schematics/pull/509>`__
(`Tuoris <https://github.com/Tuoris>`__)
`#514 <https://github.com/schematics/schematics/pull/514>`__
(`tommyzli <https://github.com/tommyzli>`__)
`#518 <https://github.com/schematics/schematics/pull/518>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#546 <https://github.com/schematics/schematics/pull/546>`__
(`harveyslash <https://github.com/harveyslash>`__)
- Fix Model.init validation when partial is True
`#531 <https://github.com/schematics/schematics/issues/531>`__
(`lkraider <https://github.com/lkraider>`__)
- Minor number types refactor and mocking fixes
`#519 <https://github.com/schematics/schematics/pull/519>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#520 <https://github.com/schematics/schematics/pull/520>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
- Add ability to import models as strings
`#496 <https://github.com/schematics/schematics/pull/496>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Add EnumType
`#504 <https://github.com/schematics/schematics/pull/504>`__
(`ekamil <https://github.com/ekamil>`__)
- Dynamic models: Possible memory issues because of _subclasses
`#502 <https://github.com/schematics/schematics/pull/502>`__
(`mjrk <https://github.com/mjrk>`__)
- Add type hints to constructors of field type classes
`#488 <https://github.com/schematics/schematics/pull/488>`__
(`KonishchevDmitry <https://github.com/KonishchevDmitry>`__)
- Regression: Do not call field validator if field has not been set
`#499 <https://github.com/schematics/schematics/pull/499>`__
(`cmonfort <https://github.com/cmonfort>`__)
- Add possibility to translate strings and add initial pt_BR translations
`#495 <https://github.com/schematics/schematics/pull/495>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.1 / 2017-05-30
==================
- Support for raising DataError inside custom validate_fieldname methods.
`#441 <https://github.com/schematics/schematics/pull/441>`__
(`alexhayes <https://github.com/alexhayes>`__)
- Add specialized SchematicsDeprecationWarning.
(`lkraider <https://github.com/lkraider>`__)
- DateTimeType to_native method should handle type errors gracefully.
`#491 <https://github.com/schematics/schematics/pull/491>`__
(`e271828- <https://github.com/e271828->`__)
- Allow fields names to override the mapping-interface methods.
`#489 <https://github.com/schematics/schematics/pull/489>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.0 / 2017-05-22
==================
**[BREAKING CHANGE]**
Version 2.0 introduces many API changes, and it is not fully backwards-compatible with 1.x code.
`Full Changelog <https://github.com/schematics/schematics/compare/v1.1.2...v2.0.0>`_
- Add syntax highlighting to README examples
`#486 <https://github.com/schematics/schematics/pull/486>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Encode Unsafe data state in Model
`#484 <https://github.com/schematics/schematics/pull/484>`__
(`lkraider <https://github.com/lkraider>`__)
- Add MACAddressType
`#482 <https://github.com/schematics/schematics/pull/482>`__
(`aleksej-paschenko <https://github.com/aleksej-paschenko>`__)
2.0.0.b1 / 2017-04-06
=====================
- Enhancing and addressing some issues around exceptions:
`#477 <https://github.com/schematics/schematics/pull/477>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
- Allow primitive and native types to be inspected
`#431 <https://github.com/schematics/schematics/pull/431>`__
(`chadrik <https://github.com/chadrik>`__)
- Atoms iterator performance improvement
`#476 <https://github.com/schematics/schematics/pull/476>`__
(`vovanbo <https://github.com/vovanbo>`__)
- Fixes 453: Recursive import\_loop with ListType
`#475 <https://github.com/schematics/schematics/pull/475>`__
(`lkraider <https://github.com/lkraider>`__)
- Schema API
`#466 <https://github.com/schematics/schematics/pull/466>`__
(`lkraider <https://github.com/lkraider>`__)
- Tweak code example to avoid sql injection
`#462 <https://github.com/schematics/schematics/pull/462>`__
(`Ian-Foote <https://github.com/Ian-Foote>`__)
- Convert readthedocs links for their .org -> .io migration for hosted
projects `#454 <https://github.com/schematics/schematics/pull/454>`__
(`adamchainz <https://github.com/adamchainz>`__)
- Support all non-string Iterables as choices (dev branch)
`#436 <https://github.com/schematics/schematics/pull/436>`__
(`di <https://github.com/di>`__)
- When testing if a values is None or Undefined, use 'is'.
`#425 <https://github.com/schematics/schematics/pull/425>`__
(`chadrik <https://github.com/chadrik>`__)
2.0.0a1 / 2016-05-03
====================
- Restore v1 to\_native behavior; simplify converter code
`#412 <https://github.com/schematics/schematics/pull/412>`__
(`bintoro <https://github.com/bintoro>`__)
- Change conversion rules for booleans
`#407 <https://github.com/schematics/schematics/pull/407>`__
(`bintoro <https://github.com/bintoro>`__)
- Test for Model.\_\_init\_\_ context passing to types
`#399 <https://github.com/schematics/schematics/pull/399>`__
(`sheilatron <https://github.com/sheilatron>`__)
- Code normalization for Python 3 + general cleanup
`#391 <https://github.com/schematics/schematics/pull/391>`__
(`bintoro <https://github.com/bintoro>`__)
- Add support for arbitrary field metadata.
`#390 <https://github.com/schematics/schematics/pull/390>`__
(`chadrik <https://github.com/chadrik>`__)
- Introduce MixedType
`#380 <https://github.com/schematics/schematics/pull/380>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev2 / 2016-02-06
=======================
- Type maintenance
`#383 <https://github.com/schematics/schematics/pull/383>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev1 / 2016-02-01
=======================
- Performance optimizations
`#378 <https://github.com/schematics/schematics/pull/378>`__
(`bintoro <https://github.com/bintoro>`__)
- Validation refactoring + exception redesign
`#374 <https://github.com/schematics/schematics/pull/374>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix typo: serilaizataion --> serialization
`#373 <https://github.com/schematics/schematics/pull/373>`__
(`jeffwidman <https://github.com/jeffwidman>`__)
- Add support for undefined values
`#372 <https://github.com/schematics/schematics/pull/372>`__
(`bintoro <https://github.com/bintoro>`__)
- Serializable improvements
`#371 <https://github.com/schematics/schematics/pull/371>`__
(`bintoro <https://github.com/bintoro>`__)
- Unify import/export interface across all types
`#368 <https://github.com/schematics/schematics/pull/368>`__
(`bintoro <https://github.com/bintoro>`__)
- Correctly decode bytestrings in Python 3
`#365 <https://github.com/schematics/schematics/pull/365>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix NumberType.to\_native()
`#364 <https://github.com/schematics/schematics/pull/364>`__
(`bintoro <https://github.com/bintoro>`__)
- Make sure field.validate() uses a native type
`#363 <https://github.com/schematics/schematics/pull/363>`__
(`bintoro <https://github.com/bintoro>`__)
- Don't validate ListType items twice
`#362 <https://github.com/schematics/schematics/pull/362>`__
(`bintoro <https://github.com/bintoro>`__)
- Collect field validators as bound methods
`#361 <https://github.com/schematics/schematics/pull/361>`__
(`bintoro <https://github.com/bintoro>`__)
- Propagate environment during recursive import/export/validation
`#359 <https://github.com/schematics/schematics/pull/359>`__
(`bintoro <https://github.com/bintoro>`__)
- DateTimeType & TimestampType major rewrite
`#358 <https://github.com/schematics/schematics/pull/358>`__
(`bintoro <https://github.com/bintoro>`__)
- Always export empty compound objects as {} / []
`#351 <https://github.com/schematics/schematics/pull/351>`__
(`bintoro <https://github.com/bintoro>`__)
- export\_loop cleanup
`#350 <https://github.com/schematics/schematics/pull/350>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix FieldDescriptor.\_\_delete\_\_ to not touch model
`#349 <https://github.com/schematics/schematics/pull/349>`__
(`bintoro <https://github.com/bintoro>`__)
- Add validation method for latitude and longitude ranges in
GeoPointType
`#347 <https://github.com/schematics/schematics/pull/347>`__
(`wraziens <https://github.com/wraziens>`__)
- Fix longitude values for GeoPointType mock and add tests
`#344 <https://github.com/schematics/schematics/pull/344>`__
(`wraziens <https://github.com/wraziens>`__)
- Add support for self-referential ModelType fields
`#335 <https://github.com/schematics/schematics/pull/335>`__
(`bintoro <https://github.com/bintoro>`__)
- avoid unnecessary code path through try/except
`#327 <https://github.com/schematics/schematics/pull/327>`__
(`scavpy <https://github.com/scavpy>`__)
- Get mock object for ModelType and ListType
`#306 <https://github.com/schematics/schematics/pull/306>`__
(`kaiix <https://github.com/kaiix>`__)
1.1.3 / 2017-06-27
==================
* [Maintenance] (`#501 <https://github.com/schematics/schematics/issues/501>`_) Dynamic models: Possible memory issues because of _subclasses
1.1.2 / 2017-03-27
==================
* [Bug] (`#478 <https://github.com/schematics/schematics/pull/478>`_) Fix dangerous performance issue with ModelConversionError in nested models
1.1.1 / 2015-11-03
==================
* [Bug] (`befa202 <https://github.com/schematics/schematics/commit/befa202c3b3202aca89fb7ef985bdca06f9da37c>`_) Fix Unicode issue with DecimalType
* [Documentation] (`41157a1 <https://github.com/schematics/schematics/commit/41157a13896bd32a337c5503c04c5e9cc30ba4c7>`_) Documentation overhaul
* [Bug] (`860d717 <https://github.com/schematics/schematics/commit/860d71778421981f284c0612aec665ebf0cfcba2>`_) Fix import that was negatively affecting performance
* [Feature] (`93b554f <https://github.com/schematics/schematics/commit/93b554fd6a4e7b38133c4da5592b1843101792f0>`_) Add DataObject to datastructures.py
* [Bug] (`#236 <https://github.com/schematics/schematics/pull/236>`_) Set `None` on a field that's a compound type should honour that semantics
* [Maintenance] (`#348 <https://github.com/schematics/schematics/pull/348>`_) Update requirements
* [Maintenance] (`#346 <https://github.com/schematics/schematics/pull/346>`_) Combining Requirements
* [Maintenance] (`#342 <https://github.com/schematics/schematics/pull/342>`_) Remove to_primitive() method from compound types
* [Bug] (`#339 <https://github.com/schematics/schematics/pull/339>`_) Basic number validation
* [Bug] (`#336 <https://github.com/schematics/schematics/pull/336>`_) Don't evaluate serializable when accessed through class
* [Bug] (`#321 <https://github.com/schematics/schematics/pull/321>`_) Do not compile regex
* [Maintenance] (`#319 <https://github.com/schematics/schematics/pull/319>`_) Remove mock from install_requires
1.1.0 / 2015-07-12
==================
* [Feature] (`#303 <https://github.com/schematics/schematics/pull/303>`_) fix ListType, validate_items adds to errors list just field name without...
* [Feature] (`#304 <https://github.com/schematics/schematics/pull/304>`_) Include Partial Data when Raising ModelConversionError
* [Feature] (`#305 <https://github.com/schematics/schematics/pull/305>`_) Updated domain verifications to fit to RFC/working standards
* [Feature] (`#308 <https://github.com/schematics/schematics/pull/308>`_) Grennady ordered validation
* [Feature] (`#309 <https://github.com/schematics/schematics/pull/309>`_) improves date_time_type error message for custom formats
* [Feature] (`#310 <https://github.com/schematics/schematics/pull/310>`_) accept optional 'Z' suffix for UTC date_time_type format
* [Feature] (`#311 <https://github.com/schematics/schematics/pull/311>`_) Remove commented lines from models.py
* [Feature] (`#230 <https://github.com/schematics/schematics/pull/230>`_) Message normalization
1.0.4 / 2015-04-13
==================
* [Example] (`#286 <https://github.com/schematics/schematics/pull/286>`_) Add schematics usage with Django
* [Feature] (`#292 <https://github.com/schematics/schematics/pull/292>`_) increase domain length to 10 for .holiday, .vacations
* [Feature] (`#297 <https://github.com/schematics/schematics/pull/297>`_) Support for fields order in serialized format
* [Feature] (`#300 <https://github.com/schematics/schematics/pull/300>`_) increase domain length to 32
1.0.3 / 2015-03-07
==================
* [Feature] (`#284 <https://github.com/schematics/schematics/pull/284>`_) Add missing requirement for `six`
* [Feature] (`#283 <https://github.com/schematics/schematics/pull/283>`_) Update error msgs to print out invalid values in base.py
* [Feature] (`#281 <https://github.com/schematics/schematics/pull/281>`_) Update Model.__eq__
* [Feature] (`#267 <https://github.com/schematics/schematics/pull/267>`_) Type choices should be list or tuple
1.0.2 / 2015-02-12
==================
* [Bug] (`#280 <https://github.com/schematics/schematics/issues/280>`_) Fix the circular import issue.
1.0.1 / 2015-02-01
==================
* [Feature] (`#184 <https://github.com/schematics/schematics/issues/184>`_ / `03b2fd9 <https://github.com/schematics/schematics/commit/03b2fd97fb47c00e8d667cc8ea7254cc64d0f0a0>`_) Support for polymorphic model fields
* [Bug] (`#233 <https://github.com/schematics/schematics/pull/233>`_) Set field.owner_model recursively and honor ListType.field.serialize_when_none
* [Bug](`#252 <https://github.com/schematics/schematics/pull/252>`_) Fixed project URL
* [Feature] (`#259 <https://github.com/schematics/schematics/pull/259>`_) Give export loop to serializable when type has one
* [Feature] (`#262 <https://github.com/schematics/schematics/pull/262>`_) Make copies of inherited meta attributes when setting up a Model
* [Documentation] (`#276 <https://github.com/schematics/schematics/pull/276>`_) Improve the documentation of get_mock_object
1.0.0 / 2014-10-16
==================
* [Documentation] (`#239 <https://github.com/schematics/schematics/issues/239>`_) Fix typo with wording suggestion
* [Documentation] (`#244 <https://github.com/schematics/schematics/issues/244>`_) fix wrong reference in docs
* [Documentation] (`#246 <https://github.com/schematics/schematics/issues/246>`_) Using the correct function name in the docstring
* [Documentation] (`#245 <https://github.com/schematics/schematics/issues/245>`_) Making the docstring match actual parameter names
* [Feature] (`#241 <https://github.com/schematics/schematics/issues/241>`_) Py3k support
0.9.5 / 2014-07-19
==================
* [Feature] (`#191 <https://github.com/schematics/schematics/pull/191>`_) Updated import_data to avoid overwriting existing data. deserialize_mapping can now support partial and nested models.
* [Documentation] (`#192 <https://github.com/schematics/schematics/pull/192>`_) Document the creation of custom types
* [Feature] (`#193 <https://github.com/schematics/schematics/pull/193>`_) Add primitive types accepting values of any simple or compound primitive JSON type.
* [Bug] (`#194 <https://github.com/schematics/schematics/pull/194>`_) Change standard coerce_key function to unicode
* [Tests] (`#196 <https://github.com/schematics/schematics/pull/196>`_) Test fixes and cleanup
* [Feature] (`#197 <https://github.com/schematics/schematics/pull/197>`_) Giving context to serialization
* [Bug] (`#198 <https://github.com/schematics/schematics/pull/198>`_) Fixed typo in variable name in DateTimeType
* [Feature] (`#200 <https://github.com/schematics/schematics/pull/200>`_) Added the option to turn of strict conversion when creating a Model from a dict
* [Feature] (`#212 <https://github.com/schematics/schematics/pull/212>`_) Support exporting ModelType fields with subclassed model instances
* [Feature] (`#214 <https://github.com/schematics/schematics/pull/214>`_) Create mock objects using a class's fields as a template
* [Bug] (`#215 <https://github.com/schematics/schematics/pull/215>`_) PEP 8 FTW
* [Feature] (`#216 <https://github.com/schematics/schematics/pull/216>`_) Datastructures cleanup
* [Feature] (`#217 <https://github.com/schematics/schematics/pull/217>`_) Models cleanup pt 1
* [Feature] (`#218 <https://github.com/schematics/schematics/pull/218>`_) Models cleanup pt 2
* [Feature] (`#219 <https://github.com/schematics/schematics/pull/219>`_) Mongo cleanup
* [Feature] (`#220 <https://github.com/schematics/schematics/pull/220>`_) Temporal cleanup
* [Feature] (`#221 <https://github.com/schematics/schematics/pull/221>`_) Base cleanup
* [Feature] (`#224 <https://github.com/schematics/schematics/pull/224>`_) Exceptions cleanup
* [Feature] (`#225 <https://github.com/schematics/schematics/pull/225>`_) Validate cleanup
* [Feature] (`#226 <https://github.com/schematics/schematics/pull/226>`_) Serializable cleanup
* [Feature] (`#227 <https://github.com/schematics/schematics/pull/227>`_) Transforms cleanup
* [Feature] (`#228 <https://github.com/schematics/schematics/pull/228>`_) Compound cleanup
* [Feature] (`#229 <https://github.com/schematics/schematics/pull/229>`_) UUID cleanup
* [Feature] (`#231 <https://github.com/schematics/schematics/pull/231>`_) Booleans as numbers
0.9.4 / 2013-12-08
==================
* [Feature] (`#178 <https://github.com/schematics/schematics/pull/178>`_) Added deserialize_from flag to BaseType for alternate field names on import
* [Bug] (`#186 <https://github.com/schematics/schematics/pull/186>`_) Compoundtype support in ListTypes
* [Bug] (`#181 <https://github.com/schematics/schematics/pull/181>`_) Removed that stupid print statement!
* [Feature] (`#182 <https://github.com/schematics/schematics/pull/182>`_) Default roles system
* [Documentation] (`#190 <https://github.com/schematics/schematics/pull/190>`_) Typos
* [Bug] (`#177 <https://github.com/schematics/schematics/pull/177>`_) Removed `__iter__` from ModelMeta
* [Documentation] (`#188 <https://github.com/schematics/schematics/pull/188>`_) Typos
0.9.3 / 2013-10-20
==================
* [Documentation] More improvements
* [Feature] (`#147 <https://github.com/schematics/schematics/pull/147>`_) Complete conversion over to py.test
* [Bug] (`#176 <https://github.com/schematics/schematics/pull/176>`_) Fixed bug preventing clean override of options class
* [Bug] (`#174 <https://github.com/schematics/schematics/pull/174>`_) Python 2.6 support
0.9.2 / 2013-09-13
==================
* [Documentation] New History file!
* [Documentation] Major improvements to documentation
* [Feature] Renamed ``check_value`` to ``validate_range``
* [Feature] Changed ``serialize`` to ``to_native``
* [Bug] (`#155 <https://github.com/schematics/schematics/pull/155>`_) NumberType number range validation bugfix
|
schemv
|
/schemv-2.1.1.1.tar.gz/schemv-2.1.1.1/HISTORY.rst
|
HISTORY.rst
|
2.1.1 / 2021-08-17
==================
- Update error message for incorrect choices field
`#572 <https://github.com/schematics/schematics/pull/572>`__
(`begor <https://github.com/begor>`__)
- Avoid some deprecation warnings when using Python 3
`#576 <https://github.com/schematics/schematics/pull/576>`__
(`jesuslosada <https://github.com/jesuslosada>`__)
- Fix EnumType enums with value=0 not working with use_values=True
`#594 <https://github.com/schematics/schematics/pull/594>`__
(`nikhilgupta345 <https://github.com/nikhilgupta345>`__)
- Fix syntax warning over comparison of literals using is.
`#611 <https://github.com/schematics/schematics/pull/611>`__
(`tirkarthi <https://github.com/tirkarthi>`__)
- Add help text generation capability to Models
`#543 <https://github.com/schematics/schematics/pull/543>`__
(`MartinHowarth <https://github.com/MartinHowarth>`__)
- Update documentation
`#578 <https://github.com/schematics/schematics/pull/578>`__
(`BobDu <https://github.com/BobDu>`__)
`#604 <https://github.com/schematics/schematics/pull/604>`__
(`BryanChan777 <https://github.com/BryanChan777>`__)
`#605 <https://github.com/schematics/schematics/pull/605>`__
(`timgates42 <https://github.com/timgates42>`__)
`#608 <https://github.com/schematics/schematics/pull/608>`__
(`dasubermanmind <https://github.com/dasubermanmind>`__)
- Add test coverage for model validation inside Dict/List
`#588 <https://github.com/schematics/schematics/pull/588>`__
(`borgstrom <https://github.com/borgstrom>`__)
- Added German translation
`#614 <https://github.com/schematics/schematics/pull/614>`__
(`hkage <https://github.com/hkage>`__)
2.1.0 / 2018-06-25
==================
**[BREAKING CHANGE]**
- Drop Python 2.6 support
`#517 <https://github.com/schematics/schematics/pull/517>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
Other changes:
- Add TimedeltaType
`#540 <https://github.com/schematics/schematics/pull/540>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Allow to create Model fields dynamically
`#512 <https://github.com/schematics/schematics/pull/512>`__
(`lkraider <https://github.com/lkraider>`__)
- Allow ModelOptions to have extra parameters
`#449 <https://github.com/schematics/schematics/pull/449>`__
(`rmb938 <https://github.com/rmb938>`__)
`#506 <https://github.com/schematics/schematics/pull/506>`__
(`ekampf <https://github.com/ekampf>`__)
- Accept callables as serialize roles
`#508 <https://github.com/schematics/schematics/pull/508>`__
(`lkraider <https://github.com/lkraider>`__)
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Simplify PolyModelType.find_model for readability
`#537 <https://github.com/schematics/schematics/pull/537>`__
(`kstrauser <https://github.com/kstrauser>`__)
- Enable PolyModelType recursive validation
`#535 <https://github.com/schematics/schematics/pull/535>`__
(`javiertejero <https://github.com/javiertejero>`__)
- Documentation fixes
`#509 <https://github.com/schematics/schematics/pull/509>`__
(`Tuoris <https://github.com/Tuoris>`__)
`#514 <https://github.com/schematics/schematics/pull/514>`__
(`tommyzli <https://github.com/tommyzli>`__)
`#518 <https://github.com/schematics/schematics/pull/518>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#546 <https://github.com/schematics/schematics/pull/546>`__
(`harveyslash <https://github.com/harveyslash>`__)
- Fix Model.init validation when partial is True
`#531 <https://github.com/schematics/schematics/issues/531>`__
(`lkraider <https://github.com/lkraider>`__)
- Minor number types refactor and mocking fixes
`#519 <https://github.com/schematics/schematics/pull/519>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
`#520 <https://github.com/schematics/schematics/pull/520>`__
(`rooterkyberian <https://github.com/rooterkyberian>`__)
- Add ability to import models as strings
`#496 <https://github.com/schematics/schematics/pull/496>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
- Add EnumType
`#504 <https://github.com/schematics/schematics/pull/504>`__
(`ekamil <https://github.com/ekamil>`__)
- Dynamic models: Possible memory issues because of _subclasses
`#502 <https://github.com/schematics/schematics/pull/502>`__
(`mjrk <https://github.com/mjrk>`__)
- Add type hints to constructors of field type classes
`#488 <https://github.com/schematics/schematics/pull/488>`__
(`KonishchevDmitry <https://github.com/KonishchevDmitry>`__)
- Regression: Do not call field validator if field has not been set
`#499 <https://github.com/schematics/schematics/pull/499>`__
(`cmonfort <https://github.com/cmonfort>`__)
- Add possibility to translate strings and add initial pt_BR translations
`#495 <https://github.com/schematics/schematics/pull/495>`__
(`jaysonsantos <https://github.com/jaysonsantos>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.1 / 2017-05-30
==================
- Support for raising DataError inside custom validate_fieldname methods.
`#441 <https://github.com/schematics/schematics/pull/441>`__
(`alexhayes <https://github.com/alexhayes>`__)
- Add specialized SchematicsDeprecationWarning.
(`lkraider <https://github.com/lkraider>`__)
- DateTimeType to_native method should handle type errors gracefully.
`#491 <https://github.com/schematics/schematics/pull/491>`__
(`e271828- <https://github.com/e271828->`__)
- Allow fields names to override the mapping-interface methods.
`#489 <https://github.com/schematics/schematics/pull/489>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
(`lkraider <https://github.com/lkraider>`__)
2.0.0 / 2017-05-22
==================
**[BREAKING CHANGE]**
Version 2.0 introduces many API changes, and it is not fully backwards-compatible with 1.x code.
`Full Changelog <https://github.com/schematics/schematics/compare/v1.1.2...v2.0.0>`_
- Add syntax highlighting to README examples
`#486 <https://github.com/schematics/schematics/pull/486>`__
(`gabisurita <https://github.com/gabisurita>`__)
- Encode Unsafe data state in Model
`#484 <https://github.com/schematics/schematics/pull/484>`__
(`lkraider <https://github.com/lkraider>`__)
- Add MACAddressType
`#482 <https://github.com/schematics/schematics/pull/482>`__
(`aleksej-paschenko <https://github.com/aleksej-paschenko>`__)
2.0.0.b1 / 2017-04-06
=====================
- Enhancing and addressing some issues around exceptions:
`#477 <https://github.com/schematics/schematics/pull/477>`__
(`toumorokoshi <https://github.com/toumorokoshi>`__)
- Allow primitive and native types to be inspected
`#431 <https://github.com/schematics/schematics/pull/431>`__
(`chadrik <https://github.com/chadrik>`__)
- Atoms iterator performance improvement
`#476 <https://github.com/schematics/schematics/pull/476>`__
(`vovanbo <https://github.com/vovanbo>`__)
- Fixes 453: Recursive import\_loop with ListType
`#475 <https://github.com/schematics/schematics/pull/475>`__
(`lkraider <https://github.com/lkraider>`__)
- Schema API
`#466 <https://github.com/schematics/schematics/pull/466>`__
(`lkraider <https://github.com/lkraider>`__)
- Tweak code example to avoid sql injection
`#462 <https://github.com/schematics/schematics/pull/462>`__
(`Ian-Foote <https://github.com/Ian-Foote>`__)
- Convert readthedocs links for their .org -> .io migration for hosted
projects `#454 <https://github.com/schematics/schematics/pull/454>`__
(`adamchainz <https://github.com/adamchainz>`__)
- Support all non-string Iterables as choices (dev branch)
`#436 <https://github.com/schematics/schematics/pull/436>`__
(`di <https://github.com/di>`__)
- When testing if a values is None or Undefined, use 'is'.
`#425 <https://github.com/schematics/schematics/pull/425>`__
(`chadrik <https://github.com/chadrik>`__)
2.0.0a1 / 2016-05-03
====================
- Restore v1 to\_native behavior; simplify converter code
`#412 <https://github.com/schematics/schematics/pull/412>`__
(`bintoro <https://github.com/bintoro>`__)
- Change conversion rules for booleans
`#407 <https://github.com/schematics/schematics/pull/407>`__
(`bintoro <https://github.com/bintoro>`__)
- Test for Model.\_\_init\_\_ context passing to types
`#399 <https://github.com/schematics/schematics/pull/399>`__
(`sheilatron <https://github.com/sheilatron>`__)
- Code normalization for Python 3 + general cleanup
`#391 <https://github.com/schematics/schematics/pull/391>`__
(`bintoro <https://github.com/bintoro>`__)
- Add support for arbitrary field metadata.
`#390 <https://github.com/schematics/schematics/pull/390>`__
(`chadrik <https://github.com/chadrik>`__)
- Introduce MixedType
`#380 <https://github.com/schematics/schematics/pull/380>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev2 / 2016-02-06
=======================
- Type maintenance
`#383 <https://github.com/schematics/schematics/pull/383>`__
(`bintoro <https://github.com/bintoro>`__)
2.0.0.dev1 / 2016-02-01
=======================
- Performance optimizations
`#378 <https://github.com/schematics/schematics/pull/378>`__
(`bintoro <https://github.com/bintoro>`__)
- Validation refactoring + exception redesign
`#374 <https://github.com/schematics/schematics/pull/374>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix typo: serilaizataion --> serialization
`#373 <https://github.com/schematics/schematics/pull/373>`__
(`jeffwidman <https://github.com/jeffwidman>`__)
- Add support for undefined values
`#372 <https://github.com/schematics/schematics/pull/372>`__
(`bintoro <https://github.com/bintoro>`__)
- Serializable improvements
`#371 <https://github.com/schematics/schematics/pull/371>`__
(`bintoro <https://github.com/bintoro>`__)
- Unify import/export interface across all types
`#368 <https://github.com/schematics/schematics/pull/368>`__
(`bintoro <https://github.com/bintoro>`__)
- Correctly decode bytestrings in Python 3
`#365 <https://github.com/schematics/schematics/pull/365>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix NumberType.to\_native()
`#364 <https://github.com/schematics/schematics/pull/364>`__
(`bintoro <https://github.com/bintoro>`__)
- Make sure field.validate() uses a native type
`#363 <https://github.com/schematics/schematics/pull/363>`__
(`bintoro <https://github.com/bintoro>`__)
- Don't validate ListType items twice
`#362 <https://github.com/schematics/schematics/pull/362>`__
(`bintoro <https://github.com/bintoro>`__)
- Collect field validators as bound methods
`#361 <https://github.com/schematics/schematics/pull/361>`__
(`bintoro <https://github.com/bintoro>`__)
- Propagate environment during recursive import/export/validation
`#359 <https://github.com/schematics/schematics/pull/359>`__
(`bintoro <https://github.com/bintoro>`__)
- DateTimeType & TimestampType major rewrite
`#358 <https://github.com/schematics/schematics/pull/358>`__
(`bintoro <https://github.com/bintoro>`__)
- Always export empty compound objects as {} / []
`#351 <https://github.com/schematics/schematics/pull/351>`__
(`bintoro <https://github.com/bintoro>`__)
- export\_loop cleanup
`#350 <https://github.com/schematics/schematics/pull/350>`__
(`bintoro <https://github.com/bintoro>`__)
- Fix FieldDescriptor.\_\_delete\_\_ to not touch model
`#349 <https://github.com/schematics/schematics/pull/349>`__
(`bintoro <https://github.com/bintoro>`__)
- Add validation method for latitude and longitude ranges in
GeoPointType
`#347 <https://github.com/schematics/schematics/pull/347>`__
(`wraziens <https://github.com/wraziens>`__)
- Fix longitude values for GeoPointType mock and add tests
`#344 <https://github.com/schematics/schematics/pull/344>`__
(`wraziens <https://github.com/wraziens>`__)
- Add support for self-referential ModelType fields
`#335 <https://github.com/schematics/schematics/pull/335>`__
(`bintoro <https://github.com/bintoro>`__)
- avoid unnecessary code path through try/except
`#327 <https://github.com/schematics/schematics/pull/327>`__
(`scavpy <https://github.com/scavpy>`__)
- Get mock object for ModelType and ListType
`#306 <https://github.com/schematics/schematics/pull/306>`__
(`kaiix <https://github.com/kaiix>`__)
1.1.3 / 2017-06-27
==================
* [Maintenance] (`#501 <https://github.com/schematics/schematics/issues/501>`_) Dynamic models: Possible memory issues because of _subclasses
1.1.2 / 2017-03-27
==================
* [Bug] (`#478 <https://github.com/schematics/schematics/pull/478>`_) Fix dangerous performance issue with ModelConversionError in nested models
1.1.1 / 2015-11-03
==================
* [Bug] (`befa202 <https://github.com/schematics/schematics/commit/befa202c3b3202aca89fb7ef985bdca06f9da37c>`_) Fix Unicode issue with DecimalType
* [Documentation] (`41157a1 <https://github.com/schematics/schematics/commit/41157a13896bd32a337c5503c04c5e9cc30ba4c7>`_) Documentation overhaul
* [Bug] (`860d717 <https://github.com/schematics/schematics/commit/860d71778421981f284c0612aec665ebf0cfcba2>`_) Fix import that was negatively affecting performance
* [Feature] (`93b554f <https://github.com/schematics/schematics/commit/93b554fd6a4e7b38133c4da5592b1843101792f0>`_) Add DataObject to datastructures.py
* [Bug] (`#236 <https://github.com/schematics/schematics/pull/236>`_) Set `None` on a field that's a compound type should honour that semantics
* [Maintenance] (`#348 <https://github.com/schematics/schematics/pull/348>`_) Update requirements
* [Maintenance] (`#346 <https://github.com/schematics/schematics/pull/346>`_) Combining Requirements
* [Maintenance] (`#342 <https://github.com/schematics/schematics/pull/342>`_) Remove to_primitive() method from compound types
* [Bug] (`#339 <https://github.com/schematics/schematics/pull/339>`_) Basic number validation
* [Bug] (`#336 <https://github.com/schematics/schematics/pull/336>`_) Don't evaluate serializable when accessed through class
* [Bug] (`#321 <https://github.com/schematics/schematics/pull/321>`_) Do not compile regex
* [Maintenance] (`#319 <https://github.com/schematics/schematics/pull/319>`_) Remove mock from install_requires
1.1.0 / 2015-07-12
==================
* [Feature] (`#303 <https://github.com/schematics/schematics/pull/303>`_) fix ListType, validate_items adds to errors list just field name without...
* [Feature] (`#304 <https://github.com/schematics/schematics/pull/304>`_) Include Partial Data when Raising ModelConversionError
* [Feature] (`#305 <https://github.com/schematics/schematics/pull/305>`_) Updated domain verifications to fit to RFC/working standards
* [Feature] (`#308 <https://github.com/schematics/schematics/pull/308>`_) Grennady ordered validation
* [Feature] (`#309 <https://github.com/schematics/schematics/pull/309>`_) improves date_time_type error message for custom formats
* [Feature] (`#310 <https://github.com/schematics/schematics/pull/310>`_) accept optional 'Z' suffix for UTC date_time_type format
* [Feature] (`#311 <https://github.com/schematics/schematics/pull/311>`_) Remove commented lines from models.py
* [Feature] (`#230 <https://github.com/schematics/schematics/pull/230>`_) Message normalization
1.0.4 / 2015-04-13
==================
* [Example] (`#286 <https://github.com/schematics/schematics/pull/286>`_) Add schematics usage with Django
* [Feature] (`#292 <https://github.com/schematics/schematics/pull/292>`_) increase domain length to 10 for .holiday, .vacations
* [Feature] (`#297 <https://github.com/schematics/schematics/pull/297>`_) Support for fields order in serialized format
* [Feature] (`#300 <https://github.com/schematics/schematics/pull/300>`_) increase domain length to 32
1.0.3 / 2015-03-07
==================
* [Feature] (`#284 <https://github.com/schematics/schematics/pull/284>`_) Add missing requirement for `six`
* [Feature] (`#283 <https://github.com/schematics/schematics/pull/283>`_) Update error msgs to print out invalid values in base.py
* [Feature] (`#281 <https://github.com/schematics/schematics/pull/281>`_) Update Model.__eq__
* [Feature] (`#267 <https://github.com/schematics/schematics/pull/267>`_) Type choices should be list or tuple
1.0.2 / 2015-02-12
==================
* [Bug] (`#280 <https://github.com/schematics/schematics/issues/280>`_) Fix the circular import issue.
1.0.1 / 2015-02-01
==================
* [Feature] (`#184 <https://github.com/schematics/schematics/issues/184>`_ / `03b2fd9 <https://github.com/schematics/schematics/commit/03b2fd97fb47c00e8d667cc8ea7254cc64d0f0a0>`_) Support for polymorphic model fields
* [Bug] (`#233 <https://github.com/schematics/schematics/pull/233>`_) Set field.owner_model recursively and honor ListType.field.serialize_when_none
* [Bug](`#252 <https://github.com/schematics/schematics/pull/252>`_) Fixed project URL
* [Feature] (`#259 <https://github.com/schematics/schematics/pull/259>`_) Give export loop to serializable when type has one
* [Feature] (`#262 <https://github.com/schematics/schematics/pull/262>`_) Make copies of inherited meta attributes when setting up a Model
* [Documentation] (`#276 <https://github.com/schematics/schematics/pull/276>`_) Improve the documentation of get_mock_object
1.0.0 / 2014-10-16
==================
* [Documentation] (`#239 <https://github.com/schematics/schematics/issues/239>`_) Fix typo with wording suggestion
* [Documentation] (`#244 <https://github.com/schematics/schematics/issues/244>`_) fix wrong reference in docs
* [Documentation] (`#246 <https://github.com/schematics/schematics/issues/246>`_) Using the correct function name in the docstring
* [Documentation] (`#245 <https://github.com/schematics/schematics/issues/245>`_) Making the docstring match actual parameter names
* [Feature] (`#241 <https://github.com/schematics/schematics/issues/241>`_) Py3k support
0.9.5 / 2014-07-19
==================
* [Feature] (`#191 <https://github.com/schematics/schematics/pull/191>`_) Updated import_data to avoid overwriting existing data. deserialize_mapping can now support partial and nested models.
* [Documentation] (`#192 <https://github.com/schematics/schematics/pull/192>`_) Document the creation of custom types
* [Feature] (`#193 <https://github.com/schematics/schematics/pull/193>`_) Add primitive types accepting values of any simple or compound primitive JSON type.
* [Bug] (`#194 <https://github.com/schematics/schematics/pull/194>`_) Change standard coerce_key function to unicode
* [Tests] (`#196 <https://github.com/schematics/schematics/pull/196>`_) Test fixes and cleanup
* [Feature] (`#197 <https://github.com/schematics/schematics/pull/197>`_) Giving context to serialization
* [Bug] (`#198 <https://github.com/schematics/schematics/pull/198>`_) Fixed typo in variable name in DateTimeType
* [Feature] (`#200 <https://github.com/schematics/schematics/pull/200>`_) Added the option to turn of strict conversion when creating a Model from a dict
* [Feature] (`#212 <https://github.com/schematics/schematics/pull/212>`_) Support exporting ModelType fields with subclassed model instances
* [Feature] (`#214 <https://github.com/schematics/schematics/pull/214>`_) Create mock objects using a class's fields as a template
* [Bug] (`#215 <https://github.com/schematics/schematics/pull/215>`_) PEP 8 FTW
* [Feature] (`#216 <https://github.com/schematics/schematics/pull/216>`_) Datastructures cleanup
* [Feature] (`#217 <https://github.com/schematics/schematics/pull/217>`_) Models cleanup pt 1
* [Feature] (`#218 <https://github.com/schematics/schematics/pull/218>`_) Models cleanup pt 2
* [Feature] (`#219 <https://github.com/schematics/schematics/pull/219>`_) Mongo cleanup
* [Feature] (`#220 <https://github.com/schematics/schematics/pull/220>`_) Temporal cleanup
* [Feature] (`#221 <https://github.com/schematics/schematics/pull/221>`_) Base cleanup
* [Feature] (`#224 <https://github.com/schematics/schematics/pull/224>`_) Exceptions cleanup
* [Feature] (`#225 <https://github.com/schematics/schematics/pull/225>`_) Validate cleanup
* [Feature] (`#226 <https://github.com/schematics/schematics/pull/226>`_) Serializable cleanup
* [Feature] (`#227 <https://github.com/schematics/schematics/pull/227>`_) Transforms cleanup
* [Feature] (`#228 <https://github.com/schematics/schematics/pull/228>`_) Compound cleanup
* [Feature] (`#229 <https://github.com/schematics/schematics/pull/229>`_) UUID cleanup
* [Feature] (`#231 <https://github.com/schematics/schematics/pull/231>`_) Booleans as numbers
0.9.4 / 2013-12-08
==================
* [Feature] (`#178 <https://github.com/schematics/schematics/pull/178>`_) Added deserialize_from flag to BaseType for alternate field names on import
* [Bug] (`#186 <https://github.com/schematics/schematics/pull/186>`_) Compoundtype support in ListTypes
* [Bug] (`#181 <https://github.com/schematics/schematics/pull/181>`_) Removed that stupid print statement!
* [Feature] (`#182 <https://github.com/schematics/schematics/pull/182>`_) Default roles system
* [Documentation] (`#190 <https://github.com/schematics/schematics/pull/190>`_) Typos
* [Bug] (`#177 <https://github.com/schematics/schematics/pull/177>`_) Removed `__iter__` from ModelMeta
* [Documentation] (`#188 <https://github.com/schematics/schematics/pull/188>`_) Typos
0.9.3 / 2013-10-20
==================
* [Documentation] More improvements
* [Feature] (`#147 <https://github.com/schematics/schematics/pull/147>`_) Complete conversion over to py.test
* [Bug] (`#176 <https://github.com/schematics/schematics/pull/176>`_) Fixed bug preventing clean override of options class
* [Bug] (`#174 <https://github.com/schematics/schematics/pull/174>`_) Python 2.6 support
0.9.2 / 2013-09-13
==================
* [Documentation] New History file!
* [Documentation] Major improvements to documentation
* [Feature] Renamed ``check_value`` to ``validate_range``
* [Feature] Changed ``serialize`` to ``to_native``
* [Bug] (`#155 <https://github.com/schematics/schematics/pull/155>`_) NumberType number range validation bugfix
| 0.787278 | 0.657799 |
==========
pip install schemv
==========
.. rubric:: Python Data Structures for Humans™.
.. image:: https://travis-ci.org/schematics/schematics.svg?branch=master
:target: https://travis-ci.org/schematics/schematics
:alt: Build Status
.. image:: https://coveralls.io/repos/github/schematics/schematics/badge.svg?branch=master
:target: https://coveralls.io/github/schematics/schematics?branch=master
:alt: Coverage
About
=====
**Project documentation:** https://schematics.readthedocs.io/en/latest/
Schematics is a Python library to combine types into structures, validate them, and transform the shapes of your data based on simple descriptions.
The internals are similar to ORM type systems, but there is no database layer in Schematics. Instead, we believe that building a database layer is easily made when Schematics handles everything except for writing the query.
Schematics can be used for tasks where having a database involved is unusual.
Some common use cases:
+ Design and document specific `data structures <https://schematics.readthedocs.io/en/latest/usage/models.html>`_
+ `Convert structures <https://schematics.readthedocs.io/en/latest/usage/exporting.html#converting-data>`_ to and from different formats such as JSON or MsgPack
+ `Validate <https://schematics.readthedocs.io/en/latest/usage/validation.html>`_ API inputs
+ `Remove fields based on access rights <https://schematics.readthedocs.io/en/latest/usage/exporting.html>`_ of some data's recipient
+ Define message formats for communications protocols, like an RPC
+ Custom `persistence layers <https://schematics.readthedocs.io/en/latest/usage/models.html#model-configuration>`_
Example
=======
This is a simple Model.
.. code:: python
>>> from schemv.models import Model
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
.. code:: python
>>> import json
>>> json.dumps(person.to_primitive())
{"name": "Joe Strummer", "website": "http://soundcloud.com/joestrummer"}
Let's try validating without a name value, since it's required.
.. code:: python
>>> person = Person()
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "schematics/models.py", line 231, in validate
raise DataError(e.messages)
schematics.exceptions.DataError: {'name': ['This field is required.']}
Add the field and validation passes.
.. code:: python
>>> person = Person()
>>> person.name = 'Amon Tobin'
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
>>>
.. _coverage:
Testing & Coverage support
==========================
Run coverage and check the missing statements. ::
$ coverage run --source schematics -m py.test && coverage report
|
schemv
|
/schemv-2.1.1.1.tar.gz/schemv-2.1.1.1/README.rst
|
README.rst
|
==========
pip install schemv
==========
.. rubric:: Python Data Structures for Humans™.
.. image:: https://travis-ci.org/schematics/schematics.svg?branch=master
:target: https://travis-ci.org/schematics/schematics
:alt: Build Status
.. image:: https://coveralls.io/repos/github/schematics/schematics/badge.svg?branch=master
:target: https://coveralls.io/github/schematics/schematics?branch=master
:alt: Coverage
About
=====
**Project documentation:** https://schematics.readthedocs.io/en/latest/
Schematics is a Python library to combine types into structures, validate them, and transform the shapes of your data based on simple descriptions.
The internals are similar to ORM type systems, but there is no database layer in Schematics. Instead, we believe that building a database layer is easily made when Schematics handles everything except for writing the query.
Schematics can be used for tasks where having a database involved is unusual.
Some common use cases:
+ Design and document specific `data structures <https://schematics.readthedocs.io/en/latest/usage/models.html>`_
+ `Convert structures <https://schematics.readthedocs.io/en/latest/usage/exporting.html#converting-data>`_ to and from different formats such as JSON or MsgPack
+ `Validate <https://schematics.readthedocs.io/en/latest/usage/validation.html>`_ API inputs
+ `Remove fields based on access rights <https://schematics.readthedocs.io/en/latest/usage/exporting.html>`_ of some data's recipient
+ Define message formats for communications protocols, like an RPC
+ Custom `persistence layers <https://schematics.readthedocs.io/en/latest/usage/models.html#model-configuration>`_
Example
=======
This is a simple Model.
.. code:: python
>>> from schemv.models import Model
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
>>> from schematics.types import StringType, URLType
>>> class Person(Model):
... name = StringType(required=True)
... website = URLType()
...
>>> person = Person({'name': u'Joe Strummer',
... 'website': 'http://soundcloud.com/joestrummer'})
>>> person.name
u'Joe Strummer'
Serializing the data to JSON.
.. code:: python
>>> import json
>>> json.dumps(person.to_primitive())
{"name": "Joe Strummer", "website": "http://soundcloud.com/joestrummer"}
Let's try validating without a name value, since it's required.
.. code:: python
>>> person = Person()
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "schematics/models.py", line 231, in validate
raise DataError(e.messages)
schematics.exceptions.DataError: {'name': ['This field is required.']}
Add the field and validation passes.
.. code:: python
>>> person = Person()
>>> person.name = 'Amon Tobin'
>>> person.website = 'http://www.amontobin.com/'
>>> person.validate()
>>>
.. _coverage:
Testing & Coverage support
==========================
Run coverage and check the missing statements. ::
$ coverage run --source schematics -m py.test && coverage report
| 0.921957 | 0.626281 |
# Schengulator
[](https://schengulator.readthedocs.io/en/latest/?badge=latest) [](https://badge.fury.io/py/schengulator)
Schengulator is a tool to calculate how many days an individual has been in Schengen countries out of a specified 180-day period.
## The Schengen Visa Rule
The schengulator determines the number of days spent and remaining based on the 90/180-day Schengen Visa Rule, where an individual can stay in Schengen countries for 90 days out of an 180 day time period. The 180-day window is defined as:
*"The 180-day period keeps rolling. Therefore, anytime you wish to enter the Schengen, you just have to count backwards the last 180 days, and see if you have been present in the Schengen for more than 90 days throughout that period"* (as stated [here](https://www.schengenvisainfo.com/visa-calculator))
Therefore, schengulator calculates the days spent in the Schengen area based on the 180 days prior to a user-defined date.
For more on the Schengen Visa Rule, see these links:
+ [Schengen visa info](https://www.schengenvisainfo.com)
+ [The 90/180-day rule made easy](https://newlandchase.com/the-schengen-areas-90-180-day-rule-made-easy/)
+ [UK Government on visa permits in Europe](https://www.gov.uk/guidance/check-if-you-need-a-visa-or-permit-for-europe)
+ [The Schengen rule: here's how it works](https://www.frenchentree.com/brexit/eu-90-180-day-rule-heres-how-it-works/)
There are many Schengen stay calculators available online or as apps. The purpose of schengulator is to create a workflow that is **transparent** (i.e. you can see the workings) and **non-repetitive** (i.e. you don't have to log each and every one of your trips to the Schengen area every time you need to use the tool).
## Quickstart
To get started, install schengulator using pip.
```python
pip install schengulator
```
Schengulator's only dependencies are **datetime** and **csv** for handling date objects and loading from csv files, respectively. These are usually in-built packages to Python distributions, and therefore there should not be any compatibility issues.
Check that the package works by opening a python console and importing it.
```python
python3
import schengulator
```
There are a number of examples in the scripts provided in the [examples](https://github.com/PennyHow/schengulator/tree/main/examples) directory of the [schengulator Github repository](https://github.com/PennyHow/schengulator) to test the installation and see how it works.
```python
from schengulator.schengulator import SchengenStay, /
checkStay, checkDaysLeft, staysFromCSV
# Example 1. Check Schengen stays from specific date
# using SchengenStay obj
# Initialise Schengen evaluation from 01/05/2022
ss = SchengenStay('2022-05-01')
# Add all stays
ss.addStay('2021-07-01', '2021-07-15') # Greece
ss.addStay('2021-09-03', '2021-09-08') # Netherlands
ss.addStay('2021-09-20', '2021-09-25') # Belgium
ss.addStay('2021-12-20', '2022-01-03') # Belgium
ss.addStay('2022-04-18', '2022-05-01') # Italy
# Check number of days spent in Schengen on 01/05/2022
flag = ss.checkDays()
if flag==True:
print('All okay!')
# Example 2. Check Schengen stays for all dates in
# proposed future stay
# Create list of all stays
trips = [['2021-07-01','2021-07-15'], # Greece
['2021-09-03', '2021-09-08'], # Netherlands
['2021-09-20', '2021-09-25'], # Belgium
['2021-12-20', '2022-01-03'], # Belgium
['2022-04-18', '2022-05-01']] # Italy
# Check if new stay is within Schengen 90-day limits
checkStay(['2022-04-18', '2022-05-01'], trips[:-1])
# See how many days left in Schengen after proposed trip
checkDaysLeft(trips)
# Example 3. Check Schengen stays from CSV file
# Import stays from csv file
infile = 'examples/example_stays.csv'
csv_trips = staysFromCSV(infile)
# Check if new trip is within Schengen 90-day limits
new_trip = ['2022-01-05', '2022-01-20']
checkStay(new_trip, csv_trips)
# Check how many days left in Schengen after new trip
csv_trips.append(new_trip)
checkDaysLeft(csv_trips, d=new_trip[1])
```
## Acknowledgements
This tool was inspired by these related python repositories:
+ [schengen](https://github.com/weddige/schengen)
+ [schengencalc](https://github.com/nuno-filipe/schengencalc)
|
schengulator
|
/schengulator-0.0.3.tar.gz/schengulator-0.0.3/README.md
|
README.md
|
pip install schengulator
python3
import schengulator
from schengulator.schengulator import SchengenStay, /
checkStay, checkDaysLeft, staysFromCSV
# Example 1. Check Schengen stays from specific date
# using SchengenStay obj
# Initialise Schengen evaluation from 01/05/2022
ss = SchengenStay('2022-05-01')
# Add all stays
ss.addStay('2021-07-01', '2021-07-15') # Greece
ss.addStay('2021-09-03', '2021-09-08') # Netherlands
ss.addStay('2021-09-20', '2021-09-25') # Belgium
ss.addStay('2021-12-20', '2022-01-03') # Belgium
ss.addStay('2022-04-18', '2022-05-01') # Italy
# Check number of days spent in Schengen on 01/05/2022
flag = ss.checkDays()
if flag==True:
print('All okay!')
# Example 2. Check Schengen stays for all dates in
# proposed future stay
# Create list of all stays
trips = [['2021-07-01','2021-07-15'], # Greece
['2021-09-03', '2021-09-08'], # Netherlands
['2021-09-20', '2021-09-25'], # Belgium
['2021-12-20', '2022-01-03'], # Belgium
['2022-04-18', '2022-05-01']] # Italy
# Check if new stay is within Schengen 90-day limits
checkStay(['2022-04-18', '2022-05-01'], trips[:-1])
# See how many days left in Schengen after proposed trip
checkDaysLeft(trips)
# Example 3. Check Schengen stays from CSV file
# Import stays from csv file
infile = 'examples/example_stays.csv'
csv_trips = staysFromCSV(infile)
# Check if new trip is within Schengen 90-day limits
new_trip = ['2022-01-05', '2022-01-20']
checkStay(new_trip, csv_trips)
# Check how many days left in Schengen after new trip
csv_trips.append(new_trip)
checkDaysLeft(csv_trips, d=new_trip[1])
| 0.59796 | 0.975946 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.