### Install pyknotid Source: https://pyknotid.readthedocs.io/en/latest/sources/overview.html Install the pyknotid package using pip. Ensure cython is installed if you want to use the optimized cython modules. ```bash $ pip install pyknotid ``` -------------------------------- ### Database Connection Setup Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/catalogue/identify.html Sets up the database connection method. It checks for an existing connection or establishes a new one. ```python from . import database as db from pyknotid.catalogue.database import Knot from pyknotid.catalogue import converters if hasattr(db.db, 'get_conn'): connection_method = db.db.get_conn else: connection_method = db.db.connection connection_method() ``` -------------------------------- ### Peewee SelectBase Query Execution and Fetching Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Provides methods for executing queries and fetching results, including peeking at the first row, getting the first N rows, retrieving a single scalar value, counting rows, checking for existence, and getting a single row. ```python class SelectBase(_HashableSource, Source, SelectQuery): def _get_hash(self): return hash((self.__class__, self._alias or id(self))) def _execute(self, database): if self._cursor_wrapper is None: cursor = database.execute(self) self._cursor_wrapper = self._get_cursor_wrapper(cursor) return self._cursor_wrapper @database_required def peek(self, database, n=1): rows = self.execute(database)[:n] if rows: return rows[0] if n == 1 else rows @database_required def first(self, database, n=1): if self._limit != n: self._limit = n self._cursor_wrapper = None return self.peek(database, n=n) @database_required def scalar(self, database, as_tuple=False): row = self.tuples().peek(database) return row[0] if row and not as_tuple else row @database_required def count(self, database, clear_limit=False): clone = self.order_by().alias('_wrapped') if clear_limit: clone._limit = clone._offset = None try: if clone._having is None and clone._windows is None and \ clone._distinct is None and clone._simple_distinct is not True: clone = clone.select(SQL('1')) except AttributeError: pass return Select([clone], [fn.COUNT(SQL('1'))]).scalar(database) @database_required def exists(self, database): clone = self.columns(SQL('1')) clone._limit = 1 clone._offset = None return bool(clone.scalar()) @database_required def get(self, database): self._cursor_wrapper = None try: return self.execute(database)[0] except IndexError: pass ``` -------------------------------- ### Create Example Knots and Links Source: https://pyknotid.readthedocs.io/en/latest/sources/overview.html Generate example knotted space curves using functions like `torus_knot`, `torus_link`, and `figure_eight`. This snippet shows how to create different types of knots and links and perform basic checks. ```python from pyknotid.make import torus_knot, torus_link, figure_eight k = torus_knot(p=5, q=2) k.identify() # [] from pyknotid.make import torus_link l = torus_link(p=2, q=8) # a 2-component link l.linking_number() # 8 from pyknotid.make import figure_eight k = figure_eight() k.determinant() # 5 ``` -------------------------------- ### Establish MySQL Database Connection Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Establishes a connection to the MySQL database using the installed driver. Raises an error if the MySQL driver is not available. ```python def _connect(self): if mysql is None: raise ImproperlyConfigured('MySQL driver not installed!') return mysql.connect(db=self.database, **self.connect_params) ``` -------------------------------- ### Get Model Instance by Primary Key Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves a single instance of the model using its primary key. This is a shortcut for `get` when you know the primary key value. ```python @classmethod def get_by_id(cls, pk): return cls.get(cls._meta.primary_key == pk) ``` -------------------------------- ### Get Database Download Directory Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/catalogue/getdb.html Returns the directory where the knots database will be downloaded. This path is determined using the appdirs library. ```python from pyknotid.catalogue.getdb import download_target_dir dir = download_target_dir() print(f'Database will be downloaded to: {dir}') ``` -------------------------------- ### VisPy Canvas Setup for Mesh Rendering Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/visualise.html Configures and displays a mesh on a VisPy canvas. This snippet sets up the camera and adds the mesh to the scene for interactive viewing. ```python from vispy.scene import TurntableCamera, Mesh # Assuming 'mesh' is a VisPy Mesh object and 'vispy_canvas' is an initialized canvas # from pyknotid.visualise.vispy_utils import ensure_vispy_canvas, clear_vispy_canvas, vispy_canvas # Placeholder for mesh and canvas initialization if not in context: # vertices = np.random.rand(10, 3) # indices = [[0, 1, 2], [0, 2, 3]] # mesh = Mesh(vertices, indices) # ensure_vispy_canvas() # clear_vispy_canvas() vispy_canvas.view.camera = TurntableCamera(fov=0, elevation=90.) vispy_canvas.view.add(mesh) vispy_canvas.show() ``` -------------------------------- ### Get or Create Model Instance Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Attempts to retrieve a model instance based on the provided keyword arguments. If found, it returns the instance and `False`. If not found, it creates a new instance using the provided arguments and optional defaults, saves it, and returns the new instance and `True`. Handles potential `IntegrityError` during creation by retrying retrieval. ```python @classmethod def get_or_create(cls, **kwargs): defaults = kwargs.pop('defaults', {}) query = cls.select() for field, value in kwargs.items(): query = query.where(getattr(cls, field) == value) try: return query.get(), False except cls.DoesNotExist: try: if defaults: kwargs.update(defaults) with cls._meta.database.atomic(): return cls.create(**kwargs), True except IntegrityError as exc: try: return query.get(), False except cls.DoesNotExist: raise exc ``` -------------------------------- ### Get Peewee Tables Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Placeholder method to retrieve a list of table names. Raises NotImplementedError if not implemented. ```python def get_tables(self, schema=None): raise NotImplementedError ``` -------------------------------- ### Get Peewee SQL Context Options Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the current context options for generating SQL, including field types, operations, and quoting settings. ```python def get_context_options(self): return { 'field_types': self._field_types, 'operations': self._operations, 'param': self.param, 'quote': self.quote, 'compound_select_parentheses': self.compound_select_parentheses, 'conflict_statement': self.conflict_statement, 'conflict_update': self.conflict_update, 'for_update': self.for_update, 'limit_max': self.limit_max, } ``` -------------------------------- ### Get Exterior Manifold Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/representations/representation.html Retrieves the knot complement manifold as a SnapPy class, providing access to SnapPy's tools. Requires Spherogram and potentially SnapPy to be installed. ```python return self.planar_diagram().as_spherogram().exterior() ``` -------------------------------- ### Model Query Helper Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes the ModelQueryHelper, setting the database if not already defined. ```python super(_ModelQueryHelper, self).__init__(*args, **kwargs) if not self._database: self._database = self.model._meta.database ``` -------------------------------- ### Context Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes the Context with a stack for states, SQL components, values, an AliasManager, and an initial State. ```python class Context(object): def __init__(self, **settings): self.stack = [] self._sql = [] self._values = [] self.alias_manager = AliasManager() self.state = State(**settings) ``` -------------------------------- ### Get Peewee Foreign Keys Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Placeholder method to retrieve foreign key information for a table. Raises NotImplementedError if not implemented. ```python def get_foreign_keys(self, table, schema=None): raise NotImplementedError ``` -------------------------------- ### Create a New Model Instance and Save Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Creates a new instance of the model with the provided query parameters and immediately saves it to the database. `force_insert=True` ensures it's an insert operation. ```python @classmethod def create(cls, **query): inst = cls(**query) inst.save(force_insert=True) return inst ``` -------------------------------- ### retrieve_space_curve Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/representations/representation.html Retrieves the space curve representation of a knot given specific starting and connection information. It handles cases with one or two possible starting lines. ```APIDOC ## retrieve_space_curve ### Description Retrieves the space curve representation of a knot. It determines the path of the curve by following connected lines and their associated arc numbers and heights. ### Method This is a method of the Representation class, called as an instance method. ### Parameters * **first** (Node) - The starting node for curve retrieval. * **next** (Node) - The next node in the sequence from the 'first' node. * **initial_arc_number** (int) - The starting arc number for the curve. * **heights** (dict) - A dictionary mapping (start_node, end_node, arc_number) to height values. ### Returns (numpy.ndarray) - An array representing the segments of the space curve. ``` -------------------------------- ### Get a Single Model Instance or None Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves a single instance of the model, returning `None` if no matching record is found. This is a safe alternative to `get` that avoids exceptions. ```python @classmethod def get_or_none(cls, *query, **filters): try: return cls.get(*query, **filters) except DoesNotExist: pass ``` -------------------------------- ### Peewee Database Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a Peewee database instance, setting up connection parameters and handling deferred initialization. ```python def __init__(self, database, thread_safe=True, autorollback=False, field_types=None, operations=None, autocommit=None, **kwargs): self._field_types = merge_dict(FIELD, self.field_types) self._operations = merge_dict(OP, self.operations) if field_types: self._field_types.update(field_types) if operations: self._operations.update(operations) self.autorollback = autorollback self.thread_safe = thread_safe if thread_safe: self._state = _ConnectionLocal() self._lock = threading.Lock() else: self._state = _ConnectionState() self._lock = _NoopLock() if autocommit is not None: __deprecated__('Peewee no longer uses the "autocommit" option, as ' 'the semantics now require it to always be True. ' 'Because some database-drivers also use the ' '"autocommit" parameter, you are receiving a ' 'warning so you may update your code and remove ' 'the parameter, as in the future, specifying ' 'autocommit could impact the behavior of the ' 'database driver you are using.') self.connect_params = {} self.init(database, **kwargs) def init(self, database, **kwargs): if not self.is_closed(): self.close() self.database = database self.connect_params.update(kwargs) self.deferred = not bool(database) ``` -------------------------------- ### Get SQLite Table Foreign Keys Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves metadata for foreign key constraints on a specified SQLite table. It uses the `foreign_key_list` PRAGMA to get constraint details. ```python def get_foreign_keys(self, table, schema=None): cursor = self.execute_sql('PRAGMA "%s".foreign_key_list("%s")' % (schema or 'main', table)) return [ForeignKeyMetadata(row[3], row[2], row[4], table) for row in cursor.fetchall()] ``` -------------------------------- ### Create All Tables Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Creates all tables defined in the schema. Supports a 'safe' mode to prevent errors if tables already exist. ```python if safe and not cls._meta.database.safe_create_index \ and cls.table_exists(): return cls._schema.create_all(safe, **options) ``` -------------------------------- ### ModelRaw Get Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves a single instance from a raw query. Raises Model.DoesNotExist if no matching instance is found, providing the SQL and parameters used. ```python def get(self): try: return self.execute()[0] except IndexError: sql, params = self.sql() raise self.model.DoesNotExist('%s instance matching query does ' 'not exist:\nSQL: %s\nParams: %s' % (self.model, sql, params)) ``` -------------------------------- ### PostgreSQL Database Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a PostgreSQL database connection, optionally registering Unicode types and setting client encoding. Requires the `psycopg2` driver. ```python def init(self, database, register_unicode=True, encoding=None, **kwargs): self._register_unicode = register_unicode self._encoding = encoding self._need_server_version = True super(PostgresqlDatabase, self).init(database, **kwargs) ``` -------------------------------- ### Get Single Instance with Pagination Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves a single instance by applying pagination to limit results to one. Raises Model.DoesNotExist if no record is found, including the SQL and parameters. ```python def get(self): clone = self.paginate(1, 1) clone._cursor_wrapper = None try: return clone.execute()[0] except IndexError: sql, params = clone.sql() raise self.model.DoesNotExist('%s instance matching query does ' 'not exist:\nSQL: %s\nParams: %s' % (clone.model, sql, params)) ``` -------------------------------- ### Begin Peewee Database Connection Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Ensures the database connection is established, connecting if it's currently closed. ```python def begin(self): if self.is_closed(): self.connect() ``` -------------------------------- ### Get Schema Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the schema name associated with the model's metadata. ```python @property def schema(self): return self._schema ``` -------------------------------- ### SqliteDatabase Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes the SqliteDatabase, setting up pragmas, timeout, and other connection parameters. It handles pragmas provided as a dictionary or a list of tuples. ```python def __init__(self, database, *args, **kwargs): self._pragmas = kwargs.pop('pragmas', ()) super(SqliteDatabase, self).__init__(database, *args, **kwargs) self._aggregates = {} self._collations = {} self._functions = {} self._table_functions = [] self._extensions = set() self._attached = {} self.register_function(_sqlite_date_part, 'date_part', 2) self.register_function(_sqlite_date_trunc, 'date_trunc', 2) ``` ```python def init(self, database, pragmas=None, timeout=5, **kwargs): if pragmas is not None: self._pragmas = pragmas if isinstance(self._pragmas, dict): self._pragmas = list(self._pragmas.items()) self._timeout = timeout super(SqliteDatabase, self).init(database, **kwargs) ``` -------------------------------- ### Get Peewee Transaction Depth Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the current number of nested transactions. ```python def transaction_depth(self): return len(self._state.transactions) ``` -------------------------------- ### Get Default Data for Insert Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns a dictionary of default values for insertable fields. ```python def get_default_data(self): return {} ``` -------------------------------- ### Link Class Initialization Source: https://pyknotid.readthedocs.io/en/latest/sources/spacecurves/link.html Initializes a Link instance with a list of lines and an optional verbose flag. ```APIDOC ## Link(lines, verbose=True) ### Description Class for holding the vertices of multiple lines, providing helper methods for convenient manipulation and analysis. The data is stored internally as multiple :class:`Knot`s. ### Parameters #### Parameters - **lines** (list of nx3 array-like or Knots) – List with the points of each line. - **verbose** (bool) – Whether to print information during processing. Defaults to True. ``` -------------------------------- ### AliasManager GetItem Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Allows dictionary-style access to retrieve an alias using the get method. ```python def __getitem__(self, source): return self.get(source) ``` -------------------------------- ### close Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/spacecurves/spacecurve.html Adds the starting point to the end of the curve, ensuring it ends exactly where it began. ```APIDOC ## close ### Description Adds the starting point to the end of the curve, so that it ends exactly where it began. ### Method N/A (This is a method of a class) ### Parameters None ### Request Example N/A ### Response N/A (Modifies the object in-place) ``` -------------------------------- ### Peewee _ModelWriteQueryHelper Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a helper class for write operations (INSERT, UPDATE, DELETE) on models. It inherits from _ModelQueryHelper and sets up the model context for write queries. ```python def __init__(self, model, *args, **kwargs): self.model = model super(_ModelWriteQueryHelper, self).__init__(model, *args, **kwargs) ``` -------------------------------- ### Get SQLite Binary Type Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the appropriate type for binary data in SQLite, which is `sqlite3.Binary`. ```python def get_binary_type(self): return sqlite3.Binary ``` -------------------------------- ### Schema Manager Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes the SchemaManager with a model, an optional database, and context options. ```python def __init__(self, model, database=None, **context_options): self.model = model self._database = database context_options.setdefault('scope', SCOPE_VALUES) self.context_options = context_options ``` -------------------------------- ### Model Initialization and Configuration Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Defines the constructor for Peewee models, handling initial data population and tracking dirty fields. Includes class methods for aliasing and selecting fields. ```python def __init__(self, *args, **kwargs): if kwargs.pop('__no_default__', None): self.__data__ = {} else: self.__data__ = self._meta.get_default_dict() self._dirty = set(self.__data__) self.__rel__ = {} for k in kwargs: setattr(self, k, kwargs[k]) def __str__(self): return str(self._pk) if self._meta.primary_key is not False else 'n/a' @classmethod def validate_model(cls): pass @classmethod def alias(cls, alias=None): return ModelAlias(cls, alias) @classmethod def select(cls, *fields): is_default = not fields if not fields: fields = cls._meta.sorted_fields return ModelSelect(cls, fields, is_default=is_default) ``` -------------------------------- ### Close the Curve Source: https://pyknotid.readthedocs.io/en/latest/sources/spacecurves/spacecurve.html Appends the starting point to the end of the curve, ensuring it closes exactly where it began. ```python close() ``` -------------------------------- ### from_qwer() Source: https://pyknotid.readthedocs.io/en/latest/genindex.html Creates a Cell from qwer data. ```APIDOC ## from_qwer() ### Description Creates a Cell from qwer data. ### Method N/A (Class method of Cell) ### Endpoint N/A (SDK Class Method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Get Dirty Fields of a Peewee Instance Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns a list of field names that have been modified on the model instance. ```python @property def dirty_fields(self): return [f for f in self._meta.sorted_fields if f.name in self._dirty] ``` -------------------------------- ### Initialize Insert Query Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes an INSERT query with the table, data to insert, and optional columns or conflict handling. ```python def __init__(self, table, insert=None, columns=None, on_conflict=None, **kwargs): super(Insert, self).__init__(table, **kwargs) self._insert = insert self._columns = columns self._on_conflict = on_conflict self._query_type = None ``` -------------------------------- ### Get Primary Key of Model Instance Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the primary key value of the current model instance. ```python def get_id(self): return getattr(self, self._meta.primary_key.name) _pk = property(get_id) ``` -------------------------------- ### Get Entity Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns an Entity object representing the model's table, including schema if specified. ```python @property def entity(self): if self._schema: return Entity(self._schema, self.table_name) else: return Entity(self.table_name) ``` -------------------------------- ### CompositeKey Get Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the composite key value for a given instance as a tuple of attribute values. ```python def __get__(self, instance, instance_type=None): if instance is not None: return tuple([getattr(instance, field_name) for field_name in self.field_names]) return self ``` -------------------------------- ### Initialize Link from periodic lines Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/spacecurves/link.html Creates a Link instance by unwrapping lines through periodic boundaries. Optionally perturbs the knot to avoid lattice issues. ```python link = cls(lines) if perturb: link.translate(n.array([0.00123, 0.00231, 0.00321])) link.rotate() ``` -------------------------------- ### Get Last Insert ID from Cursor Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the ID of the last inserted row from a database cursor. ```python def last_insert_id(self, cursor, query_type=None): return cursor.lastrowid ``` -------------------------------- ### Applying Ordering and Limits in Peewee Queries Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Applies ordering, limit, and offset clauses to the SQL context. It handles cases where limit or offset might be None or use a default maximum limit. ```python def _apply_ordering(self, ctx): if self._order_by: (ctx .literal(' ORDER BY ') .sql(CommaNodeList(self._order_by))) if self._limit is not None or (self._offset is not None and ctx.state.limit_max): ctx.literal(' LIMIT ').sql(self._limit or ctx.state.limit_max) if self._offset is not None: ctx.literal(' OFFSET ').sql(self._offset) return ctx ``` -------------------------------- ### Get Table Object Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the Table object associated with the model's metadata. Creates it if it doesn't exist. ```python @property def table(self): if self._table is None: self._table = Table( self.table_name, [field.column_name for field in self.sorted_fields], schema=self.schema, alias=self.table_alias, _model=self.model, _database=self.database) return self._table ``` -------------------------------- ### Get MySQL Binary Type Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the MySQL-specific binary type object. Used for handling binary data. ```python def get_binary_type(self): return mysql.Binary ``` -------------------------------- ### VirtualField Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a VirtualField, optionally accepting a specific field class. It stores an instance of the field if provided. ```python class VirtualField(MetaField): field_class = None def __init__(self, field_class=None, *args, **kwargs): Field = field_class if field_class is not None else self.field_class self.field_instance = Field() if Field is not None else None super(VirtualField, self).__init__(*args, **kwargs) ``` -------------------------------- ### Get MySQL Column Metadata Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves metadata for columns of a given MySQL table. Queries the 'information_schema.columns' table. ```python def get_columns(self, table, schema=None): sql = """ SELECT column_name, is_nullable, data_type, column_default FROM information_schema.columns WHERE table_name = %s AND table_schema = DATABASE()""" cursor = self.execute_sql(sql, (table,)) pks = set(self.get_primary_keys(table)) return [ColumnMetadata(name, dt, null == 'YES', name in pks, table, df) for name, null, dt, df in cursor.fetchall()] ``` -------------------------------- ### Get Peewee Columns Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Placeholder method to retrieve column information for a table. Raises NotImplementedError if not implemented. ```python def get_columns(self, table, schema=None): raise NotImplementedError ``` -------------------------------- ### Get Peewee Indexes Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Placeholder method to retrieve index information for a table. Raises NotImplementedError if not implemented. ```python def get_indexes(self, table, schema=None): raise NotImplementedError ``` -------------------------------- ### Handle Simple INSERT Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Generates the SQL for a simple INSERT statement with provided data. ```python def _simple_insert(self, ctx): if not self._insert: raise self.DefaultValuesException('Error: no data to insert.') return self._generate_insert((self._insert,), ctx) ``` -------------------------------- ### Model Metadata Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes model metadata, including table name, indexes, constraints, and relationships. Handles table name generation if not explicitly provided. ```python self.name = model.__name__.lower() self.table_function = table_function if not table_name: table_name = (self.table_function(model) if self.table_function else re.sub('[^\\w]+', '_', self.name)) self.table_name = table_name self._table = None self.indexes = list(indexes) if indexes else [] self.constraints = constraints self._schema = schema self.primary_key = primary_key self.composite_key = self.auto_increment = None self.only_save_dirty = only_save_dirty self.table_alias = table_alias self.depends_on = depends_on self.without_rowid = without_rowid self.refs = {} self.backrefs = {} self.model_refs = collections.defaultdict(list) self.model_backrefs = collections.defaultdict(list) self.manytomany = {} self.options = options or {} for key, value in kwargs.items(): setattr(self, key, value) self._additional_keys = set(kwargs.keys()) ``` -------------------------------- ### Get Rows Affected from Cursor Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the number of rows affected by the last executed query from a database cursor. ```python def rows_affected(self, cursor): return cursor.rowcount ``` -------------------------------- ### Column Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a Column object with its source and name. ```python class Column(ColumnBase): def __init__(self, source, name): self.source = source self.name = name ``` -------------------------------- ### close Source: https://pyknotid.readthedocs.io/en/latest/sources/spacecurves/spacecurve.html Modifies the SpaceCurve in-place by adding the starting point to the end of the curve, ensuring it forms a closed loop. ```APIDOC ## close ### Description Adds the starting point to the end of the curve, so that it ends exactly where it began. ``` -------------------------------- ### State Call Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Creates a new State instance, inheriting most settings from the current state but allowing overrides for scope, parentheses, subquery, and other settings. ```python def __call__(self, scope=None, parentheses=None, subquery=None, **kwargs): # All state is "inherited" except parentheses. scope = self.scope if scope is None else scope subquery = self.subquery if subquery is None else subquery # Try to avoid unnecessary dict copying. if kwargs and self.settings: settings = self.settings.copy() # Copy original settings dict. settings.update(kwargs) # Update copy with overrides. elif kwargs: settings = kwargs else: settings = self.settings return State(scope, parentheses, subquery, **settings) ``` -------------------------------- ### Enter Peewee Manual Commit Mode Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns a context manager for manual transaction commit control. ```python def manual_commit(self): return _manual(self) ``` -------------------------------- ### Download Database Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/catalogue/getdb.html Downloads the knots database to the target directory. It creates the directory if it doesn't exist and raises an IOError if the file already exists. Uses requests and tqdm for downloading and progress display. ```python from pyknotid.catalogue.getdb import download_database try: download_database() print('Database downloaded successfully.') except IOError as e: print(f'Error: {e}') ``` -------------------------------- ### Peewee FieldAccessor Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Base class for accessing model fields. Handles getting and setting field values on model instances. ```python class FieldAccessor(object): def __init__(self, model, field, name): self.model = model self.field = field self.name = name def __get__(self, instance, instance_type=None): if instance is not None: return instance.__data__.get(self.name) return self.field def __set__(self, instance, value): instance.__data__[self.name] = value instance._dirty.add(self.name) ``` -------------------------------- ### Get MySQL Foreign Keys Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves metadata for foreign key constraints on a given MySQL table. Queries 'information_schema.key_column_usage'. ```python def get_foreign_keys(self, table, schema=None): query = """ SELECT column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_name = %s AND table_schema = DATABASE() AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL""" cursor = self.execute_sql(query, (table,)) return [ ForeignKeyMetadata(column, dest_table, dest_column, table) for column, dest_table, dest_column in cursor.fetchall()] ``` -------------------------------- ### Peewee Index Class SQL Generation Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html This snippet demonstrates the SQL generation for creating indexes, including unique, safe (IF NOT EXISTS), and USING clauses. ```python def __sql__(self, ctx): statement = 'CREATE UNIQUE INDEX ' if self._unique else 'CREATE INDEX ' with ctx.scope_values(subquery=True): ctx.literal(statement) if self._safe: ctx.literal('IF NOT EXISTS ') (ctx .sql(Entity(self._name)) .literal(' ON ') .sql(self._table) .literal(' ')) if self._using is not None: ctx.literal('USING %s ' % self._using) ``` -------------------------------- ### Get MySQL Index Metadata Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves metadata for indexes on a given MySQL table. Parses the output of 'SHOW INDEX FROM'. ```python def get_indexes(self, table, schema=None): cursor = self.execute_sql('SHOW INDEX FROM `%s`' % table) unique = set() indexes = {} for row in cursor.fetchall(): if not row[1]: unique.add(row[2]) indexes.setdefault(row[2], []) indexes[row[2]].append(row[4]) return [IndexMetadata(name, None, indexes[name], name in unique, table) for name in indexes] ``` -------------------------------- ### Enter Peewee Savepoint Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns a context manager for managing database savepoints. ```python def savepoint(self): return _savepoint(self) ``` -------------------------------- ### Peewee Select Query Building Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Demonstrates the internal methods used to construct a SQL SELECT query in Peewee, including handling joins, grouping, filtering, and ordering. ```Python @Node.copy def join(self, dest, join_type='INNER', on=None): if not self._from_list: raise ValueError('No sources to join on.') item = self._from_list.pop() self._from_list.append(Join(item, dest, join_type, on)) @Node.copy def group_by(self, *columns): grouping = [] for column in columns: if isinstance(column, Table): if not column._columns: raise ValueError('Cannot pass a table to group_by() that ' 'does not have columns explicitly ' 'declared.') grouping.extend([getattr(column, col_name) for col_name in column._columns]) else: grouping.append(column) self._group_by = grouping @Node.copy def group_by_extend(self, *values): group_by = tuple(self._group_by or ()) + values return self.group_by(*group_by) @Node.copy def having(self, *expressions): if self._having is not None: expressions = (self._having,) + expressions self._having = reduce(operator.and_, expressions) @Node.copy def distinct(self, *columns): if len(columns) == 1 and (columns[0] is True or columns[0] is False): self._simple_distinct = columns[0] else: self._simple_distinct = False self._distinct = columns @Node.copy def window(self, *windows): self._windows = windows if windows else None @Node.copy def for_update(self, for_update=True): self._for_update = 'FOR UPDATE' if for_update is True else for_update def _get_query_key(self): return self._alias def __sql_selection__(self, ctx, is_subquery=False): return ctx.sql(CommaNodeList(self._returning)) def __sql__(self, ctx): super(Select, self).__sql__(ctx) if ctx.scope == SCOPE_COLUMN: return self.apply_column(ctx) is_subquery = ctx.subquery state = { 'converter': None, 'in_function': False, 'parentheses': is_subquery or (ctx.scope == SCOPE_SOURCE), 'subquery': True, } if ctx.state.in_function: state['parentheses'] = False with ctx.scope_normal(**state): ctx.literal('SELECT ') if self._simple_distinct or self._distinct is not None: ctx.literal('DISTINCT ') if self._distinct: (ctx .literal('ON ') .sql(EnclosedNodeList(self._distinct)) .literal(' ')) with ctx.scope_source(): ctx = self.__sql_selection__(ctx, is_subquery) if self._from_list: with ctx.scope_source(parentheses=False): ctx.literal(' FROM ').sql(CommaNodeList(self._from_list)) if self._where is not None: ctx.literal(' WHERE ').sql(self._where) if self._group_by: ctx.literal(' GROUP BY ').sql(CommaNodeList(self._group_by)) if self._having is not None: ctx.literal(' HAVING ').sql(self._having) if self._windows is not None: ctx.literal(' WINDOW ') ctx.sql(CommaNodeList(self._windows)) # Apply ORDER BY, LIMIT, OFFSET. self._apply_ordering(ctx) if self._for_update: if not ctx.state.for_update: raise ValueError('FOR UPDATE specified but not supported ' 'by database.') ctx.literal(' ') ctx.sql(SQL(self._for_update)) if not ctx.state.in_function: ctx = self.apply_alias(ctx) return ctx ``` -------------------------------- ### Get Top Peewee Transaction Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns the most recent transaction object from the stack without removing it, or None if no transactions are active. ```python def top_transaction(self): if self._state.transactions: return self._state.transactions[-1] ``` -------------------------------- ### Sorted Field List Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes an empty list for storing sorted fields. ```python def __init__(self): self._keys = [] self._items = [] ``` -------------------------------- ### AliasManager Get Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Retrieves the alias for a given source. If any_depth is True, it searches through all mapping scopes from the most recent to the oldest. ```python def get(self, source, any_depth=False): if any_depth: for idx in reversed(range(self._current_index)): if source in self._mapping[idx]: return self._mapping[idx][source] return self.add(source) ``` -------------------------------- ### Download Knot Database Source: https://pyknotid.readthedocs.io/en/latest/sources/catalogue/index.html Downloads the pre-built knot database. This is necessary for explicit knot identification and direct database queries. The download may take a few seconds. ```python from pyknotid.catalogue.getdb import download_database download_database() ``` -------------------------------- ### PlanarDiagram as Extended NetworkX Graph Source: https://pyknotid.readthedocs.io/en/latest/sources/representations/planardiagram.html Internal use method to get a NetworkX graph along with additional crossing information. ```python as_networkx_extended() -> (Graph, dict) ``` -------------------------------- ### ValuesList Class Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a ValuesList object with a list of values and optional column names. ```python class ValuesList(BaseTable): def __init__(self, values, columns=None, alias=None): super(ValuesList, self).__init__(alias=alias) self._values = values self._columns = columns ``` -------------------------------- ### Peewee ModelInsert Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a ModelInsert query. If a RETURNING clause is not specified and the database supports it, it defaults to returning primary keys. ```python def __init__(self, *args, **kwargs): super(ModelInsert, self).__init__(*args, **kwargs) if self._returning is None and self.model._meta.database is not None: if self.model._meta.database.returning_clause: self._returning = self.model._meta.get_primary_keys() self._row_type = ROW.TUPLE ``` -------------------------------- ### SpaceCurve.plot_projection Source: https://pyknotid.readthedocs.io/en/latest/sources/spacecurves/spacecurve.html Plots a 2D diagram of the knot projected along the current z-axis, with options to mark crossings and the start point. ```APIDOC ## SpaceCurve.plot_projection ### Description Plots a 2D diagram of the knot projected along the current z-axis. The crossings, and start point of the curve, can optionally be marked. ### Method Instance Method ### Parameters #### Path Parameters None #### Query Parameters - **with_crossings** (bool) - Optional - If True, marks the location of each self-intersection in projection. Defaults to True. - **mark_start** (bool) - Optional - If True, marks the first point of the curve. Defaults to False. - **fig_ax** (tuple) - Optional - A 2-tuple of the matplotlib (fig, ax) to use, or None to create a new pair. - **show** (bool) - Optional - If True, opens a new window showing the drawing. Defaults to True. #### Request Body None ### Returns A 2-tuple of the matplotlib (fig, ax) used for the drawing. ``` -------------------------------- ### Loading SQLite Functions Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Registers custom scalar functions with the SQLite connection. This method is called internally during connection setup. ```python def _load_functions(self, conn): for name, (fn, num_params) in self._functions.items(): conn.create_function(name, num_params, fn) ``` -------------------------------- ### Loading SQLite Collations Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Registers custom collation sequences with the SQLite connection. This method is called internally during connection setup. ```python def _load_collations(self, conn): for name, fn in self._collations.items(): conn.create_collation(name, fn) ``` -------------------------------- ### Schema Manager Context Creation Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Creates and returns an SQL context for the associated database with the specified options. ```python def _create_context(self): return self.database.get_sql_context(**self.context_options) ``` -------------------------------- ### Context Enter Method (Parentheses) Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Enters the context manager. If parentheses are enabled in the current state, it appends a literal '(' to the SQL. ```python def __enter__(self): if self.parentheses: self.literal('(') return self ``` -------------------------------- ### Loading SQLite Aggregates Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Registers custom aggregate functions with the SQLite connection. This method is called internally during connection setup. ```python def _load_aggregates(self, conn): for name, (klass, num_params) in self._aggregates.items(): conn.create_aggregate(name, num_params, klass) ``` -------------------------------- ### ManyToManyField Get Models Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Returns a list of the two models involved in the many-to-many relationship, ordered by whether they are the back reference. ```python def get_models(self): return [model for _, model in sorted(( (self._is_backref, self.model), (not self._is_backref, self.rel_model)))] ``` -------------------------------- ### Peewee Ordering __sql__ Method Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Generates SQL for ordering clauses, including direction, collation, and NULLS handling. ```python def __sql__(self, ctx): ctx.sql(self.node).literal(' %s' % self.direction) if self.collation: ctx.literal(' COLLATE %s' % self.collation) if self.nulls: ctx.literal(' NULLS %s' % self.nulls) return ctx ``` -------------------------------- ### Insert from a Query Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Prepares an operation to insert data into the model's table from the results of another query. Requires the query and a list of fields to map the results to. ```python @classmethod def insert_from(cls, query, fields): columns = [getattr(cls, field) if isinstance(field, basestring) else field for field in fields] return ModelInsert(cls, insert=query, columns=columns) ``` -------------------------------- ### Get Peewee Primary Keys Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Placeholder method to retrieve primary key information for a table. Raises NotImplementedError if not implemented. ```python def get_primary_keys(self, table, schema=None): raise NotImplementedError ``` -------------------------------- ### Initialize Update Query Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes an UPDATE query with the table to update and the fields to set. ```python def __init__(self, table, update=None, **kwargs): super(Update, self).__init__(table, **kwargs) self._update = update self._from = None ``` -------------------------------- ### Access Knot Property Directly Source: https://pyknotid.readthedocs.io/en/latest/sources/catalogue/index.html Accesses a specific property of a knot object directly as an attribute. This example retrieves the determinant of a knot. ```python k.determinant # 7 ``` -------------------------------- ### PostgreSQL Database Connection Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Establishes a connection to the PostgreSQL database using `psycopg2`. Handles Unicode type registration and client encoding if specified during initialization. ```python def _connect(self): if psycopg2 is None: raise ImproperlyConfigured('Postgres driver not installed!') conn = psycopg2.connect(database=self.database, **self.connect_params) if self._register_unicode: pg_extensions.register_type(pg_extensions.UNICODE, conn) pg_extensions.register_type(pg_extensions.UNICODEARRAY, conn) if self._encoding: conn.set_client_encoding(self._encoding) if self._need_server_version: self.set_server_version(conn.server_version) self._need_server_version = False return conn ``` -------------------------------- ### PrimaryKeyField Deprecation Warning Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Handles initialization for PrimaryKeyField, which is now an alias for AutoField. Includes a deprecation warning to guide users to update their code. ```python class PrimaryKeyField(AutoField): def __init__(self, *args, **kwargs): __deprecated__('"PrimaryKeyField" has been renamed to "AutoField". ') super(PrimaryKeyField, self).__init__(*args, **kwargs) ``` -------------------------------- ### download_target_dir Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/catalogue/getdb.html Returns the directory to which the knots database will be downloaded. ```APIDOC ## download_target_dir ### Description Returns the directory to which the knots database will be downloaded. ### Method GET ### Endpoint /download_target_dir ### Parameters None ### Response #### Success Response - **string** - The path to the download directory. #### Response Example ``` /path/to/user/data/pyknotid ``` ``` -------------------------------- ### Cursor Wrapper Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a wrapper around a database cursor to manage query results. It includes attributes for tracking row count, index, and caching. ```python class CursorWrapper(object): def __init__(self, cursor): self.cursor = cursor self.count = 0 self.index = 0 self.initialized = False self.populated = False self.row_cache = [] ``` -------------------------------- ### Populate Instance with Prefetched Data Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Populates a model instance with data from a prefetch query. It uses an ID map to efficiently link related objects to the primary instance based on whether it's a backreference or a forward relationship. ```python def populate_instance(self, instance, id_map): if self.is_backref: for field in self.fields: identifier = instance.__data__[field.name] key = (field, identifier) if key in id_map: setattr(instance, field.name, id_map[key]) else: for field, attname in self.field_to_name: identifier = instance.__data__[field.rel_field.name] key = (field, identifier) rel_instances = id_map.get(key, []) for inst in rel_instances: setattr(inst, attname, instance) setattr(instance, field.backref, rel_instances) ``` -------------------------------- ### Parsing Matrix String with cypari Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/invariants.html Converts the constructed matrix string into a cypari polynomial representation. Requires the 'cypari' library to be installed and imported. ```python from cypari.gen import pari return pari(''.join(outstrs)) ``` -------------------------------- ### Table Class Initialization Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Initializes a Table object, setting up its name, columns, primary key, schema, and model associations. It also dynamically creates column attributes if columns are provided. ```python class Table(_HashableSource, BaseTable): def __init__(self, name, columns=None, primary_key=None, schema=None, alias=None, _model=None, _database=None): self.__name__ = name self._columns = columns self._primary_key = primary_key self._schema = schema self._path = (schema, name) if schema else (name,) self._model = _model self._database = _database super(Table, self).__init__(alias=alias) # Allow tables to restrict what columns are available. if columns is not None: self.c = _ExplicitColumn() for column in columns: setattr(self, column, Column(self, column)) if primary_key: col_src = self if self._columns else self.c self.primary_key = getattr(col_src, primary_key) else: self.primary_key = None ``` -------------------------------- ### Plotting Function Dispatcher Source: https://pyknotid.readthedocs.io/en/latest/_modules/pyknotid/visualise.html Selects the appropriate plotting backend based on the 'mode' parameter. Ensure the required backend (mayavi or vispy) is installed. ```python if mode == 'mayavi': plot_cell_mayavi(lines, **kwargs) elif mode == 'vispy': plot_cell_vispy(lines, zero_centroid=False, **kwargs) else: raise ValueError('invalid toolkit/mode') ``` -------------------------------- ### Schema Manager Database Property Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Gets or sets the database associated with the schema manager. Defaults to the model's database if not explicitly set. ```python @property def database(self): return self._database or self.model._meta.database @database.setter def database(self, value): self._database = value ``` -------------------------------- ### Cursor Wrapper Initialization Placeholder Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html A placeholder method for initialization logic within the CursorWrapper. It is intended to be overridden or extended by subclasses. ```python def initialize(self): pass ``` -------------------------------- ### Create Peewee Tables Source: https://pyknotid.readthedocs.io/en/latest/_modules/peewee.html Creates database tables for a list of Peewee models, ensuring they are processed in the correct order. ```python def create_tables(self, models, **options): for model in sort_models(models): model.create_table(**options) ```