content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
"""Module for views wrappers.""" from typing import Optional, List, Dict, Union from django.conf import settings from django.views.generic.base import View from django.http.response import JsonResponse, HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.status import ( is_success, is_client_error, is_server_error, HTTP_500_INTERNAL_SERVER_ERROR, ) from views.request import DjangoRequestMixin, RestRequestMixin from exceptions import HumanReadableError from logging.debug import DebuggerMixin RequestResponseData = Union[List, Dict] class DjangoViewAPIMixin(DebuggerMixin): """Django View API base class mixin.* Created to standardize handling request and response. This class has a RESPONSE class attribute, that will serve as the response object to be returned by child instances of this base class. RESPONSE class attribute must be set on child classes as class attributes as well. The values of which is either one of the valid RESPONSE_CLASSES listed: - rest_framework's Response or - django's JsonResponse """ status = 200 RESPONSE = JsonResponse CONTENT_TYPE = "application/json" error_dict = { "title": "Error", "message": "Unable to process request.", "errors": None, } def get_content_type(self, content_type: Optional[str] = None) -> str: """Get view response content_type*. content_type possible values: None 'text/html' 'text/plain' 'application/json' # and others Defaults to class attribute CONTENT_TYPE, which can be set by children classes. https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.content_type https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type https://www.iana.org/assignments/media-types/media-types.xhtml """ return content_type if content_type is not None else self.CONTENT_TYPE def get_response( self, data: RequestResponseData, status: int, content_type: str, **kwargs ) -> HttpResponse: """Get the returned response.""" try: return self.RESPONSE( data=data, status=status, content_type=content_type, **kwargs ) except Exception: return self.RESPONSE(data=data, status=status, content_type=content_type) def success_response( self, data: RequestResponseData, status=200, content_type: Optional[str] = None, ) -> HttpResponse: """Method for returning success response from api.""" if not is_success(status): status = 200 content_type = self.get_content_type(content_type) response = self.get_response(data, status, content_type) return response def error_response( self, exception: Exception, error_data: Optional[dict] = None, status: Optional[int] = None, content_type: Optional[str] = None, ) -> HttpResponse: """Method for returning error response from api. NOTE: This should be called in the context of an except block. Arguments: exception - The exception instance on the Except block error_data - this is a mapping object with the same format as error_dict above. """ if settings.DEBUG: self.debug_exception(exception) if error_data is None: error_data = self.error_dict if status is None: status = self.status error_data = self.get_error_data(exception, error_data) status = self.get_error_status_code(status) content_type = self.get_content_type(content_type) response = self.get_response(error_data, status, content_type) return response def server_error_response( self, exception: Exception, title="Server Error", message="Please contact developer.", status=HTTP_500_INTERNAL_SERVER_ERROR, errors: Optional[List] = None, ) -> HttpResponse: """Return default server error response with debugging.""" self.status = status self.error_dict["title"] = title self.error_dict["message"] = message self.error_dict["errors"] = errors if errors else [str(exception)] return self.error_response( exception, error_data=self.error_dict, status=self.status ) def raise_error( self, title="Error", message="Unable to process request.", status=400, errors: Optional[List] = None, ) -> None: """Set status error status code and raise the human readable error.""" self.status = status self.error_dict["title"] = title self.error_dict["message"] = message self.error_dict["errors"] = errors if errors else [] raise HumanReadableError(message) def stopper(self) -> None: """For testing human readable exception clauses. Raises HumanReadableError. """ self.raise_error(title="Testing", message="Stopper") def is_error_human_readable(self, exception: Exception) -> bool: """Check if error exception is human readable.""" return isinstance(exception, HumanReadableError) def get_error_data(self, exception: Exception, error_data: dict) -> None: """Ensure correct error response data - a maping object serializable to JSON.* * On this format: { "title":<title>, "message": <message> } """ try: if self.is_valid_error_dict(error_data): error_data = error_data else: error_data = self.get_default_error_dict() if self.is_error_human_readable(exception): exception_message = str(exception) error_data["message"] = exception_message except Exception: error_data = self.get_default_error_dict() finally: return error_data def get_default_error_dict(self) -> dict: """Get default error dict.""" return { "title": "Error", "message": "Unable to process request.", "errors": None, } def is_valid_error_dict(self, error_data: dict) -> bool: """Check if error_data is in valid mapping format same as default_error_dict.""" try: valid = all( ( isinstance(error_data, dict), isinstance(error_data.get("title"), str), isinstance(error_data.get("message"), str), ) ) return valid except Exception: return False def get_error_status_code(self, code: int) -> int: """Get correct error status code, defaults to 400.""" try: error_code = 400 if self.is_valid_error_code(self.status): error_code = self.status elif self.is_valid_error_code(code): error_code = code return error_code except Exception: return 400 def is_valid_error_code(self, code: int) -> bool: """Check if code is valid error status code.""" return is_client_error(code) or is_server_error(code) class RestAPIView(DjangoViewAPIMixin, RestRequestMixin, APIView): """Our class based view for rest_framework api views. https://www.django-rest-framework.org/api-guide/views/#class-based-views """ RESPONSE = Response class DjangoView(DjangoViewAPIMixin, DjangoRequestMixin, View): """Our class based view for django views. https://docs.djangoproject.com/en/3.2/topics/class-based-views/#class-based-views https://docs.djangoproject.com/en/3.2/ref/class-based-views/base/#view """ RESPONSE = JsonResponse
[ 37811, 26796, 329, 5009, 7917, 11799, 526, 15931, 198, 198, 6738, 19720, 1330, 32233, 11, 7343, 11, 360, 713, 11, 4479, 628, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 8692, 1330, ...
2.413762
3,357
from setuptools import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name='sublime-backup', version='0.3', py_modules=['cli'], author = 'nishantwrp', author_email = 'mittalnishant14@outlook.com', long_description=long_description, long_description_content_type="text/markdown", url = 'https://github.com/nishantwrp/sublime-backup-cli', license = 'Apache 2.0', description = 'A simple command line tool to backup / sync your sublime snippets', install_requires=[ 'Click','configparser','appdirs','requests' ], entry_points=''' [console_scripts] sublime-backup=cli:cli ''', )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 4480, 1280, 7203, 15675, 11682, 13, 9132, 1600, 366, 81, 4943, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, 198, 198, 40406, 7, 198, 220, 220, 22...
2.476703
279
"""Provides the functionality to create a topic tree JSON file.""" import json from pathlib import Path from typing import Any, Dict, List, Optional, TypedDict, Union import pandas LANGUAGES = dict(en="", de="_de") class LeafNode(TypedDict): """A Node referencing a Concept""" title: str key: str type: str class Node(LeafNode): """A Node referencing a Topic""" children: List[Any] class TopicParser: """ Generate ``topics.json`` from ``topics.csv`` and ``concepts.csv``:: TopicParser().to_json() """
[ 37811, 15946, 1460, 262, 11244, 284, 2251, 257, 7243, 5509, 19449, 2393, 526, 15931, 198, 11748, 33918, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 32233, 11, 17134, 276, 35, 713, 11, ...
2.832487
197
# -*- coding: utf-8 -*- from rest_framework.permissions import BasePermission, DjangoModelPermissions, DjangoObjectPermissions from system.models import User, Role
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 7308, 5990, 3411, 11, 37770, 17633, 5990, 8481, 11, 37770, 10267, 5990, 8481, 198, 198, 6738, 1080, 13, 27530, 1330, 117...
3.5
48
__version__ = "0.7.15"
[ 834, 9641, 834, 796, 366, 15, 13, 22, 13, 1314, 1, 198 ]
1.916667
12
""" """
[ 37811, 198, 37811, 628 ]
2.25
4
""" In mathematics, the greatest common divisor (gcd) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4. » https://en.wikipedia.org/wiki/Greatest_common_divisor Due to limited recursion depth this algorithm is not suited for calculating the GCD of big integers. """ x = int(input("x = ")) y = int(input("y = ")) print(f"gcd({x}, {y}) = {recGCD(x,y)}")
[ 37811, 198, 818, 19473, 11, 262, 6000, 2219, 2659, 271, 273, 357, 70, 10210, 8, 286, 734, 393, 517, 37014, 11, 198, 4758, 389, 407, 477, 6632, 11, 318, 262, 4387, 3967, 18253, 326, 36319, 1123, 286, 262, 37014, 13, 220, 198, 1890, ...
3.108108
148
from django.core.management.base import BaseCommand from django.db import transaction from ...models import (HomePage, ObjectBiographiesPage, ObjectBiographyPage, SourcePage, SourcesPage)
[ 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 198, 6738, 2644, 27530, 1330, 357, 16060, 9876, 11, 9515, 23286, 41480, 9876, 11, 9515, 23286, 4867, 9876, 11, 198...
3.042857
70
import os import cv2 import mmcv import numpy as np from mmcv.image import imread, imwrite from mmcv import color_val from mmdet.apis import init_detector, inference_detector config_file = 'configs_zhym/faster_rcnn_r50_fpn_1x_voc_handeonlytable.py' checkpoint_file = 'work_dirs/faster_rcnn_r50_fpn_1x_handeonlytable/epoch_10.pth' #config_file = 'configs_zhym/cascade_mask_rcnn_r101_fpn_1x_four_points.py' #checkpoint_file = 'work_dirs/cascade_mask_rcnn_r101_fpn_1x/epoch_12.pth' # build the model from a config file and a checkpoint file model = init_detector(config_file, checkpoint_file, device='cuda:0') # test a single image and show the results img_root_dir = '/home/zhaoyanmei/data/HANDE/HandeOnlyTable/PDF4_new_JPEGs/' #img_root_dir = '/home/zhaoyanmei/mmdetection/data/CoCoFourPoint/test/' dst_dir = '/home/zhaoyanmei/data/HANDE/HandeOnlyTable/visualize_PDF4/' dst_pred_txt = dst_dir + 'pred_result.txt' pred_txt_file = open(dst_pred_txt, 'w') for i, img_file in enumerate(os.listdir(img_root_dir)): print(i) img = os.path.join(img_root_dir, img_file) result = inference_detector(model, img) show_result(img, result, model.CLASSES, out_file=os.path.join(dst_dir, img_file)) # test a list of images and write the results to image files #imgs = ['000000000060.jpg'] #for i, result in enumerate(inference_detector(model, imgs)): # show_result(imgs[i], result, model.CLASSES, out_file='result_{}.jpg'.format(i))
[ 11748, 28686, 198, 11748, 269, 85, 17, 198, 11748, 8085, 33967, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 8085, 33967, 13, 9060, 1330, 545, 961, 11, 545, 13564, 198, 6738, 8085, 33967, 1330, 3124, 62, 2100, 198, 6738, 8085, 15255, ...
2.467466
584
"""Python serial number generator.""" class SerialGenerator: """Machine to create unique incrementing serial numbers. >>> serial = SerialGenerator(start=100) >>> serial.generate() 100 >>> serial.generate() 101 >>> serial.generate() 102 >>> serial.reset() >>> serial.generate() 100 """ def __init__(self, start = 0): """init a new generator, with start value.""" self.start = start self.next = start def __repr__(self): """special method used to represent a class’s objects as a string""" return f"<SerialGenerator start={self.start} next={self.next}>" def generate(self): """generate next number""" n = self.next print(self.next) self.next += 1 return n def reset(self): """reset start value""" self.next = self.start s = SerialGenerator(4) s.generate() s.generate()
[ 37811, 37906, 11389, 1271, 17301, 526, 15931, 198, 198, 4871, 23283, 8645, 1352, 25, 198, 220, 220, 220, 37227, 37573, 284, 2251, 3748, 18703, 278, 11389, 3146, 13, 198, 220, 220, 220, 220, 198, 220, 220, 220, 13163, 11389, 796, 23283, ...
2.46875
384
#! /usr/bin/env python # # Copyright (c) 2014, Dionach Ltd. All rights reserved. See LICENSE file. # # By BB # based on MS-PST Microsoft specification for PST file format [MS-PST].pdf v2.1 # import struct, datetime, math, os, sys, unicodedata, re, argparse, itertools, string import progressbar error_log_list = [] if sys.hexversion >= 0x03000000: else: to_byte = ord ############################################################################################################################## # _ _ _ ____ _ _ ___ _ ____ ______ _ # | \ | | ___ __| | ___ | _ \ __ _| |_ __ _| |__ __ _ ___ ___ / / \ | | _ \| __ ) \ | | __ _ _ _ ___ _ __ # | \| |/ _ \ / _` |/ _ \ | | | |/ _` | __/ _` | '_ \ / _` / __|/ _ \ | || \| | | | | _ \| | | | / _` | | | |/ _ \ '__| # | |\ | (_) | (_| | __/ | |_| | (_| | || (_| | |_) | (_| \__ \ __/ | || |\ | |_| | |_) | | | |__| (_| | |_| | __/ | # |_| \_|\___/ \__,_|\___| |____/ \__,_|\__\__,_|_.__/ \__,_|___/\___| | ||_| \_|____/|____/| | |_____\__,_|\__, |\___|_| # \_\ /_/ |___/ ############################################################################################################################## class NBD: """Node Database Layer""" def fetch_all_block_data(self, bid): """returns list of block datas""" datas = [] block = self.fetch_block(bid) if block.block_type == Block.btypeData: datas.append(block.data) elif block.block_type == Block.btypeXBLOCK: for xbid in block.rgbid: xblock = self.fetch_block(xbid) if xblock.block_type != Block.btypeData: raise PSTException('Expecting data block, got block type %s' % xblock.block_type) datas.append(xblock.data) elif block.block_type == Block.btypeXXBLOCK: for xxbid in block.rgbid: xxblock = self.fetch_block(xxbid) if xxblock.block_type != Block.btypeXBLOCK: raise PSTException('Expecting XBLOCK, got block type %s' % xxblock.block_type) datas.extend(self.fetch_all_block_data(xxbid)) else: raise PSTException('Invalid block type (not data/XBLOCK/XXBLOCK), got %s' % block.block_type) return datas def fetch_subnodes(self, bid): """ get dictionary of subnode SLENTRYs for subnode bid""" subnodes = {} block = self.fetch_block(bid) if block.block_type == Block.btypeSLBLOCK: for slentry in block.rgentries: if slentry.nid in subnodes.keys(): raise PSTException('Duplicate subnode %s' % slentry.nid) subnodes[slentry.nid.nid] = slentry elif block.block_type == Block.btypeSIBLOCK: for sientry in block.rgentries: subnodes.update(self.fetch_subnodes(sientry.bid)) else: raise PSTException('Invalid block type (not SLBLOCK/SIBLOCK), got %s' % block.block_type) return subnodes def get_page_leaf_entries(self, entry_type, page_offset): """ entry type is NBTENTRY or BBTENTRY""" leaf_entries = {} page = self.fetch_page(page_offset) for entry in page.rgEntries: if isinstance(entry, entry_type): if entry.key in leaf_entries.keys(): raise PSTException('Invalid Leaf Key %s' % entry) leaf_entries[entry.key] = entry elif isinstance(entry, BTENTRY): leaf_entries.update(self.get_page_leaf_entries(entry_type, entry.BREF.ib)) else: raise PSTException('Invalid Entry Type') return leaf_entries ################################################################################################################################################################################ # _ _ _ _____ _ _ _ ____ _ _ ___ _____ ______ _ # | | (_)___| |_ ___ |_ _|_ _| |__ | | ___ ___ __ _ _ __ __| | | _ \ _ __ ___ _ __ ___ _ __| |_(_) ___ ___ / / | |_ _| _ \ \ | | __ _ _ _ ___ _ __ # | | | / __| __/ __| | |/ _` | '_ \| |/ _ \/ __| / _` | '_ \ / _` | | |_) | '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __| | || | | | | |_) | | | | / _` | | | |/ _ \ '__| # | |___| \__ \ |_\__ \_ | | (_| | |_) | | __/\__ \_ | (_| | | | | (_| | | __/| | | (_) | |_) | __/ | | |_| | __/\__ \ | || |___| | | __/| | | |__| (_| | |_| | __/ | # |_____|_|___/\__|___( ) |_|\__,_|_.__/|_|\___||___( ) \__,_|_| |_|\__,_| |_| |_| \___/| .__/ \___|_| \__|_|\___||___/ | ||_____|_| |_| | | |_____\__,_|\__, |\___|_| # |/ |/ |_| \_\ /_/ |___/ ################################################################################################################################################################################ class LTP: """LTP layer""" ############################################################################################################################# # __ __ _ _ # | \/ | ___ ___ ___ __ _ __ _(_)_ __ __ _ | | __ _ _ _ ___ _ __ # | |\/| |/ _ \/ __/ __|/ _` |/ _` | | '_ \ / _` | | | / _` | | | |/ _ \ '__| # | | | | __/\__ \__ \ (_| | (_| | | | | | (_| | | |__| (_| | |_| | __/ | # |_| |_|\___||___/___/\__,_|\__, |_|_| |_|\__, | |_____\__,_|\__, |\___|_| # |___/ |___/ |___/ ############################################################################################################################# class Messaging: """Messaging Layer""" ############################################################################################################################# # ____ ____ _____ _ # | _ \/ ___|_ _| | | __ _ _ _ ___ _ __ # | |_) \___ \ | | | | / _` | | | |/ _ \ '__| # | __/ ___) || | | |__| (_| | |_| | __/ | # |_| |____/ |_| |_____\__,_|\__, |\___|_| # |___/ ############################################################################################################################# ################################################################################################################################### # _ _ _ _ _ _ _ _____ _ _ # | | | | |_(_) (_) |_ _ _ | ___| _ _ __ ___| |_(_) ___ _ __ ___ # | | | | __| | | | __| | | | | |_ | | | | '_ \ / __| __| |/ _ \| '_ \/ __| # | |_| | |_| | | | |_| |_| | | _|| |_| | | | | (__| |_| | (_) | | | \__ \ # \___/ \__|_|_|_|\__|\__, | |_| \__,_|_| |_|\___|\__|_|\___/|_| |_|___/ # |___/ ################################################################################################################################### def get_unused_filename(filepath): """ adds numbered suffix to filepath if filename already exists""" if os.path.exists(filepath): suffix = 1 while os.path.exists('%s-%s%s' % (os.path.splitext(filepath)[0], suffix, os.path.splitext(filepath)[1])): suffix += 1 filepath = '%s-%s%s' % (os.path.splitext(filepath)[0], suffix, os.path.splitext(filepath)[1]) return filepath ############################################################################################################################### # # _____ _ _____ _ _ # |_ _|__ ___| |_ | ___| _ _ __ ___| |_(_) ___ _ __ ___ # | |/ _ \/ __| __| | |_ | | | | '_ \ / __| __| |/ _ \| '_ \/ __| # | | __/\__ \ |_ | _|| |_| | | | | (__| |_| | (_) | | | \__ \ # |_|\___||___/\__| |_| \__,_|_| |_|\___|\__|_|\___/|_| |_|___/ # ############################################################################################################################### def test_dump_pst(pst_filepath, output_path): """ dump out all PST email attachments and emails (into text files) to output_path folder""" pst = PST(pst_filepath) print(pst.get_pst_status()) pbar = get_simple_progressbar('Messages: ') total_messages = pst.get_total_message_count() pst.export_all_messages(output_path, pbar, total_messages) pbar.finish() pbar = get_simple_progressbar('Attachments: ') total_attachments = pst.get_total_attachment_count() pst.export_all_attachments(output_path, pbar, total_attachments) pbar.finish() pst.close() ################################################################################################################################### # __ __ _ # | \/ | __ _(_)_ __ # | |\/| |/ _` | | '_ \ # | | | | (_| | | | | | # |_| |_|\__,_|_|_| |_| # ################################################################################################################################### if __name__=="__main__": input_pst_file = '' output_folder = 'dump' arg_parser = argparse.ArgumentParser(prog='pst', description='PST: parses PST files. Can dump emails and attachments.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) arg_parser.add_argument('-i', dest='input_pst_file', default=input_pst_file, help='input PST file to dump') arg_parser.add_argument('-o', dest='output_folder', default=output_folder, help='output folder') arg_parser.add_argument('-t', dest='debug', help=argparse.SUPPRESS, action='store_true', default=False) # hidden argument args = arg_parser.parse_args() if not args.debug: input_pst_file = args.input_pst_file output_folder = args.output_folder if not os.path.exists(input_pst_file): print('Input PST file does not exist') sys.exit(1) if not os.path.exists(output_folder): print('Output folder does not exist') sys.exit(1) test_dump_pst(input_pst_file,output_folder) else: # debug pass #test_folder = 'D:\\' #test_status_pst(test_folder+'sample.pst') #test_dump_pst(test_folder+'sample.pst', test_folder+'dump') #test_folder_psts(test_folder)
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 66, 8, 1946, 11, 29628, 620, 12052, 13, 1439, 2489, 10395, 13, 4091, 38559, 24290, 2393, 13, 198, 2, 198, 2, 2750, 12597, 198, 2, 1912, 319, 6579, 12, 47...
2.165342
5,032
''' d_ij = matrice dei costi per ogni colonna trovo il minimo della colonna a ogni elemento della colonna sottraggo il minimo (d0) si ottiene una nuova matrice con pesi >= 0 --- stessa operazione con le righe (d1) --- ottengo matrice di coefficienti d2 assegnamento rappresentato da matrice X dove x_ij = 1 se i assegnato a j, 0 else Nota: sum(x[i][j] for j in V) == 1 # 1 solo nodo assegnato stesso vale per j Nota: costo assegnamento = sum(d_ij * x_ij) = sum(d2 * x_ij) + sum(d1) + sum(d0) quindi D1 = sum(d1) + D0 = sum(d0) <= sum(d_ij * x_ij) rappresenta un lower bound del costo se si trova un matching di costo D1 + D0 allora è ottimo --- trovare sottinsieme di 0 in d2 di cardinalità max (1 solo x riga e conna) se insieme ammette soluzione di cardinalità --- per trovare delta: dati due insiemi di vertici A e B traccio un arco sse d2_ij = 0, il problema diventa quindi di trovare un matching di cardinalità massima (delta) se delta = n 1h02 dimostraz: siccome gli elementi devono essere indipendenti per il principio della piccionaia e delta ha cardinalità n, sum_i(x_ij) == 1e sum_j(x_ij) == 1 se delta < n in caso non si riesca a trovare va risolto un sottoproblema --- determinare il valore minimo lambda tra gli elementi T2 non coperti da nessuna linea. (gli elementi non ricoperti sono tutti strettamente positivi siccome tutti gli zeri sono coperti) * incremento tutti gli elementi ricoperti da due linee di lambda. * decremento tutti gli elementi non ricoperti di lambda. indicato con h1 il numero di riche nel ricoprimento e con h2 il numero di colonne nel ricoprimento, : h1 + h2 = delta si ha sum_i(d3_i) = - lambda * (#righe notin ricoprimento) = - lambda (n - h1) sum_j(d3_j) = lambda * (#colonne ricoprimento) = lambda (h2) --- ''' if __name__ == '__main__': mtx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ungherese(mtx)
[ 7061, 6, 198, 67, 62, 2926, 796, 2603, 20970, 390, 72, 1575, 72, 198, 198, 525, 267, 4593, 72, 951, 6415, 4161, 13038, 4229, 10356, 78, 390, 8466, 951, 6415, 198, 198, 64, 267, 4593, 72, 5002, 78, 390, 8466, 951, 6415, 264, 1252, ...
2.364882
803
import itertools from typing import List, Optional, Union from matplotlib import pyplot as plt from .asset_list import AssetList from .common.helpers import Float from .frontier.single_period import EfficientFrontier from .settings import default_ticker class Plots(AssetList): """ Plotting tools collection to use with financial charts (Efficient Frontier, Assets and Transition map etc.) Parameters ---------- assets : list, default None List of assets. Could include tickers or asset like objects (Asset, Portfolio). If None a single asset list with a default ticker is used. first_date : str, default None First date of monthly return time series. If None the first date is calculated automatically as the oldest available date for the listed assets. last_date : str, default None Last date of monthly return time series. If None the last date is calculated automatically as the newest available date for the listed assets. ccy : str, default 'USD' Base currency for the list of assets. All risk metrics and returns are adjusted to the base currency. inflation : bool, default True Defines whether to take inflation data into account in the calculations. Including inflation could limit available data (last_date, first_date) as the inflation data is usually published with a one-month delay. With inflation = False some properties like real return are not available. """ def plot_assets( self, kind: str = "mean", tickers: Union[str, list] = "tickers", pct_values: bool = False, ) -> plt.axes: """ Plot the assets points on the risk-return chart with annotations. Annualized values for risk and return are used. Risk is a standard deviation of monthly rate of return time series. Return can be an annualized mean return (expected return) or CAGR (Compound annual growth rate). Returns ------- Axes : 'matplotlib.axes._subplots.AxesSubplot' Parameters ---------- kind : {'mean', 'cagr'}, default 'mean' Type of Return: annualized mean return (expected return) or CAGR (Compound annual growth rate). tickers : {'tickers', 'names'} or list of str, default 'tickers' Annotation type for assets. 'tickers' - assets symbols are shown in form of 'SPY.US' 'names' - assets names are used like - 'SPDR S&P 500 ETF Trust' To show custom annotations for each asset pass the list of names. pct_values : bool, default False Risk and return values in the axes: Algebraic annotation (False) Percents (True) Examples -------- >>> import matplotlib.pyplot as plt >>> x = ok.Plots(['SPY.US', 'AGG.US'], ccy='USD', inflation=False) >>> x.plot_assets() >>> plt.show() Plotting with default parameters values shows expected return, ticker annotations and algebraic values for risk and return. To use CAGR instead of expected return use kind='cagr'. >>> x.plot_assets(kind='cagr', ... tickers=['US Stocks', 'US Bonds'], # use custom annotations for the assets ... pct_values=True # risk and return values are in percents ... ) >>> plt.show() """ if kind == "mean": risks = self.risk_annual returns = Float.annualize_return(self.assets_ror.mean()) elif kind == "cagr": risks = self.risk_annual returns = self.get_cagr().loc[self.symbols] else: raise ValueError('kind should be "mean" or "cagr".') # set lists for single point scatter if len(self.symbols) < 2: risks = [risks] returns = [returns] # set the plot self._verify_axes() plt.autoscale(enable=True, axis="year", tight=False) m = 100 if pct_values else 1 self.ax.scatter(risks * m, returns * m) # Set the labels if tickers == "tickers": asset_labels = self.symbols elif tickers == "names": asset_labels = list(self.names.values()) else: if not isinstance(tickers, list): raise ValueError( f"tickers parameter should be a list of string labels." ) if len(tickers) != len(self.symbols): raise ValueError("labels and tickers must be of the same length") asset_labels = tickers # draw the points and print the labels for label, x, y in zip(asset_labels, risks, returns): self.ax.annotate( label, # this is the text (x * m, y * m), # this is the point to label textcoords="offset points", # how to position the text xytext=(0, 10), # distance from text to points (x,y) ha="center", # horizontal alignment can be left, right or center ) return self.ax def plot_transition_map( self, bounds=None, full_frontier=False, cagr=True ) -> plt.axes: """ Plot Transition Map for optimized portfolios on the single period Efficient Frontier. Transition Map shows the relation between asset weights and optimized portfolios properties: - CAGR (Compound annual growth rate) - Risk (annualized standard deviation of return) Wights are displayed on the y-axis. CAGR or Risk - on the x-axis. Constrained optimization with weights bounds is available. Returns ------- Axes : 'matplotlib.axes._subplots.AxesSubplot' Parameters ---------- bounds: tuple of ((float, float),...) Bounds for the assets weights. Each asset can have weights limitation from 0 to 1.0. If an asset has limitation for 10 to 20%, bounds are defined as (0.1, 0.2). bounds = ((0, .5), (0, 1)) shows that in Portfolio with two assets first one has weight limitations from 0 to 50%. The second asset has no limitations. full_frontier : bool, default False Defines whether to show the Transition Map for portfolios on the full Efficient Frontier or only on its upper part. If 'False' only portfolios with the return above Global Minimum Volatility (GMV) point are shown. cagr : bool, default True Show the relation between weights and CAGR (if True) or between weights and Risk (if False). of - sets X axe to CAGR (if true) or to risk (if false). CAGR or Risk are displayed on the x-axis. Examples -------- >>> import matplotlib.pyplot as plt >>> x = ok.Plots(['SPY.US', 'AGG.US', 'GLD.US'], ccy='USD', inflation=False) >>> x.plot_transition_map() >>> plt.show() Transition Map with default setting show the relation between Return (CAGR) and assets weights for optimized portfolios. The same relation for Risk can be shown setting cagr=False. >>> x.plot_transition_map(cagr=False, ... full_frontier=True, # to see the relation for the full Efficient Frontier ... ) >>> plt.show() """ ef = EfficientFrontier( assets=self.symbols, first_date=self.first_date, last_date=self.last_date, ccy=self.currency, inflation=self._bool_inflation, bounds=bounds, full_frontier=full_frontier, n_points=20, ).ef_points self._verify_axes() linestyle = itertools.cycle(("-", "--", ":", "-.")) x_axe = "CAGR" if cagr else "Risk" fig = plt.figure(figsize=(12, 6)) for i in ef: if i not in ( "Risk", "Mean return", "CAGR", ): # select only columns with tickers self.ax.plot( ef[x_axe], ef.loc[:, i], linestyle=next(linestyle), label=i ) self.ax.set_xlim(ef[x_axe].min(), ef[x_axe].max()) if cagr: self.ax.set_xlabel("CAGR (Compound Annual Growth Rate)") else: self.ax.set_xlabel("Risk (volatility)") self.ax.set_ylabel("Weights of assets") self.ax.legend(loc="upper left", frameon=False) fig.tight_layout() return self.ax def plot_pair_ef(self, tickers="tickers", bounds=None) -> plt.axes: """ Plot Efficient Frontier of every pair of assets. Efficient Frontier is a set of portfolios which satisfy the condition that no other portfolio exists with a higher expected return but with the same risk (standard deviation of return). Arithmetic mean (expected return) is used for optimized portfolios. Returns ------- Axes : 'matplotlib.axes._subplots.AxesSubplot' Parameters ---------- tickers : {'tickers', 'names'} or list of str, default 'tickers' Annotation type for assets. 'tickers' - assets symbols are shown in form of 'SPY.US' 'names' - assets names are used like - 'SPDR S&P 500 ETF Trust' To show custom annotations for each asset pass the list of names. bounds: tuple of ((float, float),...) Bounds for the assets weights. Each asset can have weights limitation from 0 to 1.0. If an asset has limitation for 10 to 20%, bounds are defined as (0.1, 0.2). bounds = ((0, .5), (0, 1)) shows that in Portfolio with two assets first one has weight limitations from 0 to 50%. The second asset has no limitations. Notes ----- It should be at least 3 assets. Examples -------- >>> import matplotlib.pyplot as plt >>> ls4 = ['SPY.US', 'BND.US', 'GLD.US', 'VNQ.US'] >>> curr = 'USD' >>> last_date = '07-2021' >>> ok.Plots(ls4, ccy=curr, last_date=last_date).plot_pair_ef() >>> plt.show() It can be useful to plot the full Efficent Frontier (EF) with optimized 4 assets portfolios together with the EFs for each pair of assets. >>> ef4 = ok.EfficientFrontier(assets=ls4, ccy=curr, n_points=100) >>> df4 = ef4.ef_points >>> fig = plt.figure() >>> # Plot Efficient Frontier of every pair of assets. Optimized portfolios will have 2 assets. >>> ok.Plots(ls4, ccy=curr, last_date=last_date).plot_pair_ef() # mean return is used for optimized portfolios. >>> ax = plt.gca() >>> # Plot the full Efficient Frontier for 4 asset portfolios. >>> ax.plot(df4['Risk'], df4['Mean return'], color = 'black', linestyle='--') >>> plt.show() """ if len(self.symbols) < 3: raise ValueError("The number of symbols cannot be less than 3") self._verify_axes() for i in itertools.combinations(self.symbols, 2): sym_pair = list(i) index0 = self.symbols.index(sym_pair[0]) index1 = self.symbols.index(sym_pair[1]) if bounds: bounds_pair = (bounds[index0], bounds[index1]) else: bounds_pair = None ef = EfficientFrontier( assets=sym_pair, ccy=self.currency, first_date=self.first_date, last_date=self.last_date, inflation=self._bool_inflation, full_frontier=True, bounds=bounds_pair, ).ef_points self.ax.plot(ef["Risk"], ef["Mean return"]) self.plot_assets(kind="mean", tickers=tickers) return self.ax
[ 11748, 340, 861, 10141, 198, 6738, 19720, 1330, 7343, 11, 32233, 11, 4479, 198, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 198, 6738, 764, 562, 316, 62, 4868, 1330, 31433, 8053, 198, 6738, 764, 11321, 13, 167...
2.322375
5,171
# A class to collect alert properties import glob import os import pandas as pd
[ 2, 317, 1398, 284, 2824, 7995, 6608, 198, 198, 11748, 15095, 198, 11748, 28686, 198, 198, 11748, 19798, 292, 355, 279, 67, 628, 628 ]
3.541667
24
"""Downloading data from the M4 competition """ import os import requests if __name__ == "__main__": data_frequencies = ['Yearly', 'Quarterly', 'Monthly', 'Weekly', 'Daily', 'Hourly'] datapath = "./dataset/" url = "https://github.com/Mcompetitions/M4-methods/raw/master/Dataset/{}.csv" download(datapath, url, 'M4-info') for freq in data_frequencies: for split in ['train', 'test']: download(datapath+split, url, '{}-{}'.format(freq, split), split.capitalize())
[ 37811, 10002, 278, 1366, 422, 262, 337, 19, 5449, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 7007, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1366, 62, 69, 8897, 3976, 796, 37250, ...
2.410377
212
import time import math import keyboard # Betting Breakdown initFee = 1500000 prefCard = 500000 infamous = 3000000 safe1 = 1000000 safe2 = 3300000 safe3 = 6500000 target = 1000000000 ct = 1 print(f'\nWelcome to your grind-less \'Golden Grin Anonymous\' Achievement!\n') currentSpend = int(input('What is your current spend amount? $').replace(',','')) leftToSpend = '{:,}'.format(target - int(currentSpend)) print(f'OK, You have ${leftToSpend} left to spend.') safedCards = int(input('\nHow many cards do you have safed? ')) isitInfamous = input('Is It Infamous? (y/n) ').upper() if safedCards == 0: spin = initFee elif safedCards == 1: spin = initFee + prefCard + safe1 elif safedCards == 2: spin = initFee + prefCard + safe1 + safe2 else: spin = initFee + prefCard + safe1 + safe2 + safe3 if isitInfamous == 'Y': spin += infamous numSpins = math.ceil(currentSpend / spin) print(f'\nAt your current settings you would need {numSpins} card turns to reach the target.') start = input('Are you ready to start? (y/n) ').upper() if start != 'Y': print('\nThanks for playing.') else: print('\nLoad the game, enter your settings into Offshore Payday') print('Press any key to start...') keyboard.read_key() print('HOLD \'Q\' to quit.') spinThatWheel()
[ 11748, 640, 198, 11748, 10688, 198, 11748, 10586, 198, 198, 2, 5147, 889, 12243, 2902, 198, 15003, 37, 1453, 796, 20007, 830, 198, 3866, 69, 16962, 796, 5323, 830, 198, 10745, 10877, 796, 513, 10535, 198, 21230, 16, 796, 1802, 2388, 1...
2.73431
478
# -*- coding: utf-8 -*- # # 3rd party imports from django_medusa.renderers import DiskStaticSiteRenderer # Project imports from statify.models import URL
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 198, 2, 513, 4372, 2151, 17944, 198, 6738, 42625, 14208, 62, 1150, 22064, 13, 10920, 19288, 1330, 31664, 45442, 29123, 49, 437, 11882, 198, 198, 2, 4935, 17944, ...
2.962264
53
import pysam from CigarIterator import CigarIterator, appendOrInc if __name__ == "__main__": pass #TODO
[ 11748, 279, 893, 321, 198, 6738, 32616, 283, 37787, 1330, 32616, 283, 37787, 11, 24443, 5574, 25517, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1208, 1303, 51, 3727, 46 ]
2.842105
38
""" WaveGlow teacher wrapper """ from functools import lru_cache import numpy as np import torch from models.waveglow import WaveGlow class WaveGlowTeacher(WaveGlow): """ A WaveGlow model optimized for use as a teacher in distillation """ @classmethod def sample_inputs_for(self, spect, sigma=1.0): """ upsample and generate noise: the non-distilled part of waveglow """ assert self.n_early_every > 0 and self.n_flows > 0 spect = self.upsample(spect) # trim conv artifacts. maybe pad spec to kernel multiple if not self.upsample_multistage: time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0] spect = spect[:, :, :-time_cutoff] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) num_noise_vectors = max(1, (self.n_flows - 1) // self.n_early_every) noise_audio = sigma * torch.randn(spect.shape[0], self.n_remaining_channels, spect.shape[2], device=spect.device, dtype=spect.dtype) noise_vectors = [sigma * torch.randn(spect.shape[0], self.n_early_size, spect.shape[2], device=spect.device, dtype=spect.dtype) for _ in range(num_noise_vectors)] return (spect, noise_audio, *noise_vectors) def forward(self, spect, noise_audio, *noise_vectors): """ A deterministic version of waveglow.infer; use compute_inputs_for(mel_spect) for inputs """ audio = noise_audio noise_index = 0 for k in reversed(range(self.n_flows)): n_half = audio.size(1) // 2 audio_0 = audio[:, :n_half, :] audio_1 = audio[:, n_half:, :] wn_input = (audio_0, spect) output = self.WN[k](wn_input) s = output[:, n_half:, :] b = output[:, :n_half, :] audio_1 = (audio_1 - b) / torch.exp(s) audio = torch.cat([audio_0, audio_1], 1) audio = self.convinv[k](audio, reverse=True) if k % self.n_early_every == 0 and k > 0: z = noise_vectors[noise_index] noise_index += 1 audio = torch.cat((z, audio), 1) assert noise_index == len(noise_vectors), f"Used {noise_index} noise vectors, but got {len(noise_vectors)}" audio = audio.permute(0, 2, 1).contiguous().view(audio.size(0), -1) return audio class DeterministicWaveGlowTeacher(WaveGlowTeacher): """ WaveGlowTeacher that predicts deterministically based on seed """ @lru_cache(maxsize=None) def sample_inputs_for(self, spect, **kwargs): """ upsample and generate noise: the non-distilled part of waveglow """ assert self.n_early_every > 0 and self.n_flows > 0 spect = self.upsample(spect) # trim conv artifacts. maybe pad spec to kernel multiple if not self.upsample_multistage: time_cutoff = self.upsample.kernel_size[0] - self.upsample.stride[0] spect = spect[:, :, :-time_cutoff] spect = spect.unfold(2, self.n_group, self.n_group).permute(0, 2, 1, 3) spect = spect.contiguous().view(spect.size(0), spect.size(1), -1).permute(0, 2, 1) num_noise_vectors = max(1, (self.n_flows - 1) // self.n_early_every) noise_num_channels = (self.n_remaining_channels,) + (self.n_early_size,) * num_noise_vectors noise_audio, *noise_vectors = self.generate_noise_inputs( spect.shape[0], noise_num_channels, spect.shape[2], device=spect.device, dtype=spect.dtype, **kwargs) return (spect, noise_audio, *noise_vectors)
[ 37811, 198, 220, 220, 17084, 38, 9319, 4701, 29908, 198, 37811, 198, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 198, 6738, 4981, 13, 19204, 4743, 322, 1330, 17084,...
2.182081
1,730
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Module for producing an animation of optimization histories for 3D problems given pickled mesh grid data. For examples of the mesh grid data, see raven/tests/framework/AnalyticModels/optimizing/plot_functions.py. """ import pickle as pk import matplotlib.pyplot as plt from matplotlib import colors from matplotlib import cm from mpl_toolkits.mplot3d import axes3d, Axes3D from matplotlib import animation import numpy as np # load function data bX,bY,bZ = pk.load(open('dvalley_plotdata.pk','rb')) norm = plt.Normalize(bZ.min()-1, bZ.max()+5) colors = cm.BuGn(norm(bZ)) rcount, ccount, _ = colors.shape fig = plt.figure(figsize=(10,8)) ax = fig.gca(projection='3d') ax.view_init(70, 0) surf = ax.plot_surface(bX, bY, bZ, rcount=rcount, ccount=ccount, facecolors=colors,alpha=0.3) ax.set_xlabel('x') ax.set_ylabel('y') # load walk data cases = range(5) data = {} for c,case in enumerate(cases): try: with open('opt_export_{}.csv'.format(case+1),'r', encoding = "utf-8-sig") as infile: data[case] = {'x':[],'y':[],'z':[],'a':[]} for l,line in enumerate(infile): line = line.strip().split(',') if l==0: ix = line.index('x') iy = line.index('y') iz = line.index('ans') ia = line.index('accepted') continue data[case]['x'].append(float(line[ix])) data[case]['y'].append(float(line[iy])) data[case]['z'].append(float(line[iz])) data[case]['a'].append(bool(float(line[ia]))) except IOError: cases = cases[:c] break # point the first dot points = [] trails = [] rejects = [] clr = ax._get_lines.prop_cycler for case in cases: c = next(clr)['color'] point, = ax.plot3D([data[case]['x'][0]],[data[case]['y'][0]],[data[case]['z'][0]],color=c,alpha=0.9,marker='${}$'.format(case)) trail, = ax.plot3D([data[case]['x'][0]],[data[case]['y'][0]],[data[case]['z'][0]],'.-',color=c,alpha=0.9) reject, = ax.plot3D([],[],[],'x',color=c,alpha=0.9) points.append(point) trails.append(trail) rejects.append(reject) def updatePoint(n,data,points,trails,rejects): """ Function to be called to update the animation points, one iteration at a time. @ In, n, int, the iteration to use @ In, data, dict, all the data collected from the RAVEN output @ In, points, list, plotted points in the animation @ In, trails, list, currently unused, finite number of trailing points to track in animation @ In, rejects, list, rejected samples from evaluations @ Out, point, matplotlib.pyplot line, last plotted point object """ print('Animating iteration',n) for c,case in enumerate(cases): point = points[c] trail = trails[c] reject = rejects[c] N = len(data[case]['x']) # truncate data x = np.array(data[case]['x'][:n+1] if n+1 < N else data[case]['x']) y = np.array(data[case]['y'][:n+1] if n+1 < N else data[case]['y']) z = np.array(data[case]['z'][:n+1] if n+1 < N else data[case]['z']) a = np.array(data[case]['a'][:n+1] if n+1 < N else data[case]['a']) # split data into accepted, rejected points xA = np.atleast_1d(x[a]) yA = np.atleast_1d(y[a]) zA = np.atleast_1d(z[a]) xR = np.atleast_1d(x[np.logical_not(a)]) yR = np.atleast_1d(y[np.logical_not(a)]) zR = np.atleast_1d(z[np.logical_not(a)]) try: point.set_data([xA[-1]],[yA[-1]]) point.set_3d_properties(zA[-1]) trail.set_data(xA,yA) trail.set_3d_properties(zA) reject.set_data(xR,yR) reject.set_3d_properties(zR) except IndexError: continue ax.set_title('iteration {}'.format(n),loc='center',pad=20) return point ani=animation.FuncAnimation(fig,updatePoint,max(len(data[case]['x']) for case in cases),fargs=(data,points,trails,rejects),interval=100,repeat_delay=3000) Writer = animation.writers['ffmpeg'] writer = Writer(fps=15,bitrate=1800) ani.save('path3d.mp4',writer=writer)
[ 2, 15069, 2177, 12350, 13485, 6682, 10302, 11, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13,...
2.40456
1,886
# Coldwallet encryption related functions. This is the heart of coldwallet. from __future__ import absolute_import, division, print_function import base64 import math import os import coldwallet.aes import pylibscrypt def disable_randomness(): '''Make the random number generator produce deterministic (ie. non-random) output. This is used for internal testing only, and must never be used otherwise! A warning is printed. ''' import random import sys print('', file=sys.stderr) print('-- coldwallet running in test mode - random number generation disabled --', file=sys.stderr) print('', file=sys.stderr) if sys.hexversion >= 0x03000000: random.seed(a=0, version=1) else: random.seed(a=0) os.urandom = fakerandom def generate_random_string(bits): '''Generate a random string with a given number of bits. If the number of bits is not divisible by 8 then pad with 0s. ''' assert bits >= 1, "Cannot create 0 bit random strings" stringbytes = int(math.ceil(bits / 8)) rand_string = os.urandom(stringbytes) zero_padding = stringbytes * 8 - bits if zero_padding: mask = 0x100 - (2 ** zero_padding) rand_string = rand_string[:-1] + bytes(bytearray((ord(rand_string[-1:]) & mask,))) return rand_string def encrypt_secret_key(secret, coldkey, public_address, scrypt_N=2**14, scrypt_p=1): '''Encrypt a secret exponent using an individual symmetric key. The symmetric key is generated from the shared coldwallet key (given as byte string) and the public bitcoin address (given in human readable format) using the memory-hard scrypt hash. The result is returned in base64 encoding. ''' # Generate a 256 bit symmetric key from the coldwallet key and the public bitcoin address symmetric_key = pylibscrypt.scrypt(coldkey, public_address.encode('ascii'), olen=32, N=scrypt_N, p=scrypt_p) # Encrypt the secret exponent with the symmetric key encrypted_secret = coldwallet.aes.encrypt_block(secret, symmetric_key) # Base64 encode the result return base64.b64encode(encrypted_secret).decode('ascii') def decrypt_secret_key(code, coldkey, public_address, scrypt_N=2**14, scrypt_p=1): '''Decrypt a secret exponent, given in base64 encoding, using an individual symmetric key. The symmetric key is generated as above. The result is returned as a byte string. ''' # Base64 decode the input code = base64.b64decode(code.encode('ascii')) # Generate a 256 bit symmetric key from the coldwallet key and the public bitcoin address symmetric_key = pylibscrypt.scrypt(coldkey, public_address.encode('ascii'), olen=32, N=scrypt_N, p=scrypt_p) # Decrypt the secret exponent with the symmetric key secret = coldwallet.aes.decrypt_block(code, symmetric_key) return secret
[ 2, 10250, 44623, 15835, 3519, 5499, 13, 770, 318, 262, 2612, 286, 4692, 44623, 13, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 11748, 2779, 2414, 198, 11748, 10688, 198, 11748, 286...
3.103795
896
# pylint: disable=duplicate-code # -*- coding: utf-8 -*- # # ramstk.models.action.record.py is part of The RAMSTK Project # # All rights reserved. # Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com """RAMSTKAction Table Module.""" # Standard Library Imports from datetime import date, timedelta # Third Party Imports from sqlalchemy import Column, Date, ForeignKeyConstraint, Integer, String from sqlalchemy.orm import relationship # RAMSTK Package Imports from ramstk.db import RAMSTK_BASE from ramstk.models import RAMSTKBaseRecord class RAMSTKActionRecord(RAMSTK_BASE, RAMSTKBaseRecord): """Class to represent table ramstk_action in the RAMSTK Program database. This table shares a Many-to-One relationship with ramstk_cause. """ __defaults__ = { "action_recommended": "", "action_category": "", "action_owner": "", "action_due_date": date.today() + timedelta(days=30), "action_status": "", "action_taken": "", "action_approved": 0, "action_approve_date": date.today() + timedelta(days=30), "action_closed": 0, "action_close_date": date.today() + timedelta(days=30), } __tablename__ = "ramstk_action" __table_args__ = ( ForeignKeyConstraint( [ "fld_revision_id", "fld_hardware_id", "fld_mode_id", "fld_mechanism_id", "fld_cause_id", ], [ "ramstk_cause.fld_revision_id", "ramstk_cause.fld_hardware_id", "ramstk_cause.fld_mode_id", "ramstk_cause.fld_mechanism_id", "ramstk_cause.fld_cause_id", ], ), {"extend_existing": True}, ) revision_id = Column("fld_revision_id", Integer, primary_key=True, nullable=False) hardware_id = Column( "fld_hardware_id", Integer, primary_key=True, default=-1, nullable=False ) mode_id = Column("fld_mode_id", Integer, primary_key=True, nullable=False) mechanism_id = Column("fld_mechanism_id", Integer, primary_key=True, nullable=False) cause_id = Column( "fld_cause_id", Integer, primary_key=True, nullable=False, unique=True ) action_id = Column( "fld_action_id", Integer, primary_key=True, autoincrement=True, nullable=False ) action_recommended = Column( "fld_action_recommended", String, default=__defaults__["action_recommended"] ) action_category = Column( "fld_action_category", String(512), default=__defaults__["action_category"] ) action_owner = Column( "fld_action_owner", String(512), default=__defaults__["action_owner"] ) action_due_date = Column( "fld_action_due_date", Date, default=__defaults__["action_due_date"] ) action_status = Column( "fld_action_status", String(512), default=__defaults__["action_status"] ) action_taken = Column( "fld_action_taken", String, default=__defaults__["action_taken"] ) action_approved = Column( "fld_action_approved", Integer, default=__defaults__["action_approved"] ) action_approve_date = Column( "fld_action_approve_date", Date, default=__defaults__["action_approve_date"] ) action_closed = Column( "fld_action_closed", Integer, default=__defaults__["action_closed"] ) action_close_date = Column( "fld_action_close_date", Date, default=__defaults__["action_close_date"] ) # Define the relationships to other tables in the RAMSTK Program database. cause = relationship("RAMSTKCauseRecord", back_populates="action") # type: ignore is_mode = False is_mechanism = False is_cause = False is_control = False is_action = True def get_attributes(self): """Retrieve current values of the RAMSTKAction data model attributes. :return: {cause_id, action_id, action_recommended, action_category, action_owner, action_due_date, action_status, action_taken, action_approved, action_approved_date, action_closed, action_closed_date} pairs. :rtype: dict """ _attributes = { "cause_id": self.cause_id, "action_id": self.action_id, "action_recommended": self.action_recommended, "action_category": self.action_category, "action_owner": self.action_owner, "action_due_date": self.action_due_date, "action_status": self.action_status, "action_taken": self.action_taken, "action_approved": self.action_approved, "action_approve_date": self.action_approve_date, "action_closed": self.action_closed, "action_close_date": self.action_close_date, } return _attributes
[ 2, 279, 2645, 600, 25, 15560, 28, 646, 489, 5344, 12, 8189, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 15770, 301, 74, 13, 27530, 13, 2673, 13, 22105, 13, 9078,...
2.256714
2,197
# # Vortex OpenSplice # # This software and documentation are Copyright 2006 to TO_YEAR ADLINK # Technology Limited, its affiliated companies and licensors. All rights # reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ''' Created on Dec 22, 2017 @author: prismtech ''' import unittest import ddsutil import enum if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
[ 2, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 49790, 4946, 26568, 501, 198, 2, 198, 2, 220, 220, 770, 3788, 290, 10314, 389, 15069, 4793, 284, ...
3.099359
312
"""Contain the models related to the app ``users``.""" from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from teamspirit.users.managers import UserManager
[ 37811, 4264, 391, 262, 4981, 3519, 284, 262, 598, 7559, 18417, 15506, 526, 15931, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 8692, 62, 7220, 1330, 27741, 14881, 12982, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, ...
3.541667
96
"""Process AWOS METAR file""" from __future__ import print_function import re import sys import os import datetime import ftplib import subprocess import tempfile from io import StringIO from pyiem import util INCOMING = "/mesonet/data/incoming" def fetch_files(): """Fetch files """ props = util.get_properties() fn = "%s/iaawos_metar.txt" % (INCOMING, ) try: ftp = ftplib.FTP('165.206.203.34') except TimeoutError as _exp: print("process_idot_awos FTP server timeout error") sys.exit() ftp.login('rwis', props['rwis_ftp_password']) ftp.retrbinary('RETR METAR.txt', open(fn, 'wb').write) ftp.close() return fn def main(): """Go Main""" fn = fetch_files() utc = datetime.datetime.utcnow().strftime("%Y%m%d%H%M") data = {} # Sometimes, the file gets gobbled it seems for line in open(fn, 'rb'): line = line.decode('utf-8', 'ignore') match = re.match("METAR K(?P<id>[A-Z1-9]{3})", line) if not match: continue gd = match.groupdict() data[gd['id']] = line sio = StringIO() sio.write("\001\r\r\n") sio.write(("SAUS00 KISU %s\r\r\n" ) % (datetime.datetime.utcnow().strftime("%d%H%M"), )) sio.write("METAR\r\r\n") for sid in data: sio.write('%s=\r\r\n' % (data[sid].strip().replace("METAR ", ""), )) sio.write("\003") sio.seek(0) (tmpfd, tmpname) = tempfile.mkstemp() os.write(tmpfd, sio.getvalue().encode('utf-8')) os.close(tmpfd) proc = subprocess.Popen(("/home/ldm/bin/pqinsert -i -p 'data c %s " "LOCDSMMETAR.dat LOCDSMMETAR.dat txt' %s" ) % (utc, tmpname), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdout, stderr) = proc.communicate() os.remove(tmpname) if stdout != b"" or stderr is not None: print("process_idot_awos\nstdout: %s\nstderr: %s" % (stdout, stderr)) if __name__ == '__main__': main()
[ 37811, 18709, 14356, 2640, 31243, 1503, 2393, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 11748, 10117, 489, 571, 198, 11748, 850, 14681, 1...
2.036965
1,028
from django.db import models from django.core.exceptions import ObjectDoesNotExist
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 628, 628, 198 ]
3.48
25
S = input() result = 0 for s in S.split('+'): if s.count('0') == 0: result += 1 print(result)
[ 50, 796, 5128, 3419, 198, 198, 20274, 796, 657, 198, 1640, 264, 287, 311, 13, 35312, 10786, 10, 6, 2599, 198, 220, 611, 264, 13, 9127, 10786, 15, 11537, 6624, 657, 25, 198, 220, 220, 220, 1255, 15853, 352, 198, 4798, 7, 20274, 8, ...
2.244444
45
import os CACHE_DIRECTORY = os.path.join(os.path.expanduser('~'), os.path.join('temp', 'cache')) RESULT_DIRECTORY = os.path.join(os.path.expanduser('~'), os.path.join('temp', 'result')) # CACHE_DIRECTORY = 'cache' # RESULT_DIRECTORY = 'result'
[ 11748, 28686, 628, 198, 34, 2246, 13909, 62, 17931, 23988, 15513, 796, 28686, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 11201, 392, 7220, 10786, 93, 33809, 28686, 13, 6978, 13, 22179, 10786, 29510, 3256, 705, 23870, 6, 4008, 198, 195...
2.411765
102
import os import yaml from launch import LaunchDescription from launch_ros.actions import Node from launch.actions import ExecuteProcess, DeclareLaunchArgument from launch.substitutions import Command, FindExecutable, LaunchConfiguration, PathJoinSubstitution from ament_index_python.packages import get_package_share_directory from launch_ros.substitutions import FindPackageShare import xacro #sudo apt install ros-foxy-xacro
[ 11748, 28686, 198, 11748, 331, 43695, 198, 6738, 4219, 1330, 21225, 11828, 198, 6738, 4219, 62, 4951, 13, 4658, 1330, 19081, 198, 6738, 4219, 13, 4658, 1330, 8393, 1133, 18709, 11, 16691, 533, 38296, 28100, 1713, 198, 6738, 4219, 13, 72...
3.873874
111
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' This is a plugin for the Sublime Text Editor https://www.sublimetext.com/ Replace all occurences of the currently selected text in the document with an incrementing number. Some options are provided: * Start with an offset * Use fixed number of digits (fill up with leading 0s) * Define a preceding text in front of the iterator ''' import sublime, sublime_plugin import re SETTINGS_FILE = "SimpleIncrementor.sublime-settings" EXPHELP = '''Use key:value pairs separated by a blank character to pass options. Valid Keys: digits, offset, prectext, step Example: digits:5 offset:10 To re-show this dialogue, enable show_help in the Plugin Settings. ''' class SimpleIncrementExpertParseCommand(sublime_plugin.TextCommand): ''' Take the arguments from expert mode and create a dictionary from it to call the main function ''' class SimpleIncrementExpertCommand(sublime_plugin.TextCommand): ''' Get the user input for expert-mode execution ''' class SimpleIncrementCommand(sublime_plugin.TextCommand): ''' The main component for doing the replacement ''' class SimpleIncrementDigitsCommand(sublime_plugin.TextCommand): ''' Fill up the left part with leading zeros to match the given number of digits ''' prectext = '' class SimpleIncrementPrectextCommand(sublime_plugin.TextCommand): ''' Get the preceding text from the user ''' class SimpleIncrementPrectextDigitsCommand(sublime_plugin.TextCommand): ''' Combination of preceding text and fill-up with leading zeros ''' class SimpleIncrementOffsetCommand(sublime_plugin.TextCommand): ''' Start incrementation with an offset '''
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 7061, 6, 198, 1212, 318, 257, 13877, 329, 262, 3834, 27299, 8255, 12058, 198, 5450, 1378, 2503, 13, 7266, 2475, 316, 2302, ...
3.412121
495
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ import urllib3 import shutil import zipfile from .hash import getFileSha256Hash import os PILLOW_MODULE_DOWNLOAD_FILE_NAME = "pillow_layer_module.zip" def downloadPillowLayerFile(directory: str, url: str, file_hash: str): """ Download the Pillow layer :param directory: Target directory to store the downloaded file :param url: The url for the download :param file_hash: The verification sha256 hash :return: None """ if not os.path.exists(directory): os.mkdir(directory) http = urllib3.PoolManager() try: with http.request('GET', url, preload_content=False) as r, open( f"{directory}/{PILLOW_MODULE_DOWNLOAD_FILE_NAME}", 'wb') as f: shutil.copyfileobj(r, f) except Exception as err: raise IOError(err) if getFileSha256Hash(f"{directory}/{PILLOW_MODULE_DOWNLOAD_FILE_NAME}") != file_hash: os.unlink(f"{directory}/{PILLOW_MODULE_DOWNLOAD_FILE_NAME}") raise ImportError(f"Bad Pillow module file sha256 signature : {url}") try: with zipfile.ZipFile(f"{directory}/{PILLOW_MODULE_DOWNLOAD_FILE_NAME}", 'r') as f: f.extractall(f"{directory}/python") except Exception as err: raise IOError(err) os.unlink(f"{directory}/{PILLOW_MODULE_DOWNLOAD_FILE_NAME}")
[ 37811, 198, 15269, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 4303, 36227, 12, 34156, 12, 33234, 7483, 25, 17168, 12, 15, 198, 37811, 198, 198, 11748, 2956, 297, 571, 18, 198, 11748, 4423, 346, 198...
2.441581
582
import json from types import SimpleNamespace import pytest from mock import patch from backend.lambdas.settings import handlers pytestmark = [pytest.mark.unit, pytest.mark.api, pytest.mark.settings] @patch("backend.lambdas.settings.handlers.get_config")
[ 11748, 33918, 198, 6738, 3858, 1330, 17427, 36690, 10223, 198, 198, 11748, 12972, 9288, 198, 6738, 15290, 1330, 8529, 198, 198, 6738, 30203, 13, 2543, 17457, 292, 13, 33692, 1330, 32847, 198, 198, 9078, 9288, 4102, 796, 685, 9078, 9288, ...
3.209877
81
from django.apps import AppConfig from django.conf import settings
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 628, 628 ]
3.888889
18
# Copyright 2018 SUSE Linux GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystoneauth1.identity.v3 import base __all__ = ('ApplicationCredentialMethod', 'ApplicationCredential') class ApplicationCredentialMethod(base.AuthMethod): """Construct a User/Passcode based authentication method. :param string application_credential_secret: Application credential secret. :param string application_credential_id: Application credential id. :param string application_credential_name: The name of the application credential, if an ID is not provided. :param string username: Username for authentication, if an application credential ID is not provided. :param string user_id: User ID for authentication, if an application credential ID is not provided. :param string user_domain_id: User's domain ID for authentication, if an application credential ID is not provided. :param string user_domain_name: User's domain name for authentication, if an application credential ID is not provided. """ _method_parameters = ['application_credential_secret', 'application_credential_id', 'application_credential_name', 'user_id', 'username', 'user_domain_id', 'user_domain_name'] class ApplicationCredential(base.AuthConstructor): """A plugin for authenticating with an application credential. :param string auth_url: Identity service endpoint for authentication. :param string application_credential_secret: Application credential secret. :param string application_credential_id: Application credential ID. :param string application_credential_name: Application credential name. :param string username: Username for authentication. :param string user_id: User ID for authentication. :param string user_domain_id: User's domain ID for authentication. :param string user_domain_name: User's domain name for authentication. :param bool reauthenticate: Allow fetching a new token if the current one is going to expire. (optional) default True """ _auth_method_class = ApplicationCredentialMethod
[ 2, 15069, 2864, 311, 19108, 7020, 402, 2022, 39, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 92...
2.7042
1,119
import numpy import os.path from amuse.test.amusetest import get_path_to_results try: from matplotlib import pyplot HAS_MATPLOTLIB = True from amuse.plot import plot, semilogy, xlabel, ylabel, loglog except ImportError: HAS_MATPLOTLIB = False from amuse.units import units from amuse.units import generic_unit_system from amuse.units import nbody_system from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.support.exceptions import AmuseException from amuse.community.mesa.interface import MESA from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.star_to_sph import * from amuse.datamodel import Particles from amuse.datamodel import Grid from prepare_figure import single_frame, figure_frame, set_tickmarks from distinct_colours import get_distinct def hydro_plot(view, hydro_code, image_size, time, figname): """ Produce a series of images suitable for conversion into a movie. view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) time: current hydro code time """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe \ = hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-9 | units.g / units.cm**3 max_rho = 1.0e-5 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr/min_v**2)) / numpy.log((max_v**2/min_v**2)) log_rho = numpy.log((rho/min_rho)) / numpy.log((max_rho/min_rho)) log_E = numpy.log((E/min_E)) / numpy.log((max_E/min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))))).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis = 2) pyplot.figure(figsize = (image_size[0]/100.0, image_size[1]/100.0), dpi = 100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi = 100, facecolor='k', edgecolor='k') print "Saved hydroplot at time", time, "in file" print ' ', figname pyplot.close() if __name__ == "__main__": print "Test run to mimic a supernova in SPH" print "Details:" print " A high-mass star is evolved to the supergiant phase using MESA." print " Then it is converted to SPH particles using", \ "convert_stellar_model_to_SPH" print " (with a non-SPH 'core' particle).", \ "Finally the internal energies of" print " the innermost particles are increased so that the star gains the" print " 10^51 erg released in a typical supernova explosion." run_supernova()
[ 11748, 299, 32152, 198, 11748, 28686, 13, 6978, 198, 6738, 26072, 13, 9288, 13, 25509, 316, 395, 1330, 651, 62, 6978, 62, 1462, 62, 43420, 198, 28311, 25, 198, 220, 220, 220, 422, 2603, 29487, 8019, 1330, 12972, 29487, 198, 220, 220, ...
2.175502
1,943
# -*- coding: utf-8 -*- import os import click from .._internal_utils import _config_utils from . import remote from . import branch from . import commit from . import blob @click.group() def cli(): """ModelDB versioning CLI for snapshotting and tracking model ingredients.""" pass @click.command() def init(): """ Create a Verta config file in the current directory. Running verta init in an existing repository is safe. It will not overwrite things that are already there. """ for config_filename in _config_utils.CONFIG_FILENAMES: if os.path.isfile(config_filename): config_filepath = os.path.abspath(config_filename) click.echo("found existing config file {}".format(config_filepath)) return config_filepath = _config_utils.create_empty_config_file('.') click.echo("initialized empty config file {}".format(config_filepath)) cli.add_command(init) cli.add_command(remote.remote) cli.add_command(branch.branch) cli.add_command(branch.checkout) cli.add_command(branch.log) cli.add_command(commit.add) cli.add_command(commit.rm) cli.add_command(commit.commit) cli.add_command(commit.tag) cli.add_command(commit.status) cli.add_command(commit.diff) cli.add_command(blob.pull) cli.add_command(blob.import_, name="import")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 198, 11748, 3904, 198, 198, 6738, 11485, 62, 32538, 62, 26791, 1330, 4808, 11250, 62, 26791, 198, 198, 6738, 764, 1330, 6569, 198, 6738, 764, 133...
2.814103
468
from oelint_adv.cls_rule import Rule from oelint_parser.cls_item import Variable
[ 6738, 267, 417, 600, 62, 32225, 13, 565, 82, 62, 25135, 1330, 14330, 198, 6738, 267, 417, 600, 62, 48610, 13, 565, 82, 62, 9186, 1330, 35748, 628 ]
2.928571
28
import random import unittest from clovars.scientific import brownian_motion, bounded_brownian_motion, reflect_around_interval, triangular_wave class TestBrownian(unittest.TestCase): """Class representing unit-tests for clovars.scientific.brownian_motion module.""" def test_bounded_brownian_motion_returns_values_between_bounds(self) -> None: """ Tests whether the "bounded_brownian_motion" function always returns values between the lower and upper bounds used. """ for _ in range(30): current_value, scale = random.random(), random.random() lower_bound, upper_bound = random.random(), random.random() + 1 value = bounded_brownian_motion( current_value=current_value, scale=scale, lower_bound=lower_bound, upper_bound=upper_bound, ) with self.subTest(value=value, lower_bound=lower_bound, upper_bound=upper_bound): self.assertGreaterEqual(value, lower_bound) self.assertLessEqual(value, upper_bound) def test_brownian_motion_returns_values_close_to_the_input_value(self) -> None: """Tests whether the "brownian_motion" function returns new values within ~ 7 SDs of the input value.""" for current_value in [0, 17.98, 999, 312, -73.4]: for scale in [0.2, 0.5, 0.8]: tolerance = 7 * scale with self.subTest(current_value=current_value, scale=scale, tolerance=tolerance): result = brownian_motion(current_value=current_value, scale=scale) self.assertGreaterEqual(result, current_value - tolerance) self.assertLessEqual(result, current_value + tolerance) def test_brownian_motion_returns_input_value_if_scale_is_one(self) -> None: """Tests whether the "brownian_motion" function returns the exact input value if the scale argument is one.""" for _ in range(30): current_value = random.random() with self.subTest(current_value=current_value): result = brownian_motion(current_value=current_value, scale=1.0) self.assertEqual(current_value, result) def test_reflect_around_interval_returns_input_value_reflected_between_bounds(self) -> None: """ Tests whether the "reflect_around_interval" function returns the input value after reflecting it between two bounds. """ reflect_test_cases = [ (0.5, 0.0, 1.0, 0.5), (1.5, 0.0, 1.0, 0.5), (-.5, 0.0, 1.0, 0.5), (3.6, 2.0, 3.0, 2.4), (3.2, 1.0, 3.0, 2.8), (6.4, 4.0, 6.0, 5.6), (10., 5.0, 8.0, 6.0), (10., 1.0, 3.0, 2.0), ] for x, lower_bound, upper_bound, expected_x in reflect_test_cases: with self.subTest(x=x, lower_bound=lower_bound, upper_bound=upper_bound, expected_x=expected_x): actual_x = reflect_around_interval(x=x, lower_bound=lower_bound, upper_bound=upper_bound) self.assertAlmostEqual(expected_x, actual_x) def test_triangular_wave_behaves_as_a_triangular_wave(self) -> None: """Tests whether the "triangular_wave" function returns values as expected by a triangular wave function.""" triangular_test_cases = [ (0.0, 1.0, 1.0, 0.0), (.25, 1.0, 1.0, 1.0), (.50, 1.0, 1.0, 0.0), (.75, 1.0, 1.0, -1.), (1.0, 1.0, 1.0, 0.0), ] for x, period, amplitude, expected_y in triangular_test_cases: with self.subTest(x=x, period=period, amplitude=amplitude, expected_y=expected_y): actual_y = triangular_wave(x=x, period=period, amplitude=amplitude) self.assertEqual(expected_y, actual_y) def test_triangular_wave_scales_with_period(self) -> None: """Tests whether the "triangular_wave" function scales with its period argument properly.""" triangular_test_cases = [ (.25, 1.0, 1.0, 1.0), (.25, 2.0, 1.0, 0.5), (.25, 4.0, 1.0, .25), (.25, 0.5, 1.0, 0.0), ] for x, period, amplitude, expected_y in triangular_test_cases: with self.subTest(x=x, period=period, amplitude=amplitude, expected_y=expected_y): actual_y = triangular_wave(x=x, period=period, amplitude=amplitude) self.assertEqual(expected_y, actual_y) def test_triangular_wave_scales_with_amplitude(self) -> None: """Tests whether the "triangular_wave" function scales with its amplitude argument properly.""" triangular_test_cases = [ (0.25, 1.0, 1.0, 1.0), (0.25, 1.0, 2.0, 2.0), (0.25, 1.0, 4.0, 4.0), (0.25, 1.0, 5.0, 5.0), (0.75, 1.0, 1.0, -1.), (0.75, 1.0, 2.0, -2.), (0.75, 1.0, 4.0, -4.), (0.75, 1.0, 5.0, -5.), ] for x, period, amplitude, expected_y in triangular_test_cases: with self.subTest(x=x, period=period, amplitude=amplitude, expected_y=expected_y): actual_y = triangular_wave(x=x, period=period, amplitude=amplitude) self.assertEqual(expected_y, actual_y) if __name__ == '__main__': unittest.main()
[ 11748, 4738, 198, 11748, 555, 715, 395, 198, 198, 6738, 537, 709, 945, 13, 41355, 1330, 7586, 666, 62, 38714, 11, 49948, 62, 33282, 666, 62, 38714, 11, 4079, 62, 14145, 62, 3849, 2100, 11, 46963, 62, 19204, 628, 198, 4871, 6208, 206...
2.094163
2,570
""" A nondeterministic transition function """ import copy from typing import Set from .state import State from .symbol import Symbol class NondeterministicTransitionFunction(object): """ A nondeterministic transition function in a finite automaton. The difference with a deterministic transition is that the return value is a set of States """ def add_transition(self, s_from: State, symb_by: Symbol, s_to: State) -> int: """ Adds a new transition to the function Parameters ---------- s_from : :class:`~pyformlang.finite_automaton.State` The source state symb_by : :class:`~pyformlang.finite_automaton.Symbol` The transition symbol s_to : :class:`~pyformlang.finite_automaton.State` The destination state Returns -------- done : int Always 1 """ if s_from in self._transitions: if symb_by in self._transitions[s_from]: self._transitions[s_from][symb_by].add(s_to) else: self._transitions[s_from][symb_by] = {s_to} else: self._transitions[s_from] = dict() self._transitions[s_from][symb_by] = {s_to} return 1 def remove_transition(self, s_from: State, symb_by: Symbol, s_to: State) -> int: """ Removes a transition to the function Parameters ---------- s_from : :class:`~pyformlang.finite_automaton.State` The source state symb_by : :class:`~pyformlang.finite_automaton.Symbol` The transition symbol s_to : :class:`~pyformlang.finite_automaton.State` The destination state Returns -------- done : int 1 is the transition was found, 0 otherwise """ if s_from in self._transitions and \ symb_by in self._transitions[s_from] and \ s_to in self._transitions[s_from][symb_by]: self._transitions[s_from][symb_by].remove(s_to) return 1 return 0 def get_number_transitions(self) -> int: """ Gives the number of transitions describe by the function Returns ---------- n_transitions : int The number of transitions """ counter = 0 for s_from in self._transitions: for symb_by in self._transitions[s_from]: counter += len(self._transitions[s_from][symb_by]) return counter def __call__(self, s_from: State, symb_by: Symbol=None) -> Set[State]: """ Calls the transition function as a real function Parameters ---------- s_from : :class:`~pyformlang.finite_automaton.State` The source state symb_by : :class:`~pyformlang.finite_automaton.Symbol` The transition symbol Returns ---------- s_from : :class:`~pyformlang.finite_automaton.State` or None The destination state or None if it does not exists """ if s_from in self._transitions: if symb_by is not None: if symb_by in self._transitions[s_from]: return self._transitions[s_from][symb_by] else: return self._transitions[s_from].items() return set() def is_deterministic(self): """ Whether the transition function is deterministic Returns ---------- is_deterministic : bool Whether the function is deterministic """ for s_from in self._transitions: for symb in self._transitions[s_from]: if len(self._transitions[s_from][symb]) > 1: return False return True def get_edges(self): """ Gets the edges Returns ---------- edges : generator of (:class:`~pyformlang.finite_automaton.State`, \ :class:`~pyformlang.finite_automaton.Symbol`,\ :class:`~pyformlang.finite_automaton.State`) A generator of edges """ for state in self._transitions: for symbol in self._transitions[state]: for next_state in self._transitions[state][symbol]: yield state, symbol, next_state
[ 37811, 198, 32, 30745, 2357, 49228, 6801, 2163, 198, 37811, 198, 11748, 4866, 198, 6738, 19720, 1330, 5345, 198, 198, 6738, 764, 5219, 1330, 1812, 198, 6738, 764, 1837, 23650, 1330, 38357, 628, 198, 4871, 399, 623, 2357, 49228, 8291, 65...
2.168495
2,006
import contextlib import os import shelve from .registry import PlatformRegistry
[ 11748, 4732, 8019, 198, 11748, 28686, 198, 11748, 7497, 303, 198, 6738, 764, 2301, 4592, 1330, 19193, 8081, 4592, 628, 628, 198 ]
3.863636
22
from datetime import time from typing import List, Optional from pydantic import BaseModel, Field from papi_sdk.models.base import BaseResponse
[ 6738, 4818, 8079, 1330, 640, 198, 6738, 19720, 1330, 7343, 11, 32233, 198, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 11, 7663, 198, 198, 6738, 279, 15042, 62, 21282, 74, 13, 27530, 13, 8692, 1330, 7308, 31077, 628, 628, 628, 628,...
3.333333
51
#!/usr/bin/env python # -*-coding:utf-8-*- # net login from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import codecs import os driver = webdriver.PhantomJS() #driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver') driver.get('https://gw.ict.ac.cn/srun_portal_pc.php?ac_id=1&') name = driver.find_element_by_name("username") name.send_keys('user_key') password = driver.find_element_by_id('password') password.send_keys('user_value') password.send_keys(Keys.RETURN) time.sleep(1) file_object = codecs.open("dump.html", "w", "utf-8") html = driver.page_source file_object.write(html) driver.quit()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 66, 7656, 25, 40477, 12, 23, 12, 9, 12, 198, 198, 2, 2010, 17594, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, ...
2.652
250
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # less required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """The PDarts model file.""" import mindspore.nn as nn import mindspore.ops as P from src.operations import FactorizedReduce, ReLUConvBN, OPS from src.my_utils import drop_path class Module(nn.Cell): """ The module of PDarts. """ def _compile(self, C, op_names, indices, concat, reduction): """ Combine the functions of model. """ assert len(op_names) == len(indices) self._steps = len(op_names) // 2 self._concat = concat self.multiplier = len(concat) self._ops = nn.CellList() for name, index in zip(op_names, indices): stride = 2 if reduction and index < 2 else 1 op = OPS[name](C, stride, True) self._ops += [op] self._indices = indices def construct(self, s0, s1, drop_prob, layer_mask): """ Do the module. """ s0 = self.preprocess0(s0) s1 = self.preprocess1(s1) concat_result = None states = [s0, s1] for i in range(self._steps): h1 = states[self._indices[2 * i]] h2 = states[self._indices[2 * i + 1]] op1 = self._ops[2 * i] op2 = self._ops[2 * i + 1] h1 = op1(h1) h2 = op2(h2) if self.training and drop_prob > 0.: h1 = drop_path(self.div, self.mul, h1, drop_prob, layer_mask[i * 2]) h2 = drop_path(self.div, self.mul, h2, drop_prob, layer_mask[i * 2 + 1]) s = h1 + h2 states.append(s) if len(states) - 1 == self.concat_start + 1 and len(states) - 1 <= self.concat_end: concat_result = self.concat_1( (states[len(states) - 2], states[len(states) - 1])) elif len(states) - 1 > self.concat_start + 1 and len(states) - 1 <= self.concat_end: concat_result = self.concat_1( (concat_result, states[len(states) - 1])) return concat_result class AuxiliaryHeadCIFAR(nn.Cell): """ Define the Auxiliary Head. """ def __init__(self, C, num_classes): """assuming input size 8x8""" super(AuxiliaryHeadCIFAR, self).__init__() self.features = nn.SequentialCell( nn.ReLU(), nn.AvgPool2d(5, stride=3), # image size = 2 x 2 nn.Conv2d(C, 128, 1, pad_mode='pad', has_bias=False), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 768, 2, pad_mode='pad', has_bias=False), nn.BatchNorm2d(768), nn.ReLU() ) self.reshape = P.Reshape() self.classifier = nn.Dense(768, num_classes) class NetworkCIFAR(nn.Cell): """ The PDarts model define """ def construct(self, x): """ Do the model. """ logits_aux = None s0 = s1 = self.stem(x) for i in range(len(self.cell_list)): cell = self.cell_list[i] s0, s1 = s1, cell(s0, s1, self.drop_path_prob, self.epoch_mask[i]) if i == 2 * self._layers // 3: if self._auxiliary and self.training: logits_aux = self.auxiliary_head(s1) out = self.global_pooling(s1, (2, 3)) out = self.reshape(out, (out.shape[0], -1)) logits = self.classifier(out) if self._auxiliary and self.training: return logits, logits_aux return logits
[ 2, 15069, 33160, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
2.077805
2,005
from django.shortcuts import render from rest_framework.decorators import api_view from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import status from rest_framework.response import Response from .models import * from .serializers import * from django.core import serializers from rest_framework_jwt.utils import jwt_decode_handler import jwt from rest_framework.views import APIView from rest_framework.generics import ListAPIView, RetrieveAPIView from rest_framework.pagination import PageNumberPagination from django_filters.rest_framework import DjangoFilterBackend from django.utils.decorators import method_decorator from rest_framework import viewsets
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 40391, 62, 1177, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 449, 1559, 31077, 198, 6738, 42625, 14208, 13, 33...
3.627451
204
if __name__ == '__main__': expected1 = {'c': 2, 'b': 2, 'a': 1} expected2 = {'a': 1, 'b': 2, 'c': 2} a = change(expected1) print(expected1 == a)
[ 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220, 220, 220, 2938, 16, 796, 1391, 6, 66, 10354, 362, 11, 705, 65, 10354, 362, 11, 705, 64, 10354, 352, 92, 198, 220, 220, 220, 2938, 17, 796, 1391, 6, 64, 103...
2.075949
79
# -*- coding: utf-8 -*- r""" Finite State Machines, Automata, Transducers This module adds support for finite state machines, automata and transducers. See classes :class:`Automaton` and :class:`Transducer` (or the more general class :class:`FiniteStateMachine`) and the :ref:`examples <finite_state_machine_examples>` below for details creating one. Contents ======== :class:`FiniteStateMachine` and derived classes :class:`Transducer` and :class:`Automaton` ------------------------------------------------------------------------------------------ Accessing parts of a finite state machine ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.state` | Get a state by its label :meth:`~FiniteStateMachine.states` | List of states :meth:`~FiniteStateMachine.iter_states` | Iterator over the states :meth:`~FiniteStateMachine.initial_states` | List of initial states :meth:`~FiniteStateMachine.iter_initial_states` | Iterator over initial states :meth:`~FiniteStateMachine.final_states` | List of final states :meth:`~FiniteStateMachine.iter_final_states` | Iterator over final states :meth:`~FiniteStateMachine.transition` | Get a transition by its states and labels :meth:`~FiniteStateMachine.transitions` | List of transitions :meth:`~FiniteStateMachine.iter_transitions` | Iterator over the transitions :meth:`~FiniteStateMachine.predecessors` | List of predecessors of a state :meth:`~FiniteStateMachine.induced_sub_finite_state_machine` | Induced sub-machine :meth:`~FiniteStateMachine.accessible_components` | Accessible components :meth:`~FiniteStateMachine.final_components` | Final components (connected components which cannot be left again) (Modified) Copies ^^^^^^^^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.empty_copy` | Returns an empty deep copy :meth:`~FiniteStateMachine.deepcopy` | Returns a deep copy :meth:`~FiniteStateMachine.relabeled` | Returns a relabeled deep copy Manipulation ^^^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.add_state` | Add a state :meth:`~FiniteStateMachine.add_states` | Add states :meth:`~FiniteStateMachine.delete_state` | Delete a state :meth:`~FiniteStateMachine.add_transition` | Add a transition :meth:`~FiniteStateMachine.add_transitions_from_function` | Add transitions :attr:`~FiniteStateMachine.on_duplicate_transition` | Hook for handling duplicate transitions :meth:`~FiniteStateMachine.add_from_transition_function` | Add transitions by a transition function :meth:`~FiniteStateMachine.delete_transition` | Delete a transition :meth:`~FiniteStateMachine.remove_epsilon_transitions` | Remove epsilon transitions (not implemented) :meth:`~FiniteStateMachine.split_transitions` | Split transitions with input words of length ``> 1`` :meth:`~FiniteStateMachine.determine_alphabets` | Determines input and output alphabets :meth:`~FiniteStateMachine.construct_final_word_out` | Construct final output by implicitly reading trailing letters; cf. :meth:`~FiniteStateMachine.with_final_word_out` Properties ^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.has_state` | Checks for a state :meth:`~FiniteStateMachine.has_initial_state` | Checks for an initial state :meth:`~FiniteStateMachine.has_initial_states` | Checks for initial states :meth:`~FiniteStateMachine.has_final_state` | Checks for an final state :meth:`~FiniteStateMachine.has_final_states` | Checks for final states :meth:`~FiniteStateMachine.has_transition` | Checks for a transition :meth:`~FiniteStateMachine.is_deterministic` | Checks for a deterministic machine :meth:`~FiniteStateMachine.is_complete` | Checks for a complete machine :meth:`~FiniteStateMachine.is_connected` | Checks for a connected machine :meth:`~FiniteStateMachine.is_Markov_chain` | Checks for a Markov chain :meth:`~FiniteStateMachine.is_monochromatic` | Checks whether the colors of all states are equal :meth:`~FiniteStateMachine.asymptotic_moments` | Main terms of expectation and variance of sums of labels Operations ^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.disjoint_union` | Disjoint union (not implemented) :meth:`~FiniteStateMachine.concatenation` | Concatenation (not implemented) :meth:`~FiniteStateMachine.Kleene_closure` | Kleene closure (not implemented) :meth:`Automaton.intersection` | Intersection of automata :meth:`Transducer.intersection` | Intersection of transducers :meth:`Transducer.cartesian_product` | Cartesian product of a transducer with another finite state machine :meth:`~FiniteStateMachine.product_FiniteStateMachine` | Product of finite state machines :meth:`~FiniteStateMachine.composition` | Composition (output of other is input of self) :meth:`~FiniteStateMachine.input_projection` | Input projection (output is deleted) :meth:`~FiniteStateMachine.output_projection` | Output projection (old output is new input) :meth:`~FiniteStateMachine.projection` | Input or output projection :meth:`~FiniteStateMachine.transposition` | Transposition (all transitions are reversed) :meth:`~FiniteStateMachine.with_final_word_out` | Machine with final output constructed by implicitly reading trailing letters, cf. :meth:`~FiniteStateMachine.construct_final_word_out` for inplace version :meth:`Automaton.determinisation` | Determinisation of an automaton :meth:`~FiniteStateMachine.process` | Process input :meth:`Automaton.process` | Process input of an automaton (output differs from general case) :meth:`Transducer.process` | Process input of a transducer (output differs from general case) :meth:`~FiniteStateMachine.iter_process` | Return process iterator Simplification ^^^^^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.prepone_output` | Prepone output where possible :meth:`~FiniteStateMachine.equivalence_classes` | List of equivalent states :meth:`~FiniteStateMachine.quotient` | Quotient with respect to equivalence classes :meth:`~FiniteStateMachine.merged_transitions` | Merge transitions while adding input :meth:`~FiniteStateMachine.markov_chain_simplification` | Simplification of a Markov chain :meth:`Automaton.minimization` | Minimization of an automaton :meth:`Transducer.simplification` | Simplification of a transducer Conversion ^^^^^^^^^^ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.adjacency_matrix` | (Weighted) adjacency :class:`matrix <Matrix>` :meth:`~FiniteStateMachine.graph` | Underlying :class:`DiGraph` :meth:`~FiniteStateMachine.plot` | Plot LaTeX output ++++++++++++ .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :meth:`~FiniteStateMachine.latex_options` | Set options :meth:`~FiniteStateMachine.set_coordinates` | Set coordinates of the states :meth:`~FiniteStateMachine.default_format_transition_label` | Default formatting of words in transition labels :meth:`~FiniteStateMachine.format_letter_negative` | Format negative numbers as overlined number :meth:`~FiniteStateMachine.format_transition_label_reversed` | Format words in transition labels in reversed order :class:`FSMState` ----------------- .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :attr:`~FSMState.final_word_out` | Final output of a state :attr:`~FSMState.is_final` | Describes whether a state is final or not :attr:`~FSMState.is_initial` | Describes whether a state is initial or not :meth:`~FSMState.label` | Label of a state :meth:`~FSMState.relabeled` | Returns a relabeled deep copy of a state :meth:`~FSMState.fully_equal` | Checks whether two states are fully equal (including all attributes) :class:`FSMTransition` ---------------------- .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :attr:`~FSMTransition.from_state` | State in which transition starts :attr:`~FSMTransition.to_state` | State in which transition ends :attr:`~FSMTransition.word_in` | Input word of the transition :attr:`~FSMTransition.word_out` | Output word of the transition :meth:`~FSMTransition.deepcopy` | Returns a deep copy of the transition Helper Functions ---------------- .. csv-table:: :class: contentstable :widths: 30, 70 :delim: | :func:`equal` | Checks whether all elements of ``iterator`` are equal :func:`full_group_by` | Group iterable by values of some key :func:`startswith` | Determine whether list starts with the given prefix :func:`FSMLetterSymbol` | Returns a string associated to the input letter :func:`FSMWordSymbol` | Returns a string associated to a word :func:`is_FSMState` | Tests whether an object inherits from :class:`FSMState` :func:`is_FSMTransition` | Tests whether an object inherits from :class:`FSMTransition` :func:`is_FiniteStateMachine` | Tests whether an object inherits from :class:`FiniteStateMachine` :func:`duplicate_transition_ignore` | Default function for handling duplicate transitions :func:`duplicate_transition_raise_error` | Raise error when inserting a duplicate transition :func:`duplicate_transition_add_input` | Add input when inserting a duplicate transition .. _finite_state_machine_examples: Examples ======== We start with a general :class:`FiniteStateMachine`. Later there will be also an :class:`Automaton` and a :class:`Transducer`. A simple finite state machine ----------------------------- We can easily create a finite state machine by :: sage: fsm = FiniteStateMachine() sage: fsm Finite state machine with 0 states By default this is the empty finite state machine, so not very interesting. Let's create and add some states and transitions:: sage: day = fsm.add_state('day') sage: night = fsm.add_state('night') sage: sunrise = fsm.add_transition(night, day) sage: sunset = fsm.add_transition(day, night) Let us look at ``sunset`` more closely:: sage: sunset Transition from 'day' to 'night': -|- Note that could also have created and added the transitions directly by:: sage: fsm.add_transition('day', 'night') Transition from 'day' to 'night': -|- This would have had added the states automatically, since they are present in the transitions. Anyhow, we got the following finite state machine:: sage: fsm Finite state machine with 2 states We can also obtain the underlying directed graph by :: sage: fsm.graph() Digraph on 2 vertices To visualize a finite state machine, we can use :func:`~sage.misc.latex.latex` and run the result through LaTeX, see the section on :ref:`finite_state_machine_LaTeX_output` below. Alternatively, we could have created the finite state machine above simply by :: sage: FiniteStateMachine([('night', 'day'), ('day', 'night')]) Finite state machine with 2 states See :class:`FiniteStateMachine` for a lot of possibilities to create finite state machines. .. _finite_state_machine_recognizing_NAFs_example: A simple Automaton (recognizing NAFs) --------------------------------------- We want to build an automaton which recognizes non-adjacent forms (NAFs), i.e., sequences which have no adjacent non-zeros. We use `0`, `1`, and `-1` as digits:: sage: NAF = Automaton( ....: {'A': [('A', 0), ('B', 1), ('B', -1)], 'B': [('A', 0)]}) sage: NAF.state('A').is_initial = True sage: NAF.state('A').is_final = True sage: NAF.state('B').is_final = True sage: NAF Automaton with 2 states Of course, we could have specified the initial and final states directly in the definition of ``NAF`` by ``initial_states=['A']`` and ``final_states=['A', 'B']``. So let's test the automaton with some input:: sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False # activate new output behavior sage: NAF([0]) True sage: NAF([0, 1]) True sage: NAF([1, -1]) False sage: NAF([0, -1, 0, 1]) True sage: NAF([0, -1, -1, -1, 0]) False sage: NAF([-1, 0, 0, 1, 1]) False Alternatively, we could call that by :: sage: NAF.process([0, -1, 0, 1]) (True, 'B') which gives additionally the state in which we arrived. .. _finite_state_machine_LaTeX_output: LaTeX output ------------ We can visualize a finite state machine by converting it to LaTeX by using the usual function :func:`~sage.misc.latex.latex`. Within LaTeX, TikZ is used for typesetting the graphics, see the :wikipedia:`PGF/TikZ`. :: sage: print latex(NAF) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state, accepting, initial] (v0) at (3.000000, 0.000000) {$\text{\texttt{A}}$}; \node[state, accepting] (v1) at (-3.000000, 0.000000) {$\text{\texttt{B}}$}; \path[->] (v0) edge[loop above] node {$0$} (); \path[->] (v0.185.00) edge node[rotate=360.00, anchor=north] {$1, -1$} (v1.355.00); \path[->] (v1.5.00) edge node[rotate=0.00, anchor=south] {$0$} (v0.175.00); \end{tikzpicture} We can turn this into a graphical representation. :: sage: view(NAF) # not tested To actually see this, use the live documentation in the Sage notebook and execute the cells in this and the previous section. Several options can be set to customize the output, see :meth:`~FiniteStateMachine.latex_options` for details. In particular, we use :meth:`~FiniteStateMachine.format_letter_negative` to format `-1` as `\overline{1}`. :: sage: NAF.latex_options( ....: coordinates={'A': (0, 0), ....: 'B': (6, 0)}, ....: initial_where={'A': 'below'}, ....: format_letter=NAF.format_letter_negative, ....: format_state_label=lambda x: ....: r'\mathcal{%s}' % x.label() ....: ) sage: print latex(NAF) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state, accepting, initial, initial where=below] (v0) at (0.000000, 0.000000) {$\mathcal{A}$}; \node[state, accepting] (v1) at (6.000000, 0.000000) {$\mathcal{B}$}; \path[->] (v0) edge[loop above] node {$0$} (); \path[->] (v0.5.00) edge node[rotate=0.00, anchor=south] {$1, \overline{1}$} (v1.175.00); \path[->] (v1.185.00) edge node[rotate=360.00, anchor=north] {$0$} (v0.355.00); \end{tikzpicture} sage: view(NAF) # not tested A simple transducer (binary inverter) ------------------------------------- Let's build a simple transducer, which rewrites a binary word by iverting each bit:: sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) We can look at the states and transitions:: sage: inverter.states() ['A'] sage: for t in inverter.transitions(): ....: print t Transition from 'A' to 'A': 0|1 Transition from 'A' to 'A': 1|0 Now we apply a word to it and see what the transducer does:: sage: inverter([0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1]) [1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0] ``True`` means, that we landed in a final state, that state is labeled ``'A'``, and we also got an output. A transducer which performs division by `3` in binary ----------------------------------------------------- Now we build a transducer, which divides a binary number by `3`. The labels of the states are the remainder of the division. The transition function is :: sage: def f(state_from, read): ....: if state_from + read <= 1: ....: state_to = 2*state_from + read ....: write = 0 ....: else: ....: state_to = 2*state_from + read - 3 ....: write = 1 ....: return (state_to, write) which assumes reading a binary number from left to right. We get the transducer with :: sage: D = Transducer(f, initial_states=[0], final_states=[0], ....: input_alphabet=[0, 1]) Let us try to divide `12` by `3`:: sage: D([1, 1, 0, 0]) [0, 1, 0, 0] Now we want to divide `13` by `3`:: sage: D([1, 1, 0, 1]) Traceback (most recent call last): ... ValueError: Invalid input sequence. The raised ``ValueError`` means `13` is not divisible by `3`. .. _finite_state_machine_gray_code_example: Gray Code --------- The Gray code is a binary :wikipedia:`numeral system <Numeral_system>` where two successive values differ in only one bit, cf. the :wikipedia:`Gray_code`. The Gray code of an integer `n` is obtained by a bitwise xor between the binary expansion of `n` and the binary expansion of `\lfloor n/2\rfloor`; the latter corresponds to a shift by one position in binary. The purpose of this example is to construct a transducer converting the standard binary expansion to the Gray code by translating this construction into operations with transducers. For this construction, the least significant digit is at the left-most position. Note that it is easier to shift everything to the right first, i.e., multiply by `2` instead of building `\lfloor n/2\rfloor`. Then, we take the input xor with the right shift of the input and forget the first letter. We first construct a transducer shifting the binary expansion to the right. This requires storing the previously read digit in a state. :: sage: def shift_right_transition(state, digit): ....: if state == 'I': ....: return (digit, None) ....: else: ....: return (digit, state) sage: shift_right_transducer = Transducer( ....: shift_right_transition, ....: initial_states=['I'], ....: input_alphabet=[0, 1], ....: final_states=[0]) sage: shift_right_transducer.transitions() [Transition from 'I' to 0: 0|-, Transition from 'I' to 1: 1|-, Transition from 0 to 0: 0|0, Transition from 0 to 1: 1|0, Transition from 1 to 0: 0|1, Transition from 1 to 1: 1|1] sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False sage: shift_right_transducer([0, 1, 1, 0]) [0, 1, 1] sage: shift_right_transducer([1, 0, 0]) [1, 0] The output of the shifts above look a bit weird (from a right-shift transducer, we would expect, for example, that ``[1, 0, 0]`` was mapped to ``[0, 1, 0]``), since we write ``None`` instead of the zero at the left. Further, note that only `0` is listed as a final state as we have to enforce that a most significant zero is read as the last input letter in order to flush the last digit:: sage: shift_right_transducer([0, 1, 0, 1]) Traceback (most recent call last): ... ValueError: Invalid input sequence. Next, we construct the transducer performing the xor operation. We also have to take ``None`` into account as our ``shift_right_transducer`` waits one iteration until it starts writing output. This corresponds with our intention to forget the first letter. :: sage: def xor_transition(state, digits): ....: if digits[0] is None or digits[1] is None: ....: return (0, None) ....: else: ....: return (0, digits[0].__xor__(digits[1])) sage: from itertools import product sage: xor_transducer = Transducer( ....: xor_transition, ....: initial_states=[0], ....: final_states=[0], ....: input_alphabet=list(product([None, 0, 1], [0, 1]))) sage: xor_transducer.transitions() [Transition from 0 to 0: (None, 0)|-, Transition from 0 to 0: (None, 1)|-, Transition from 0 to 0: (0, 0)|0, Transition from 0 to 0: (0, 1)|1, Transition from 0 to 0: (1, 0)|1, Transition from 0 to 0: (1, 1)|0] sage: xor_transducer([(None, 0), (None, 1), (0, 0), (0, 1), (1, 0), (1, 1)]) [0, 1, 1, 0] sage: xor_transducer([(0, None)]) Traceback (most recent call last): ... ValueError: Invalid input sequence. The transducer computing the Gray code is then constructed as a :meth:`cartesian product <Transducer.cartesian_product>` between the shifted version and the original input (represented here by the ``shift_right_transducer`` and the :meth:`identity transducer <sage.combinat.finite_state_machine_generators.TransducerGenerators.Identity>`, respectively). This cartesian product is then fed into the ``xor_transducer`` as a :meth:`composition <FiniteStateMachine.composition>` of transducers. As described in :meth:`Transducer.cartesian_product`, we have to temporarily set ``finite_state_machine.FSMOldCodeTransducerCartesianProduct`` to ``False`` in order to disable backwards compatible code. :: sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = False sage: product_transducer = shift_right_transducer.cartesian_product(transducers.Identity([0, 1])) sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = True sage: Gray_transducer = xor_transducer(product_transducer) We use :meth:`~FiniteStateMachine.construct_final_word_out` to make sure that all output is written; otherwise, we would have to make sure that a sufficient number of trailing zeros is read. :: sage: Gray_transducer.construct_final_word_out([0]) sage: Gray_transducer.transitions() [Transition from (('I', 0), 0) to ((0, 0), 0): 0|-, Transition from (('I', 0), 0) to ((1, 0), 0): 1|-, Transition from ((0, 0), 0) to ((0, 0), 0): 0|0, Transition from ((0, 0), 0) to ((1, 0), 0): 1|1, Transition from ((1, 0), 0) to ((0, 0), 0): 0|1, Transition from ((1, 0), 0) to ((1, 0), 0): 1|0] There is a :meth:`prepackaged transducer <sage.combinat.finite_state_machine_generators.TransducerGenerators.GrayCode>` for Gray code, let's see whether they agree. We have to use :meth:`~FiniteStateMachine.relabeled` to relabel our states with integers. :: sage: constructed = Gray_transducer.relabeled() sage: packaged = transducers.GrayCode() sage: constructed == packaged True Finally, we check that this indeed computes the Gray code of the first 10 non-negative integers. :: sage: for n in srange(10): ....: Gray_transducer(n.bits()) [] [1] [1, 1] [0, 1] [0, 1, 1] [1, 1, 1] [1, 0, 1] [0, 0, 1] [0, 0, 1, 1] [1, 0, 1, 1] Using the hook-functions ------------------------ Let's use the previous example "divison by `3`" to demonstrate the optional state and transition parameters ``hook``. First, we define, what those functions should do. In our case, this is just saying in which state we are and which transition we take :: sage: def state_hook(state, process): ....: print "We are now in State %s." % (state.label(),) sage: from sage.combinat.finite_state_machine import FSMWordSymbol sage: def transition_hook(transition, process): ....: print ("Currently we go from %s to %s, " ....: "reading %s and writing %s." % ( ....: transition.from_state, transition.to_state, ....: FSMWordSymbol(transition.word_in), ....: FSMWordSymbol(transition.word_out))) Now, let's add these hook-functions to the existing transducer:: sage: for s in D.iter_states(): ....: s.hook = state_hook sage: for t in D.iter_transitions(): ....: t.hook = transition_hook Rerunning the process again now gives the following output:: sage: D.process([1, 1, 0, 1]) We are now in State 0. Currently we go from 0 to 1, reading 1 and writing 0. We are now in State 1. Currently we go from 1 to 0, reading 1 and writing 1. We are now in State 0. Currently we go from 0 to 0, reading 0 and writing 0. We are now in State 0. Currently we go from 0 to 1, reading 1 and writing 0. We are now in State 1. (False, 1, [0, 1, 0, 0]) The example above just explains the basic idea of using hook-functions. In the following, we will use those hooks more seriously. Detecting sequences with same number of `0` and `1` --------------------------------------------------- Suppose we have a binary input and want to accept all sequences with the same number of `0` and `1`. This cannot be done with a finite automaton. Anyhow, we can make usage of the hook functions to extend our finite automaton by a counter:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: C = FiniteStateMachine() sage: def update_counter(state, process): ....: l = process.read_letter() ....: process.fsm.counter += 1 if l == 1 else -1 ....: if process.fsm.counter > 0: ....: next_state = 'positive' ....: elif process.fsm.counter < 0: ....: next_state = 'negative' ....: else: ....: next_state = 'zero' ....: return FSMTransition(state, process.fsm.state(next_state), ....: l, process.fsm.counter) sage: C.add_state(FSMState('zero', hook=update_counter, ....: is_initial=True, is_final=True)) 'zero' sage: C.add_state(FSMState('positive', hook=update_counter)) 'positive' sage: C.add_state(FSMState('negative', hook=update_counter)) 'negative' Now, let's input some sequence:: sage: C.counter = 0; C([1, 1, 1, 1, 0, 0]) (False, 'positive', [1, 2, 3, 4, 3, 2]) The result is False, since there are four `1` but only two `0`. We land in the state ``positive`` and we can also see the values of the counter in each step. Let's try some other examples:: sage: C.counter = 0; C([1, 1, 0, 0]) (True, 'zero', [1, 2, 1, 0]) sage: C.counter = 0; C([0, 1, 0, 0]) (False, 'negative', [-1, 0, -1, -2]) See also methods :meth:`Automaton.process` and :meth:`Transducer.process` (or even :meth:`FiniteStateMachine.process`), the explanation of the parameter ``hook`` and the examples in :class:`FSMState` and :class:`FSMTransition`, and the description and examples in :class:`FSMProcessIterator` for more information on processing and hooks. AUTHORS: - Daniel Krenn (2012-03-27): initial version - Clemens Heuberger (2012-04-05): initial version - Sara Kropf (2012-04-17): initial version - Clemens Heuberger (2013-08-21): release candidate for Sage patch - Daniel Krenn (2013-08-21): release candidate for Sage patch - Sara Kropf (2013-08-21): release candidate for Sage patch - Clemens Heuberger (2013-09-02): documentation improved - Daniel Krenn (2013-09-13): comments from trac worked in - Clemens Heuberger (2013-11-03): output (labels) of determinisation, product, composition, etc. changed (for consistency), representation of state changed, documentation improved - Daniel Krenn (2013-11-04): whitespaces in documentation corrected - Clemens Heuberger (2013-11-04): full_group_by added - Daniel Krenn (2013-11-04): next release candidate for Sage patch - Sara Kropf (2013-11-08): fix for adjacency matrix - Clemens Heuberger (2013-11-11): fix for prepone_output - Daniel Krenn (2013-11-11): comments from trac #15078 included: docstring of FiniteStateMachine rewritten, Automaton and Transducer inherited from FiniteStateMachine - Daniel Krenn (2013-11-25): documentation improved according to comments from trac #15078 - Clemens Heuberger, Daniel Krenn, Sara Kropf (2014-02-21--2014-07-18): A huge bunch of improvements. Details see #15841, #15847, #15848, #15849, #15850, #15922, #15923, #15924, #15925, #15928, #15960, #15961, #15962, #15963, #15975, #16016, #16024, #16061, #16128, #16132, #16138, #16139, #16140, #16143, #16144, #16145, #16146, #16191, #16200, #16205, #16206, #16207, #16229, #16253, #16254, #16255, #16266, #16355, #16357, #16387, #16425, #16539, #16555, #16557, #16588, #16589, #16666, #16668, #16674, #16675, #16677. ACKNOWLEDGEMENT: - Clemens Heuberger, Daniel Krenn and Sara Kropf are supported by the Austrian Science Fund (FWF): P 24644-N26. Methods ======= """ #***************************************************************************** # Copyright (C) 2012--2014 Clemens Heuberger <clemens.heuberger@aau.at> # 2012--2014 Daniel Krenn <dev@danielkrenn.at> # 2012--2014 Sara Kropf <sara.kropf@aau.at> # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from sage.structure.sage_object import SageObject from sage.graphs.digraph import DiGraph from sage.matrix.constructor import matrix from sage.rings.integer_ring import ZZ from sage.rings.real_mpfr import RR from sage.symbolic.ring import SR from sage.calculus.var import var from sage.misc.cachefunc import cached_function from sage.misc.latex import latex from sage.misc.misc import verbose from sage.functions.trig import cos, sin, atan2 from sage.symbolic.constants import pi from copy import copy from copy import deepcopy import itertools from itertools import imap from collections import defaultdict, OrderedDict def full_group_by(l, key=lambda x: x): """ Group iterable ``l`` by values of ``key``. INPUT: - iterable ``l`` - key function ``key`` OUTPUT: A list of pairs ``(k, elements)`` such that ``key(e)=k`` for all ``e`` in ``elements``. This is similar to ``itertools.groupby`` except that lists are returned instead of iterables and no prior sorting is required. We do not require - that the keys are sortable (in contrast to the approach via ``sorted`` and ``itertools.groupby``) and - that the keys are hashable (in contrast to the implementation proposed in `<http://stackoverflow.com/a/15250161>`_). However, it is required - that distinct keys have distinct ``str``-representations. The implementation is inspired by `<http://stackoverflow.com/a/15250161>`_, but non-hashable keys are allowed. EXAMPLES:: sage: from sage.combinat.finite_state_machine import full_group_by sage: t = [2/x, 1/x, 2/x] sage: r = full_group_by([0, 1, 2], key=lambda i:t[i]) sage: sorted(r, key=lambda p:p[1]) [(2/x, [0, 2]), (1/x, [1])] sage: from itertools import groupby sage: for k, elements in groupby(sorted([0, 1, 2], ....: key=lambda i:t[i]), ....: key=lambda i:t[i]): ....: print k, list(elements) 2/x [0] 1/x [1] 2/x [2] Note that the behavior is different from ``itertools.groupby`` because neither `1/x<2/x` nor `2/x<1/x` does hold. Here, the result ``r`` has been sorted in order to guarantee a consistent order for the doctest suite. """ elements = defaultdict(list) original_keys = {} for item in l: k = key(item) s = str(k) if s in original_keys: if original_keys[s]!=k: raise ValueError("Two distinct elements with representation " "%s " % s) else: original_keys[s]=k elements[s].append(item) return [(original_keys[s], values ) for (s, values) in elements.items()] def equal(iterator): """ Checks whether all elements of ``iterator`` are equal. INPUT: - ``iterator`` -- an iterator of the elements to check OUTPUT: ``True`` or ``False``. This implements `<http://stackoverflow.com/a/3844832/1052778>`_. EXAMPLES:: sage: from sage.combinat.finite_state_machine import equal sage: equal([0, 0, 0]) True sage: equal([0, 1, 0]) False sage: equal([]) True sage: equal(iter([None, None])) True We can test other properties of the elements than the elements themselves. In the following example, we check whether all tuples have the same lengths:: sage: equal(len(x) for x in [(1, 2), (2, 3), (3, 1)]) True sage: equal(len(x) for x in [(1, 2), (1, 2, 3), (3, 1)]) False """ try: iterator = iter(iterator) first = next(iterator) return all(first == rest for rest in iterator) except StopIteration: return True def startswith(list, prefix): """ Determine whether list starts with the given prefix. INPUT: - ``list`` -- list - ``prefix`` -- list representing the prefix OUTPUT: ``True`` or ``False``. Similar to :meth:`str.startswith`. EXAMPLES:: sage: from sage.combinat.finite_state_machine import startswith sage: startswith([1, 2, 3], [1, 2]) True sage: startswith([1], [1, 2]) False sage: startswith([1, 3, 2], [1, 2]) False """ return list[:len(prefix)] == prefix #***************************************************************************** FSMEmptyWordSymbol = '-' EmptyWordLaTeX = r'\varepsilon' EndOfWordLaTeX = r'\$' FSMOldCodeTransducerCartesianProduct = True FSMOldProcessOutput = True # See trac #16132 (deprecation). tikz_automata_where = {"right": 0, "above": 90, "left": 180, "below": 270} def FSMLetterSymbol(letter): """ Returns a string associated to the input letter. INPUT: - ``letter`` -- the input letter or ``None`` (representing the empty word). OUTPUT: If ``letter`` is ``None`` the symbol for the empty word ``FSMEmptyWordSymbol`` is returned, otherwise the string associated to the letter. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMLetterSymbol sage: FSMLetterSymbol(0) '0' sage: FSMLetterSymbol(None) '-' """ return FSMEmptyWordSymbol if letter is None else repr(letter) def FSMWordSymbol(word): """ Returns a string of ``word``. It may returns the symbol of the empty word ``FSMEmptyWordSymbol``. INPUT: - ``word`` -- the input word. OUTPUT: A string of ``word``. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMWordSymbol sage: FSMWordSymbol([0, 1, 1]) '0,1,1' """ if not isinstance(word, list): return FSMLetterSymbol(word) if len(word) == 0: return FSMEmptyWordSymbol s = '' for letter in word: s += (',' if len(s) > 0 else '') + FSMLetterSymbol(letter) return s #***************************************************************************** def is_FSMState(S): """ Tests whether or not ``S`` inherits from :class:`FSMState`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FSMState, FSMState sage: is_FSMState(FSMState('A')) True """ return isinstance(S, FSMState) class FSMState(SageObject): """ Class for a state of a finite state machine. INPUT: - ``label`` -- the label of the state. - ``word_out`` -- (default: ``None``) a word that is written when the state is reached. - ``is_initial`` -- (default: ``False``) - ``is_final`` -- (default: ``False``) - ``final_word_out`` -- (default: ``None``) a word that is written when the state is reached as the last state of some input; only for final states. - ``hook`` -- (default: ``None``) A function which is called when the state is reached during processing input. It takes two input parameters: the first is the current state (to allow using the same hook for several states), the second is the current process iterator object (to have full access to everything; e.g. the next letter from the input tape can be read in). It can output the next transition, i.e. the transition to take next. If it returns ``None`` the process iterator chooses. Moreover, this function can raise a ``StopIteration`` exception to stop processing of a finite state machine the input immediately. See also the example below. - ``color`` -- (default: ``None``) In order to distinguish states, they can be given an arbitrary "color" (an arbitrary object). This is used in :meth:`FiniteStateMachine.equivalence_classes`: states of different colors are never considered to be equivalent. Note that :meth:`Automaton.determinisation` requires that ``color`` is hashable. - ``allow_label_None`` -- (default: ``False``) If ``True`` allows also ``None`` as label. Note that a state with label ``None`` is used in :class:`FSMProcessIterator`. OUTPUT: Returns a state of a finite state machine. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('state 1', word_out=0, is_initial=True) sage: A 'state 1' sage: A.label() 'state 1' sage: B = FSMState('state 2') sage: A == B False We can also define a final output word of a final state which is used if the input of a transducer leads to this state. Such final output words are used in subsequential transducers. :: sage: C = FSMState('state 3', is_final=True, final_word_out='end') sage: C.final_word_out ['end'] The final output word can be a single letter, ``None`` or a list of letters:: sage: A = FSMState('A') sage: A.is_final = True sage: A.final_word_out = 2 sage: A.final_word_out [2] sage: A.final_word_out = [2, 3] sage: A.final_word_out [2, 3] Only final states can have a final output word which is not ``None``:: sage: B = FSMState('B') sage: B.final_word_out is None True sage: B.final_word_out = 2 Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state B is not final. Setting the ``final_word_out`` of a final state to ``None`` is the same as setting it to ``[]`` and is also the default for a final state:: sage: C = FSMState('C', is_final=True) sage: C.final_word_out [] sage: C.final_word_out = None sage: C.final_word_out [] sage: C.final_word_out = [] sage: C.final_word_out [] It is not allowed to use ``None`` as a label:: sage: from sage.combinat.finite_state_machine import FSMState sage: FSMState(None) Traceback (most recent call last): ... ValueError: Label None reserved for a special state, choose another label. This can be overridden by:: sage: FSMState(None, allow_label_None=True) None Note that :meth:`Automaton.determinisation` requires that ``color`` is hashable:: sage: A = Automaton([[0, 0, 0]], initial_states=[0]) sage: A.state(0).color = [] sage: A.determinisation() Traceback (most recent call last): ... TypeError: unhashable type: 'list' sage: A.state(0).color = () sage: A.determinisation() Automaton with 1 states We can use a hook function of a state to stop processing. This is done by raising a ``StopIteration`` exception. The following code demonstrates this:: sage: T = Transducer([(0, 1, 9, 'a'), (1, 2, 9, 'b'), ....: (2, 3, 9, 'c'), (3, 4, 9, 'd')], ....: initial_states=[0], ....: final_states=[4], ....: input_alphabet=[9]) sage: def stop(current_state, process_iterator): ....: raise StopIteration() sage: T.state(3).hook = stop sage: T.process([9, 9, 9, 9]) (False, 3, ['a', 'b', 'c']) """ is_initial = False """ Describes whether the state is initial. EXAMPLES:: sage: T = Automaton([(0,0,0)]) sage: T.initial_states() [] sage: T.state(0).is_initial = True sage: T.initial_states() [0] """ def __init__(self, label, word_out=None, is_initial=False, is_final=False, final_word_out=None, hook=None, color=None, allow_label_None=False): """ See :class:`FSMState` for more information. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: FSMState('final', is_final=True) 'final' TESTS:: sage: A = FSMState('A', is_final=True) sage: A.final_word_out [] sage: A.is_final = True sage: A = FSMState('A', is_final=True, final_word_out='end') sage: A.final_word_out ['end'] sage: A = FSMState('A', is_final=True, ....: final_word_out=['e', 'n', 'd']) sage: A.final_word_out ['e', 'n', 'd'] sage: A = FSMState('A', is_final=True, final_word_out=[]) sage: A.final_word_out [] sage: A = FSMState('A', is_final=True, final_word_out=None) sage: A.final_word_out [] sage: A = FSMState('A', is_final=False) sage: A.final_word_out is None True sage: A.is_final = False sage: A = FSMState('A', is_final=False, final_word_out='end') Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state A is not final. sage: A = FSMState('A', is_final=False, ....: final_word_out=['e', 'n', 'd']) Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state A is not final. sage: A = FSMState('A', is_final=False, final_word_out=None) sage: A.final_word_out is None True sage: A = FSMState('A', is_final=False, final_word_out=[]) Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state A is not final. """ if not allow_label_None and label is None: raise ValueError("Label None reserved for a special state, " "choose another label.") self._label_ = label if isinstance(word_out, list): self.word_out = word_out elif word_out is not None: self.word_out = [word_out] else: self.word_out = [] self.is_initial = is_initial self._final_word_out_ = None self.is_final = is_final self.final_word_out = final_word_out if hook is not None: if hasattr(hook, '__call__'): self.hook = hook else: raise TypeError('Wrong argument for hook.') self.color = color def __lt__(self, other): """ Returns True if label of ``self`` is less than label of ``other``. INPUT: - `other` -- a state. OUTPUT: True or False. EXAMPLE:: sage: from sage.combinat.finite_state_machine import FSMState sage: FSMState(0) < FSMState(1) True """ return self.label() < other.label() @property def final_word_out(self): """ The final output word of a final state which is written if the state is reached as the last state of the input of the finite state machine. For a non-final state, the value is ``None``. ``final_word_out`` can be a single letter, a list or ``None``, but for a final-state, it is always saved as a list. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_final=True, final_word_out=2) sage: A.final_word_out [2] sage: A.final_word_out = 3 sage: A.final_word_out [3] sage: A.final_word_out = [3, 4] sage: A.final_word_out [3, 4] sage: A.final_word_out = None sage: A.final_word_out [] sage: B = FSMState('B') sage: B.final_word_out is None True A non-final state cannot have a final output word:: sage: B.final_word_out = [3, 4] Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state B is not final. """ return self._final_word_out_ @final_word_out.setter def final_word_out(self, final_word_out): """ Sets the value of the final output word of a final state. INPUT: - ``final_word_out`` -- a list, any element or ``None``. OUTPUT: Nothing. TESTS:: sage: from sage.combinat.finite_state_machine import FSMState sage: B = FSMState('B') sage: B.final_word_out = [] Traceback (most recent call last): ... ValueError: Only final states can have a final output word, but state B is not final. sage: B.final_word_out = None sage: B.final_word_out is None True """ if not self.is_final: if final_word_out is not None: raise ValueError("Only final states can have a " "final output word, but state %s is not final." % (self.label())) else: self._final_word_out_ = None elif isinstance(final_word_out, list): self._final_word_out_ = final_word_out elif final_word_out is not None: self._final_word_out_ = [final_word_out] else: self._final_word_out_ = [] @property def is_final(self): """ Describes whether the state is final or not. ``True`` if the state is final and ``False`` otherwise. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_final=True, final_word_out=3) sage: A.is_final True sage: A.is_final = False Traceback (most recent call last): ... ValueError: State A cannot be non-final, because it has a final output word. Only final states can have a final output word. sage: A.final_word_out = None sage: A.is_final = False sage: A.is_final False """ return (self.final_word_out is not None) @is_final.setter def is_final(self, is_final): """ Defines the state as a final state or a non-final state. INPUT: - ``is_final`` -- ``True`` if the state should be final and ``False`` otherwise. OUTPUT: Nothing. TESTS:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_final=True) sage: A.final_word_out [] sage: A.is_final = False sage: A.final_word_out is None True sage: A = FSMState('A', is_final=True, final_word_out='a') sage: A.is_final = False Traceback (most recent call last): ... ValueError: State A cannot be non-final, because it has a final output word. Only final states can have a final output word. sage: A = FSMState('A', is_final=True, final_word_out=[]) sage: A.is_final = False sage: A.final_word_out is None True """ if is_final and self.final_word_out is None: self._final_word_out_ = [] elif not is_final: if not self.final_word_out: self._final_word_out_ = None else: raise ValueError("State %s cannot be non-final, because it " "has a final output word. Only final states " "can have a final output word. " % self.label()) def label(self): """ Returns the label of the state. INPUT: Nothing. OUTPUT: The label of the state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('state') sage: A.label() 'state' """ return self._label_ def __copy__(self): """ Returns a (shallow) copy of the state. INPUT: Nothing. OUTPUT: A new state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: copy(A) 'A' """ new = FSMState(self.label(), self.word_out, self.is_initial, self.is_final, color=self.color, final_word_out=self.final_word_out) if hasattr(self, 'hook'): new.hook = self.hook return new copy = __copy__ def __deepcopy__(self, memo): """ Returns a deep copy of the state. INPUT: - ``memo`` -- a dictionary storing already processed elements. OUTPUT: A new state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: deepcopy(A) 'A' """ try: label = self._deepcopy_relabel_ except AttributeError: label = deepcopy(self.label(), memo) new = FSMState(label, deepcopy(self.word_out, memo), self.is_initial, self.is_final) if hasattr(self, 'hook'): new.hook = deepcopy(self.hook, memo) new.color = deepcopy(self.color, memo) new.final_word_out = deepcopy(self.final_word_out, memo) return new def deepcopy(self, memo=None): """ Returns a deep copy of the state. INPUT: - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. OUTPUT: A new state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState((1, 3), color=[1, 2], ....: is_final=True, final_word_out=3) sage: B = deepcopy(A) sage: B (1, 3) sage: B.label == A.label True sage: B.label is A.label False sage: B.color == A.color True sage: B.color is A.color False sage: B.is_final == A.is_final True sage: B.is_final is A.is_final True sage: B.final_word_out == A.final_word_out True sage: B.final_word_out is A.final_word_out False """ return deepcopy(self, memo) def relabeled(self, label, memo=None): """ Returns a deep copy of the state with a new label. INPUT: - ``label`` -- the label of new state. - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. OUTPUT: A new state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: A.relabeled('B') 'B' """ self._deepcopy_relabel_ = label new = deepcopy(self, memo) del self._deepcopy_relabel_ return new def __hash__(self): """ Returns a hash value for the object. INPUT: Nothing. OUTPUT: The hash of this state. TESTS:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: hash(A) #random -269909568 """ return hash(self.label()) def _repr_(self): """ Returns the string "label". INPUT: Nothing. OUTPUT: A string. TESTS: sage: from sage.combinat.finite_state_machine import FSMState sage: FSMState('A')._repr_() "'A'" """ return repr(self.label()) def __eq__(left, right): """ Returns True if two states are the same, i.e., if they have the same labels. INPUT: - ``left`` -- a state. - ``right`` -- a state. OUTPUT: True or False. Note that the hooks and whether the states are initial or final are not checked. To fully compare two states (including these attributes), use :meth:`.fully_equal`. As only the labels are used when hashing a state, only the labels can actually be compared by the equality relation. Note that the labels are unique within one finite state machine, so this may only lead to ambiguities when comparing states belonging to different finite state machines. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: B = FSMState('A', is_initial=True) sage: A == B True """ if not is_FSMState(right): return False return left.label() == right.label() def __ne__(left, right): """ Tests for inequality, complement of __eq__. INPUT: - ``left`` -- a state. - ``right`` -- a state. OUTPUT: True or False. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial=True) sage: B = FSMState('A', is_final=True) sage: A != B False """ return (not (left == right)) def fully_equal(left, right, compare_color=True): """ Checks whether two states are fully equal, i.e., including all attributes except ``hook``. INPUT: - ``left`` -- a state. - ``right`` -- a state. - ``compare_color`` -- If ``True`` (default) colors are compared as well, otherwise not. OUTPUT: ``True`` or ``False``. Note that usual comparison by ``==`` does only compare the labels. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: B = FSMState('A', is_initial=True) sage: A.fully_equal(B) False sage: A == B True sage: A.is_initial = True; A.color = 'green' sage: A.fully_equal(B) False sage: A.fully_equal(B, compare_color=False) True """ color = not compare_color or left.color == right.color return (left.__eq__(right) and left.is_initial == right.is_initial and left.is_final == right.is_final and left.final_word_out == right.final_word_out and left.word_out == right.word_out and color) def __nonzero__(self): """ Returns True. INPUT: Nothing. OUTPUT: True or False. TESTS:: sage: from sage.combinat.finite_state_machine import FSMState sage: FSMState('A').__nonzero__() True """ return True # A state cannot be zero (see __init__) #***************************************************************************** def is_FSMTransition(T): """ Tests whether or not ``T`` inherits from :class:`FSMTransition`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FSMTransition, FSMTransition sage: is_FSMTransition(FSMTransition('A', 'B')) True """ return isinstance(T, FSMTransition) class FSMTransition(SageObject): """ Class for a transition of a finite state machine. INPUT: - ``from_state`` -- state from which transition starts. - ``to_state`` -- state in which transition ends. - ``word_in`` -- the input word of the transitions (when the finite state machine is used as automaton) - ``word_out`` -- the output word of the transitions (when the finite state machine is used as transducer) OUTPUT: A transition of a finite state machine. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: A = FSMState('A') sage: B = FSMState('B') sage: S = FSMTransition(A, B, 0, 1) sage: T = FSMTransition('A', 'B', 0, 1) sage: T == S True sage: U = FSMTransition('A', 'B', 0) sage: U == T False """ from_state = None """State from which the transition starts. Read-only.""" to_state = None """State in which the transition ends. Read-only.""" word_in = None """Input word of the transition. Read-only.""" word_out = None """Output word of the transition. Read-only.""" def __init__(self, from_state, to_state, word_in=None, word_out=None, hook=None): """ See :class:`FSMTransition` for more information. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: FSMTransition('A', 'B', 0, 1) Transition from 'A' to 'B': 0|1 """ if is_FSMState(from_state): self.from_state = from_state else: self.from_state = FSMState(from_state) if is_FSMState(to_state): self.to_state = to_state else: self.to_state = FSMState(to_state) if isinstance(word_in, list): self.word_in = word_in elif word_in is not None: self.word_in = [word_in] else: self.word_in = [] if isinstance(word_out, list): self.word_out = word_out elif word_out is not None: self.word_out = [word_out] else: self.word_out = [] if hook is not None: if hasattr(hook, '__call__'): self.hook = hook else: raise TypeError('Wrong argument for hook.') def __lt__(self, other): """ Returns True if ``self`` is less than ``other`` with respect to the key ``(self.from_state, self.word_in, self.to_state, self.word_out)``. INPUT: - `other` -- a transition. OUTPUT: True or False. EXAMPLE:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: FSMTransition(0,1,0,0) < FSMTransition(1,0,0,0) True """ return (self.from_state, self.word_in, self.to_state, self.word_out) < \ (other.from_state, other.word_in, other.to_state, other.word_out) def __copy__(self): """ Returns a (shallow) copy of the transition. INPUT: Nothing. OUTPUT: A new transition. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t = FSMTransition('A', 'B', 0) sage: copy(t) Transition from 'A' to 'B': 0|- """ new = FSMTransition(self.from_state, self.to_state, self.word_in, self.word_out) if hasattr(self, 'hook'): new.hook = self.hook return new copy = __copy__ def __deepcopy__(self, memo): """ Returns a deep copy of the transition. INPUT: - ``memo`` -- a dictionary storing already processed elements. OUTPUT: A new transition. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t = FSMTransition('A', 'B', 0) sage: deepcopy(t) Transition from 'A' to 'B': 0|- """ new = FSMTransition(deepcopy(self.from_state, memo), deepcopy(self.to_state, memo), deepcopy(self.word_in, memo), deepcopy(self.word_out, memo)) if hasattr(self, 'hook'): new.hook = deepcopy(self.hook, memo) return new def deepcopy(self, memo=None): """ Returns a deep copy of the transition. INPUT: - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. OUTPUT: A new transition. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t = FSMTransition('A', 'B', 0) sage: deepcopy(t) Transition from 'A' to 'B': 0|- """ return deepcopy(self, memo) def __hash__(self): """ Since transitions are mutable, they should not be hashable, so we return a type error. INPUT: Nothing. OUTPUT: The hash of this transition. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: hash(FSMTransition('A', 'B')) Traceback (most recent call last): ... TypeError: Transitions are mutable, and thus not hashable. """ raise TypeError("Transitions are mutable, and thus not hashable.") def _repr_(self): """ Represents a transitions as from state to state and input, output. INPUT: Nothing. OUTPUT: A string. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: FSMTransition('A', 'B', 0, 0)._repr_() "Transition from 'A' to 'B': 0|0" """ return "Transition from %s to %s: %s" % (repr(self.from_state), repr(self.to_state), self._in_out_label_()) def _in_out_label_(self): """ Returns the input and output of a transition as "word_in|word_out". INPUT: Nothing. OUTPUT: A string of the input and output labels. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: FSMTransition('A', 'B', 0, 1)._in_out_label_() '0|1' """ return "%s|%s" % (FSMWordSymbol(self.word_in), FSMWordSymbol(self.word_out)) def __eq__(left, right): """ Returns True if the two transitions are the same, i.e., if the both go from the same states to the same states and read and write the same words. Note that the hooks are not checked. INPUT: - ``left`` -- a transition. - ``right`` -- a transition. OUTPUT: True or False. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: A = FSMState('A', is_initial=True) sage: t1 = FSMTransition('A', 'B', 0, 1) sage: t2 = FSMTransition(A, 'B', 0, 1) sage: t1 == t2 True """ if not is_FSMTransition(right): raise TypeError('Only instances of FSMTransition ' \ 'can be compared.') return left.from_state == right.from_state \ and left.to_state == right.to_state \ and left.word_in == right.word_in \ and left.word_out == right.word_out def __ne__(left, right): """ INPUT: - ``left`` -- a transition. - ``right`` -- a transition. OUTPUT: True or False. Tests for inequality, complement of __eq__. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: A = FSMState('A', is_initial=True) sage: t1 = FSMTransition('A', 'B', 0, 1) sage: t2 = FSMTransition(A, 'B', 0, 1) sage: t1 != t2 False """ return (not (left == right)) def __nonzero__(self): """ Returns True. INPUT: Nothing. OUTPUT: True or False. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: FSMTransition('A', 'B', 0).__nonzero__() True """ return True # A transition cannot be zero (see __init__) #***************************************************************************** def is_FiniteStateMachine(FSM): """ Tests whether or not ``FSM`` inherits from :class:`FiniteStateMachine`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine sage: is_FiniteStateMachine(FiniteStateMachine()) True sage: is_FiniteStateMachine(Automaton()) True sage: is_FiniteStateMachine(Transducer()) True """ return isinstance(FSM, FiniteStateMachine) def duplicate_transition_ignore(old_transition, new_transition): """ Default function for handling duplicate transitions in finite state machines. This implementation ignores the occurrence. See the documentation of the ``on_duplicate_transition`` parameter of :class:`FiniteStateMachine`. INPUT: - ``old_transition`` -- A transition in a finite state machine. - ``new_transition`` -- A transition, identical to ``old_transition``, which is to be inserted into the finite state machine. OUTPUT: The same transition, unchanged. EXAMPLES:: sage: from sage.combinat.finite_state_machine import duplicate_transition_ignore sage: from sage.combinat.finite_state_machine import FSMTransition sage: duplicate_transition_ignore(FSMTransition(0, 0, 1), ....: FSMTransition(0, 0, 1)) Transition from 0 to 0: 1|- """ return old_transition def duplicate_transition_raise_error(old_transition, new_transition): """ Alternative function for handling duplicate transitions in finite state machines. This implementation raises a ``ValueError``. See the documentation of the ``on_duplicate_transition`` parameter of :class:`FiniteStateMachine`. INPUT: - ``old_transition`` -- A transition in a finite state machine. - ``new_transition`` -- A transition, identical to ``old_transition``, which is to be inserted into the finite state machine. OUTPUT: Nothing. A ``ValueError`` is raised. EXAMPLES:: sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error sage: from sage.combinat.finite_state_machine import FSMTransition sage: duplicate_transition_raise_error(FSMTransition(0, 0, 1), ....: FSMTransition(0, 0, 1)) Traceback (most recent call last): ... ValueError: Attempting to re-insert transition Transition from 0 to 0: 1|- """ raise ValueError("Attempting to re-insert transition %s" % old_transition) def duplicate_transition_add_input(old_transition, new_transition): """ Alternative function for handling duplicate transitions in finite state machines. This implementation adds the input label of the new transition to the input label of the old transition. This is intended for the case where a Markov chain is modelled by a finite state machine using the input labels as transition probabilities. See the documentation of the ``on_duplicate_transition`` parameter of :class:`FiniteStateMachine`. INPUT: - ``old_transition`` -- A transition in a finite state machine. - ``new_transition`` -- A transition, identical to ``old_transition``, which is to be inserted into the finite state machine. OUTPUT: A transition whose input weight is the sum of the input weights of ``old_transition`` and ``new_transition``. EXAMPLES:: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: from sage.combinat.finite_state_machine import FSMTransition sage: duplicate_transition_add_input(FSMTransition('a', 'a', 1/2), ....: FSMTransition('a', 'a', 1/2)) Transition from 'a' to 'a': 1|- Input labels must be lists of length 1:: sage: duplicate_transition_add_input(FSMTransition('a', 'a', [1, 1]), ....: FSMTransition('a', 'a', [1, 1])) Traceback (most recent call last): ... TypeError: Trying to use duplicate_transition_add_input on "Transition from 'a' to 'a': 1,1|-" and "Transition from 'a' to 'a': 1,1|-", but input words are assumed to be lists of length 1 """ if (hasattr(old_transition.word_in, '__iter__') and len(old_transition.word_in) == 1 and hasattr(new_transition.word_in, '__iter__') and len(new_transition.word_in) == 1): old_transition.word_in = [old_transition.word_in[0] + new_transition.word_in[0]] else: raise TypeError('Trying to use duplicate_transition_add_input on ' + '"%s" and "%s", ' % (old_transition, new_transition) + 'but input words are assumed to be lists of length 1') return old_transition class FiniteStateMachine(SageObject): """ Class for a finite state machine. A finite state machine is a finite set of states connected by transitions. INPUT: - ``data`` -- can be any of the following: #. a dictionary of dictionaries (of transitions), #. a dictionary of lists (of states or transitions), #. a list (of transitions), #. a function (transition function), #. an other instance of a finite state machine. - ``initial_states`` and ``final_states`` -- the initial and final states of this machine - ``input_alphabet`` and ``output_alphabet`` -- the input and output alphabets of this machine - ``determine_alphabets`` -- If ``True``, then the function :meth:`.determine_alphabets` is called after ``data`` was read and processed, if ``False``, then not. If it is ``None``, then it is decided during the construction of the finite state machine whether :meth:`.determine_alphabets` should be called. - ``with_final_word_out`` -- If given (not ``None``), then the function :meth:`.with_final_word_out` (more precisely, its inplace pendant :meth:`.construct_final_word_out`) is called with input ``letters=with_final_word_out`` at the end of the creation process. - ``store_states_dict`` -- If ``True``, then additionally the states are stored in an interal dictionary for speed up. - ``on_duplicate_transition`` -- A function which is called when a transition is inserted into ``self`` which already existed (same ``from_state``, same ``to_state``, same ``word_in``, same ``word_out``). This function is assumed to take two arguments, the first being the already existing transition, the second being the new transition (as an :class:`FSMTransition`). The function must return the (possibly modified) original transition. By default, we have ``on_duplicate_transition=None``, which is interpreted as ``on_duplicate_transition=duplicate_transition_ignore``, where ``duplicate_transition_ignore`` is a predefined function ignoring the occurrence. Other such predefined functions are ``duplicate_transition_raise_error`` and ``duplicate_transition_add_input``. OUTPUT: A finite state machine. The object creation of :class:`Automaton` and :class:`Transducer` is the same as the one described here (i.e. just replace the word ``FiniteStateMachine`` by ``Automaton`` or ``Transducer``). Each transition of an automaton has an input label. Automata can, for example, be determinised (see :meth:`Automaton.determinisation`) and minimized (see :meth:`Automaton.minimization`). Each transition of a transducer has an input and an output label. Transducers can, for example, be simplified (see :meth:`Transducer.simplification`). EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition See documentation for more examples. We illustrate the different input formats: #. The input-data can be a dictionary of dictionaries, where - the keys of the outer dictionary are state-labels (from-states of transitions), - the keys of the inner dictionaries are state-labels (to-states of transitions), - the values of the inner dictionaries specify the transition more precisely. The easiest is to use a tuple consisting of an input and an output word:: sage: FiniteStateMachine({'a':{'b':(0, 1), 'c':(1, 1)}}) Finite state machine with 3 states Instead of the tuple anything iterable (e.g. a list) can be used as well. If you want to use the arguments of :class:`FSMTransition` directly, you can use a dictionary:: sage: FiniteStateMachine({'a':{'b':{'word_in':0, 'word_out':1}, ....: 'c':{'word_in':1, 'word_out':1}}}) Finite state machine with 3 states In the case you already have instances of :class:`FSMTransition`, it is possible to use them directly:: sage: FiniteStateMachine({'a':{'b':FSMTransition('a', 'b', 0, 1), ....: 'c':FSMTransition('a', 'c', 1, 1)}}) Finite state machine with 3 states #. The input-data can be a dictionary of lists, where the keys are states or label of states. The list-elements can be states:: sage: a = FSMState('a') sage: b = FSMState('b') sage: c = FSMState('c') sage: FiniteStateMachine({a:[b, c]}) Finite state machine with 3 states Or the list-elements can simply be labels of states:: sage: FiniteStateMachine({'a':['b', 'c']}) Finite state machine with 3 states The list-elements can also be transitions:: sage: FiniteStateMachine({'a':[FSMTransition('a', 'b', 0, 1), ....: FSMTransition('a', 'c', 1, 1)]}) Finite state machine with 3 states Or they can be tuples of a label, an input word and an output word specifying a transition:: sage: FiniteStateMachine({'a':[('b', 0, 1), ('c', 1, 1)]}) Finite state machine with 3 states #. The input-data can be a list, where its elements specify transitions:: sage: FiniteStateMachine([FSMTransition('a', 'b', 0, 1), ....: FSMTransition('a', 'c', 1, 1)]) Finite state machine with 3 states It is possible to skip ``FSMTransition`` in the example above:: sage: FiniteStateMachine([('a', 'b', 0, 1), ('a', 'c', 1, 1)]) Finite state machine with 3 states The parameters of the transition are given in tuples. Anyhow, anything iterable (e.g. a list) is possible. You can also name the parameters of the transition. For this purpose you take a dictionary:: sage: FiniteStateMachine([{'from_state':'a', 'to_state':'b', ....: 'word_in':0, 'word_out':1}, ....: {'from_state':'a', 'to_state':'c', ....: 'word_in':1, 'word_out':1}]) Finite state machine with 3 states Other arguments, which :class:`FSMTransition` accepts, can be added, too. #. The input-data can also be function acting as transition function: This function has two input arguments: #. a label of a state (from which the transition starts), #. a letter of the (input-)alphabet (as input-label of the transition). It returns a tuple with the following entries: #. a label of a state (to which state the transition goes), #. a letter of or a word over the (output-)alphabet (as output-label of the transition). It may also output a list of such tuples if several transitions from the from-state and the input letter exist (this means that the finite state machine is non-deterministic). If the transition does not exist, the function should raise a ``LookupError`` or return an empty list. When constructing a finite state machine in this way, some inital states and an input alphabet have to be specified. :: sage: def f(state_from, read): ....: if int(state_from) + read <= 2: ....: state_to = 2*int(state_from)+read ....: write = 0 ....: else: ....: state_to = 2*int(state_from) + read - 5 ....: write = 1 ....: return (str(state_to), write) sage: F = FiniteStateMachine(f, input_alphabet=[0, 1], ....: initial_states=['0'], ....: final_states=['0']) sage: F([1, 0, 1]) (True, '0', [0, 0, 1]) #. The input-data can be an other instance of a finite state machine:: sage: FiniteStateMachine(FiniteStateMachine([])) Traceback (most recent call last): ... NotImplementedError The following examples demonstrate the use of ``on_duplicate_transition``:: sage: F = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]]) sage: F.transitions() [Transition from 'a' to 'a': 1/2|-] :: sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error sage: F1 = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]], ....: on_duplicate_transition=duplicate_transition_raise_error) Traceback (most recent call last): ... ValueError: Attempting to re-insert transition Transition from 'a' to 'a': 1/2|- Use ``duplicate_transition_add_input`` to emulate a Markov chain, the input labels are considered as transition probabilities:: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: F = FiniteStateMachine([['a', 'a', 1/2], ['a', 'a', 1/2]], ....: on_duplicate_transition=duplicate_transition_add_input) sage: F.transitions() [Transition from 'a' to 'a': 1|-] Use ``with_final_word_out`` to construct final output:: sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)], ....: initial_states=[0], ....: final_states=[0], ....: with_final_word_out=0) sage: for s in T.iter_final_states(): ....: print s, s.final_word_out 0 [] 1 [0] TESTS:: sage: a = FSMState('S_a', 'a') sage: b = FSMState('S_b', 'b') sage: c = FSMState('S_c', 'c') sage: d = FSMState('S_d', 'd') sage: FiniteStateMachine({a:[b, c], b:[b, c, d], ....: c:[a, b], d:[a, c]}) Finite state machine with 4 states We have several constructions which lead to the same finite state machine:: sage: A = FSMState('A') sage: B = FSMState('B') sage: C = FSMState('C') sage: FSM1 = FiniteStateMachine( ....: {A:{B:{'word_in':0, 'word_out':1}, ....: C:{'word_in':1, 'word_out':1}}}) sage: FSM2 = FiniteStateMachine({A:{B:(0, 1), C:(1, 1)}}) sage: FSM3 = FiniteStateMachine( ....: {A:{B:FSMTransition(A, B, 0, 1), ....: C:FSMTransition(A, C, 1, 1)}}) sage: FSM4 = FiniteStateMachine({A:[(B, 0, 1), (C, 1, 1)]}) sage: FSM5 = FiniteStateMachine( ....: {A:[FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)]}) sage: FSM6 = FiniteStateMachine( ....: [{'from_state':A, 'to_state':B, 'word_in':0, 'word_out':1}, ....: {'from_state':A, 'to_state':C, 'word_in':1, 'word_out':1}]) sage: FSM7 = FiniteStateMachine([(A, B, 0, 1), (A, C, 1, 1)]) sage: FSM8 = FiniteStateMachine( ....: [FSMTransition(A, B, 0, 1), FSMTransition(A, C, 1, 1)]) sage: FSM1 == FSM2 == FSM3 == FSM4 == FSM5 == FSM6 == FSM7 == FSM8 True It is possible to skip ``FSMTransition`` in the example above. Some more tests for different input-data:: sage: FiniteStateMachine({'a':{'a':[0, 0], 'b':[1, 1]}, ....: 'b':{'b':[1, 0]}}) Finite state machine with 2 states sage: a = FSMState('S_a', 'a') sage: b = FSMState('S_b', 'b') sage: c = FSMState('S_c', 'c') sage: d = FSMState('S_d', 'd') sage: t1 = FSMTransition(a, b) sage: t2 = FSMTransition(b, c) sage: t3 = FSMTransition(b, d) sage: t4 = FSMTransition(c, d) sage: FiniteStateMachine([t1, t2, t3, t4]) Finite state machine with 4 states """ on_duplicate_transition = duplicate_transition_ignore """ Which function to call when a duplicate transition is inserted. See the documentation of the parameter ``on_duplicate_transition`` of the class :class:`FiniteStateMachine` for details. """ #************************************************************************* # init #************************************************************************* def __init__(self, data=None, initial_states=None, final_states=None, input_alphabet=None, output_alphabet=None, determine_alphabets=None, with_final_word_out=None, store_states_dict=True, on_duplicate_transition=None): """ See :class:`FiniteStateMachine` for more information. TEST:: sage: FiniteStateMachine() Finite state machine with 0 states """ self._states_ = [] # List of states in the finite state # machine. Each state stores a list of # outgoing transitions. if store_states_dict: self._states_dict_ = {} if initial_states is not None: if not hasattr(initial_states, '__iter__'): raise TypeError('Initial states must be iterable ' \ '(e.g. a list of states).') for s in initial_states: state = self.add_state(s) state.is_initial = True if final_states is not None: if not hasattr(final_states, '__iter__'): raise TypeError('Final states must be iterable ' \ '(e.g. a list of states).') for s in final_states: state = self.add_state(s) state.is_final = True self.input_alphabet = input_alphabet self.output_alphabet = output_alphabet if on_duplicate_transition is None: on_duplicate_transition = duplicate_transition_ignore if hasattr(on_duplicate_transition, '__call__'): self.on_duplicate_transition=on_duplicate_transition else: raise TypeError('on_duplicate_transition must be callable') if data is None: pass elif is_FiniteStateMachine(data): raise NotImplementedError elif hasattr(data, 'iteritems'): # data is a dict (or something similar), # format: key = from_state, value = iterator of transitions for (sf, iter_transitions) in data.iteritems(): self.add_state(sf) if hasattr(iter_transitions, 'iteritems'): for (st, transition) in iter_transitions.iteritems(): self.add_state(st) if is_FSMTransition(transition): self.add_transition(transition) elif hasattr(transition, 'iteritems'): self.add_transition(sf, st, **transition) elif hasattr(transition, '__iter__'): self.add_transition(sf, st, *transition) else: self.add_transition(sf, st, transition) elif hasattr(iter_transitions, '__iter__'): for transition in iter_transitions: if hasattr(transition, '__iter__'): L = [sf] L.extend(transition) elif is_FSMTransition(transition): L = transition else: L = [sf, transition] self.add_transition(L) else: raise TypeError('Wrong input data for transition.') if determine_alphabets is None and input_alphabet is None \ and output_alphabet is None: determine_alphabets = True elif hasattr(data, '__iter__'): # data is a something that is iterable, # items are transitions for transition in data: if is_FSMTransition(transition): self.add_transition(transition) elif hasattr(transition, 'iteritems'): self.add_transition(transition) elif hasattr(transition, '__iter__'): self.add_transition(transition) else: raise TypeError('Wrong input data for transition.') if determine_alphabets is None and input_alphabet is None \ and output_alphabet is None: determine_alphabets = True elif hasattr(data, '__call__'): self.add_from_transition_function(data) else: raise TypeError('Cannot decide what to do with data.') if determine_alphabets: self.determine_alphabets() if with_final_word_out is not None: self.construct_final_word_out(with_final_word_out) self._allow_composition_ = True #************************************************************************* # copy and hash #************************************************************************* def __copy__(self): """ Returns a (shallow) copy of the finite state machine. INPUT: Nothing. OUTPUT: A new finite state machine. TESTS:: sage: copy(FiniteStateMachine()) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError copy = __copy__ def empty_copy(self, memo=None, new_class=None): """ Returns an empty deep copy of the finite state machine, i.e., ``input_alphabet``, ``output_alphabet``, ``on_duplicate_transition`` are preserved, but states and transitions are not. INPUT: - ``memo`` -- a dictionary storing already processed elements. - ``new_class`` -- a class for the copy. By default (``None``), the class of ``self`` is used. OUTPUT: A new finite state machine. EXAMPLES:: sage: from sage.combinat.finite_state_machine import duplicate_transition_raise_error sage: F = FiniteStateMachine([('A', 'A', 0, 2), ('A', 'A', 1, 3)], ....: input_alphabet=[0, 1], ....: output_alphabet=[2, 3], ....: on_duplicate_transition=duplicate_transition_raise_error) sage: FE = F.empty_copy(); FE Finite state machine with 0 states sage: FE.input_alphabet [0, 1] sage: FE.output_alphabet [2, 3] sage: FE.on_duplicate_transition == duplicate_transition_raise_error True TESTS:: sage: T = Transducer() sage: type(T.empty_copy()) <class 'sage.combinat.finite_state_machine.Transducer'> sage: type(T.empty_copy(new_class=Automaton)) <class 'sage.combinat.finite_state_machine.Automaton'> """ if new_class is None: new = self.__class__() else: new = new_class() new.input_alphabet = deepcopy(self.input_alphabet, memo) new.output_alphabet = deepcopy(self.output_alphabet, memo) new.on_duplicate_transition = self.on_duplicate_transition return new def __deepcopy__(self, memo): """ Returns a deep copy of the finite state machine. INPUT: - ``memo`` -- a dictionary storing already processed elements. OUTPUT: A new finite state machine. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)]) sage: deepcopy(F) Finite state machine with 1 states """ relabel = hasattr(self, '_deepcopy_relabel_') new = self.empty_copy(memo=memo) relabel_iter = itertools.count(0) for state in self.iter_states(): if relabel: if self._deepcopy_labels_ is None: state._deepcopy_relabel_ = next(relabel_iter) elif hasattr(self._deepcopy_labels_, '__call__'): state._deepcopy_relabel_ = self._deepcopy_labels_(state.label()) elif hasattr(self._deepcopy_labels_, '__getitem__'): state._deepcopy_relabel_ = self._deepcopy_labels_[state.label()] else: raise TypeError("labels must be None, a callable " "or a dictionary.") s = deepcopy(state, memo) if relabel: del state._deepcopy_relabel_ new.add_state(s) for transition in self.iter_transitions(): new.add_transition(deepcopy(transition, memo)) return new def deepcopy(self, memo=None): """ Returns a deep copy of the finite state machine. INPUT: - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. OUTPUT: A new finite state machine. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'A', 0, 1), ('A', 'A', 1, 0)]) sage: deepcopy(F) Finite state machine with 1 states TESTS: Make sure that the links between transitions and states are still intact:: sage: C = deepcopy(F) sage: C.transitions()[0].from_state is C.state('A') True sage: C.transitions()[0].to_state is C.state('A') True """ return deepcopy(self, memo) def relabeled(self, memo=None, labels=None): """ Returns a deep copy of the finite state machine, but the states are relabeled. INPUT: - ``memo`` -- (default: ``None``) a dictionary storing already processed elements. - ``labels`` -- (default: ``None``) a dictionary or callable mapping old labels to new labels. If ``None``, then the new labels are integers starting with 0. OUTPUT: A new finite state machine. EXAMPLES:: sage: FSM1 = FiniteStateMachine([('A', 'B'), ('B', 'C'), ('C', 'A')]) sage: FSM1.states() ['A', 'B', 'C'] sage: FSM2 = FSM1.relabeled() sage: FSM2.states() [0, 1, 2] sage: FSM3 = FSM1.relabeled(labels={'A': 'a', 'B': 'b', 'C': 'c'}) sage: FSM3.states() ['a', 'b', 'c'] sage: FSM4 = FSM2.relabeled(labels=lambda x: 2*x) sage: FSM4.states() [0, 2, 4] TESTS:: sage: FSM2.relabeled(labels=1) Traceback (most recent call last): ... TypeError: labels must be None, a callable or a dictionary. """ self._deepcopy_relabel_ = True self._deepcopy_labels_ = labels new = deepcopy(self, memo) del self._deepcopy_relabel_ del self._deepcopy_labels_ return new def induced_sub_finite_state_machine(self, states): """ Returns a sub-finite-state-machine of the finite state machine induced by the given states. INPUT: - ``states`` -- a list (or an iterator) of states (either labels or instances of :class:`FSMState`) of the sub-finite-state-machine. OUTPUT: A new finite state machine. It consists (of deep copies) of the given states and (deep copies) of all transitions of ``self`` between these states. EXAMPLE:: sage: FSM = FiniteStateMachine([(0, 1, 0), (0, 2, 0), ....: (1, 2, 0), (2, 0, 0)]) sage: sub_FSM = FSM.induced_sub_finite_state_machine([0, 1]) sage: sub_FSM.states() [0, 1] sage: sub_FSM.transitions() [Transition from 0 to 1: 0|-] sage: FSM.induced_sub_finite_state_machine([3]) Traceback (most recent call last): ... ValueError: 3 is not a state of this finite state machine. TESTS: Make sure that the links between transitions and states are still intact:: sage: sub_FSM.transitions()[0].from_state is sub_FSM.state(0) True """ good_states = set() for state in states: if not self.has_state(state): raise ValueError("%s is not a state of this finite state machine." % state) good_states.add(self.state(state)) memo = {} new = self.empty_copy(memo=memo) for state in good_states: s = deepcopy(state, memo) new.add_state(s) for state in good_states: for transition in self.iter_transitions(state): if transition.to_state in good_states: new.add_transition(deepcopy(transition, memo)) return new def __hash__(self): """ Since finite state machines are mutable, they should not be hashable, so we return a type error. INPUT: Nothing. OUTPUT: The hash of this finite state machine. EXAMPLES:: sage: hash(FiniteStateMachine()) Traceback (most recent call last): ... TypeError: Finite state machines are mutable, and thus not hashable. """ if getattr(self, "_immutable", False): return hash((tuple(self.states()), tuple(self.transitions()))) raise TypeError("Finite state machines are mutable, " \ "and thus not hashable.") #************************************************************************* # operators #************************************************************************* def __or__(self, other): """ Returns the disjoint union of the finite state machines self and other. INPUT: - ``other`` -- a finite state machine. OUTPUT: A new finite state machine. TESTS:: sage: FiniteStateMachine() | FiniteStateMachine([('A', 'B')]) Traceback (most recent call last): ... NotImplementedError """ if is_FiniteStateMachine(other): return self.disjoint_union(other) __add__ = __or__ def __iadd__(self, other): """ TESTS:: sage: F = FiniteStateMachine() sage: F += FiniteStateMachine() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def __and__(self, other): """ Returns the intersection of ``self`` with ``other``. TESTS:: sage: FiniteStateMachine() & FiniteStateMachine([('A', 'B')]) Traceback (most recent call last): ... NotImplementedError """ if is_FiniteStateMachine(other): return self.intersection(other) def __imul__(self, other): """ TESTS:: sage: F = FiniteStateMachine() sage: F *= FiniteStateMachine() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def __call__(self, *args, **kwargs): """ .. WARNING:: The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting ``FSMOldProcessOutput`` to ``False``. Calls either method :meth:`.composition` or :meth:`.process` (with ``full_output=False``). By setting ``FSMOldProcessOutput`` to ``False`` the new desired output is produced. EXAMPLES:: sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False # activate new output behavior sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial=True, is_final=True) sage: binary_inverter = Transducer({A:[(A, 0, 1), (A, 1, 0)]}) sage: binary_inverter([0, 1, 0, 0, 1, 1]) [1, 0, 1, 1, 0, 0] :: sage: F = Transducer([('A', 'B', 1, 0), ('B', 'B', 1, 1), ....: ('B', 'B', 0, 0)], ....: initial_states=['A'], final_states=['B']) sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0), ....: (2, 2, 0, 1), (2, 1, 1, 1)], ....: initial_states=[1], final_states=[1]) sage: H = G(F) sage: H.states() [('A', 1), ('B', 1), ('B', 2)] """ if len(args) == 0: raise TypeError("Called with too few arguments.") if is_FiniteStateMachine(args[0]): return self.composition(*args, **kwargs) if hasattr(args[0], '__iter__'): if not kwargs.has_key('full_output'): kwargs['full_output'] = False return self.process(*args, **kwargs) raise TypeError("Do not know what to do with that arguments.") #************************************************************************* # tests #************************************************************************* def __nonzero__(self): """ Returns True if the finite state machine consists of at least one state. INPUT: Nothing. OUTPUT: True or False. TESTS:: sage: FiniteStateMachine().__nonzero__() False """ return len(self._states_) > 0 def __eq__(left, right): """ Returns ``True`` if the two finite state machines are equal, i.e., if they have the same states and the same transitions. INPUT: - ``left`` -- a finite state machine. - ``right`` -- a finite state machine. OUTPUT: ``True`` or ``False``. Note that this function compares all attributes of a state (by using :meth:`FSMState.fully_equal`) except for colors. Colors are handled as follows: If the colors coincide, then the finite state machines are also considered equal. If not, then they are considered as equal if both finite state machines are monochromatic. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 1)]) sage: F == FiniteStateMachine() False sage: G = FiniteStateMachine([('A', 'B', 1)], ....: initial_states=['A']) sage: F == G False sage: F.state('A').is_initial = True sage: F == G True This shows the behavior when the states have colors:: sage: F.state('A').color = 'red' sage: G.state('A').color = 'red' sage: F == G True sage: G.state('A').color = 'blue' sage: F == G False sage: F.state('B').color = 'red' sage: F.is_monochromatic() True sage: G.state('B').color = 'blue' sage: G.is_monochromatic() True sage: F == G True """ if not is_FiniteStateMachine(right): raise TypeError('Only instances of FiniteStateMachine ' 'can be compared.') if len(left._states_) != len(right._states_): return False colors_equal = True for state in left.iter_states(): try: right_state = right.state(state.label()) except LookupError: return False # we handle colors separately if not state.fully_equal(right_state, compare_color=False): return False if state.color != right_state.color: colors_equal = False left_transitions = state.transitions right_transitions = right.state(state).transitions if len(left_transitions) != len(right_transitions): return False for t in left_transitions: if t not in right_transitions: return False # handle colors if colors_equal: return True if left.is_monochromatic() and right.is_monochromatic(): return True return False def __ne__(left, right): """ Tests for inequality, complement of :meth:`.__eq__`. INPUT: - ``left`` -- a finite state machine. - ``right`` -- a finite state machine. OUTPUT: True or False. EXAMPLES:: sage: E = FiniteStateMachine([('A', 'B', 0)]) sage: F = Automaton([('A', 'B', 0)]) sage: G = Transducer([('A', 'B', 0, 1)]) sage: E == F True sage: E == G False """ return (not (left == right)) def __contains__(self, item): """ Returns true, if the finite state machine contains the state or transition item. Note that only the labels of the states and the input and output words are tested. INPUT: - ``item`` -- a state or a transition. OUTPUT: True or False. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: F = FiniteStateMachine([('A', 'B', 0), ('B', 'A', 1)]) sage: FSMState('A', is_initial=True) in F True sage: 'A' in F False sage: FSMTransition('A', 'B', 0) in F True """ if is_FSMState(item): return self.has_state(item) if is_FSMTransition(item): return self.has_transition(item) return False def is_Markov_chain(self, is_zero=None): """ Checks whether ``self`` is a Markov chain where the transition probabilities are modeled as input labels. INPUT: - ``is_zero`` -- by default (``is_zero=None``), checking for zero is simply done by :meth:`~sage.structure.element.Element.is_zero`. This parameter can be used to provide a more sophisticated check for zero, e.g. in the case of symbolic probabilities, see the examples below. OUTPUT: ``True`` or ``False``. :attr:`on_duplicate_transition` must be :func:`duplicate_transition_add_input` and the sum of the input weights of the transitions leaving a state must add up to 1. EXAMPLES:: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1], ....: [1, 0, 1/2, 0], [1, 1, 1/2, 1]], ....: on_duplicate_transition=duplicate_transition_add_input) sage: F.is_Markov_chain() True :attr:`on_duplicate_transition` must be :func:`duplicate_transition_add_input`:: sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1], ....: [1, 0, 1/2, 0], [1, 1, 1/2, 1]]) sage: F.is_Markov_chain() False Sum of input labels of the transitions leaving states must be 1:: sage: F = Transducer([[0, 0, 1/4, 0], [0, 1, 3/4, 1], ....: [1, 0, 1/2, 0]], ....: on_duplicate_transition=duplicate_transition_add_input) sage: F.is_Markov_chain() False If the probabilities are variables in the symbolic ring, :func:`~sage.symbolic.assumptions.assume` will do the trick:: sage: var('p q') (p, q) sage: F = Transducer([(0, 0, p, 1), (0, 0, q, 0)], ....: on_duplicate_transition=duplicate_transition_add_input) sage: assume(p + q == 1) sage: (p + q - 1).is_zero() True sage: F.is_Markov_chain() True sage: forget() sage: del(p, q) If the probabilities are variables in some polynomial ring, the parameter ``is_zero`` can be used:: sage: R.<p, q> = PolynomialRing(QQ) sage: def is_zero_polynomial(polynomial): ....: return polynomial in (p + q - 1)*R sage: F = Transducer([(0, 0, p, 1), (0, 0, q, 0)], ....: on_duplicate_transition=duplicate_transition_add_input) sage: F.is_Markov_chain() False sage: F.is_Markov_chain(is_zero_polynomial) True """ is_zero_function = default_is_zero if is_zero is not None: is_zero_function = is_zero if self.on_duplicate_transition != duplicate_transition_add_input: return False return all(is_zero_function(sum(t.word_in[0] for t in state.transitions) - 1) for state in self.states()) #************************************************************************* # representations / LaTeX #************************************************************************* def _repr_(self): """ Represents the finite state machine as "Finite state machine with n states" where n is the number of states. INPUT: Nothing. OUTPUT: A string. EXAMPLES:: sage: FiniteStateMachine()._repr_() 'Finite state machine with 0 states' """ return "Finite state machine with %s states" % len(self._states_) default_format_letter = latex format_letter = default_format_letter def format_letter_negative(self, letter): r""" Format negative numbers as overlined numbers, everything else by standard LaTeX formatting. INPUT: ``letter`` -- anything. OUTPUT: Overlined absolute value if letter is a negative integer, :func:`latex(letter) <sage.misc.latex.latex>` otherwise. EXAMPLES:: sage: A = Automaton([(0, 0, -1)]) sage: map(A.format_letter_negative, [-1, 0, 1, 'a', None]) ['\\overline{1}', 0, 1, \text{\texttt{a}}, \mbox{\rm None}] sage: A.latex_options(format_letter=A.format_letter_negative) sage: print(latex(A)) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state] (v0) at (3.000000, 0.000000) {$0$}; \path[->] (v0) edge[loop above] node {$\overline{1}$} (); \end{tikzpicture} """ if letter in ZZ and letter < 0: return r'\overline{%d}' % -letter else: return latex(letter) def format_transition_label_reversed(self, word): r""" Format words in transition labels in reversed order. INPUT: ``word`` -- list of letters. OUTPUT: String representation of ``word`` suitable to be typeset in mathematical mode, letters are written in reversed order. This is the reversed version of :meth:`.default_format_transition_label`. In digit expansions, digits are frequently processed from the least significant to the most significant position, but it is customary to write the least significant digit at the right-most position. Therefore, the labels have to be reversed. EXAMPLE:: sage: T = Transducer([(0, 0, 0, [1, 2, 3])]) sage: T.format_transition_label_reversed([1, 2, 3]) '3 2 1' sage: T.latex_options(format_transition_label=T.format_transition_label_reversed) sage: print latex(T) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state] (v0) at (3.000000, 0.000000) {$0$}; \path[->] (v0) edge[loop above] node {$0\mid 3 2 1$} (); \end{tikzpicture} TEST: Check that #16357 is fixed:: sage: T = Transducer() sage: T.format_transition_label_reversed([]) '\\varepsilon' """ return self.default_format_transition_label(reversed(word)) def default_format_transition_label(self, word): r""" Default formatting of words in transition labels for LaTeX output. INPUT: ``word`` -- list of letters OUTPUT: String representation of ``word`` suitable to be typeset in mathematical mode. - For a non-empty word: Concatenation of the letters, piped through ``self.format_letter`` and separated by blanks. - For an empty word: ``sage.combinat.finite_state_machine.EmptyWordLaTeX``. There is also a variant :meth:`.format_transition_label_reversed` writing the words in reversed order. EXAMPLES: #. Example of a non-empty word:: sage: T = Transducer() sage: print T.default_format_transition_label( ....: ['a', 'alpha', 'a_1', '0', 0, (0, 1)]) \text{\texttt{a}} \text{\texttt{alpha}} \text{\texttt{a{\char`\_}1}} 0 0 \left(0, 1\right) #. In the example above, ``'a'`` and ``'alpha'`` should perhaps be symbols:: sage: var('a alpha a_1') (a, alpha, a_1) sage: print T.default_format_transition_label([a, alpha, a_1]) a \alpha a_{1} #. Example of an empty word:: sage: print T.default_format_transition_label([]) \varepsilon We can change this by setting ``sage.combinat.finite_state_machine.EmptyWordLaTeX``:: sage: sage.combinat.finite_state_machine.EmptyWordLaTeX = '' sage: T.default_format_transition_label([]) '' Finally, we restore the default value:: sage: sage.combinat.finite_state_machine.EmptyWordLaTeX = r'\varepsilon' #. This method is the default value for ``FiniteStateMachine.format_transition_label``. That can be changed to be any other function:: sage: A = Automaton([(0, 1, 0)]) sage: def custom_format_transition_label(word): ....: return "t" sage: A.latex_options(format_transition_label=custom_format_transition_label) sage: print latex(A) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state] (v0) at (3.000000, 0.000000) {$0$}; \node[state] (v1) at (-3.000000, 0.000000) {$1$}; \path[->] (v0) edge node[rotate=360.00, anchor=south] {$t$} (v1); \end{tikzpicture} TEST: Check that #16357 is fixed:: sage: T = Transducer() sage: T.default_format_transition_label([]) '\\varepsilon' sage: T.default_format_transition_label(iter([])) '\\varepsilon' """ result = " ".join(imap(self.format_letter, word)) if result: return result else: return EmptyWordLaTeX format_transition_label = default_format_transition_label def latex_options(self, coordinates=None, format_state_label=None, format_letter=None, format_transition_label=None, loop_where=None, initial_where=None, accepting_style=None, accepting_distance=None, accepting_where=None, accepting_show_empty=None): r""" Set options for LaTeX output via :func:`~sage.misc.latex.latex` and therefore :func:`~sage.misc.latex.view`. INPUT: - ``coordinates`` -- a dictionary or a function mapping labels of states to pairs interpreted as coordinates. If no coordinates are given, states a placed equidistantly on a circle of radius `3`. See also :meth:`.set_coordinates`. - ``format_state_label`` -- a function mapping labels of states to a string suitable for typesetting in LaTeX's mathematics mode. If not given, :func:`~sage.misc.latex.latex` is used. - ``format_letter`` -- a function mapping letters of the input and output alphabets to a string suitable for typesetting in LaTeX's mathematics mode. If not given, :meth:`.default_format_transition_label` uses :func:`~sage.misc.latex.latex`. - ``format_transition_label`` -- a function mapping words over the input and output alphabets to a string suitable for typesetting in LaTeX's mathematics mode. If not given, :meth:`.default_format_transition_label` is used. - ``loop_where`` -- a dictionary or a function mapping labels of initial states to one of ``'above'``, ``'left'``, ``'below'``, ``'right'``. If not given, ``'above'`` is used. - ``initial_where`` -- a dictionary or a function mapping labels of initial states to one of ``'above'``, ``'left'``, ``'below'``, ``'right'``. If not given, TikZ' default (currently ``'left'``) is used. - ``accepting_style`` -- one of ``'accepting by double'`` and ``'accepting by arrow'``. If not given, ``'accepting by double'`` is used unless there are non-empty final output words. - ``accepting_distance`` -- a string giving a LaTeX length used for the length of the arrow leading from a final state. If not given, TikZ' default (currently ``'3ex'``) is used unless there are non-empty final output words, in which case ``'7ex'`` is used. - ``accepting_where`` -- a dictionary or a function mapping labels of final states to one of ``'above'``, ``'left'``, ``'below'``, ``'right'``. If not given, TikZ' default (currently ``'right'``) is used. If the final state has a final output word, it is also possible to give an angle in degrees. - ``accepting_show_empty`` -- if ``True`` the arrow of an empty final output word is labeled as well. Note that this implicitly implies ``accepting_style='accepting by arrow'``. If not given, the default ``False`` is used. OUTPUT: Nothing. As TikZ (cf. the :wikipedia:`PGF/TikZ`) is used to typeset the graphics, the syntax is oriented on TikZ' syntax. This is a convenience function collecting all options for LaTeX output. All of its functionality can also be achieved by directly setting the attributes - ``coordinates``, ``format_label``, ``loop_where``, ``initial_where``, and ``accepting_where`` of :class:`FSMState` (here, ``format_label`` is a callable without arguments, everything else is a specific value); - ``format_label`` of :class:`FSMTransition` (``format_label`` is a callable without arguments); - ``format_state_label``, ``format_letter``, ``format_transition_label``, ``accepting_style``, ``accepting_distance``, and ``accepting_show_empty`` of :class:`FiniteStateMachine`. This function, however, also (somewhat) checks its input and serves to collect documentation on all these options. The function can be called several times, only those arguments which are not ``None`` are taken into account. By the same means, it can be combined with directly setting some attributes as outlined above. EXAMPLES: See also the section on :ref:`finite_state_machine_LaTeX_output` in the introductory examples of this module. :: sage: T = Transducer(initial_states=[4], ....: final_states=[0, 3]) sage: for j in srange(4): ....: T.add_transition(4, j, 0, [0, j]) ....: T.add_transition(j, 4, 0, [0, -j]) ....: T.add_transition(j, j, 0, 0) Transition from 4 to 0: 0|0,0 Transition from 0 to 4: 0|0,0 Transition from 0 to 0: 0|0 Transition from 4 to 1: 0|0,1 Transition from 1 to 4: 0|0,-1 Transition from 1 to 1: 0|0 Transition from 4 to 2: 0|0,2 Transition from 2 to 4: 0|0,-2 Transition from 2 to 2: 0|0 Transition from 4 to 3: 0|0,3 Transition from 3 to 4: 0|0,-3 Transition from 3 to 3: 0|0 sage: T.add_transition(4, 4, 0, 0) Transition from 4 to 4: 0|0 sage: T.state(3).final_word_out = [0, 0] sage: T.latex_options( ....: coordinates={4: (0, 0), ....: 0: (-6, 3), ....: 1: (-2, 3), ....: 2: (2, 3), ....: 3: (6, 3)}, ....: format_state_label=lambda x: r'\mathbf{%s}' % x, ....: format_letter=lambda x: r'w_{%s}' % x, ....: format_transition_label=lambda x: ....: r"{\scriptstyle %s}" % T.default_format_transition_label(x), ....: loop_where={4: 'below', 0: 'left', 1: 'above', ....: 2: 'right', 3:'below'}, ....: initial_where=lambda x: 'above', ....: accepting_style='accepting by double', ....: accepting_distance='10ex', ....: accepting_where={0: 'left', 3: 45} ....: ) sage: T.state(4).format_label=lambda: r'\mathcal{I}' sage: latex(T) \begin{tikzpicture}[auto, initial text=, >=latex] \node[state, initial, initial where=above] (v0) at (0.000000, 0.000000) {$\mathcal{I}$}; \node[state, accepting, accepting where=left] (v1) at (-6.000000, 3.000000) {$\mathbf{0}$}; \node[state, accepting, accepting where=45] (v2) at (6.000000, 3.000000) {$\mathbf{3}$}; \path[->] (v2.45.00) edge node[rotate=45.00, anchor=south] {$\$ \mid {\scriptstyle w_{0} w_{0}}$} ++(45.00:10ex); \node[state] (v3) at (-2.000000, 3.000000) {$\mathbf{1}$}; \node[state] (v4) at (2.000000, 3.000000) {$\mathbf{2}$}; \path[->] (v1) edge[loop left] node[rotate=90, anchor=south] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0}}$} (); \path[->] (v1.-21.57) edge node[rotate=-26.57, anchor=south] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{0}}$} (v0.148.43); \path[->] (v3) edge[loop above] node {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0}}$} (); \path[->] (v3.-51.31) edge node[rotate=-56.31, anchor=south] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{-1}}$} (v0.118.69); \path[->] (v4) edge[loop right] node[rotate=90, anchor=north] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0}}$} (); \path[->] (v4.-118.69) edge node[rotate=56.31, anchor=north] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{-2}}$} (v0.51.31); \path[->] (v2) edge[loop below] node {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0}}$} (); \path[->] (v2.-148.43) edge node[rotate=26.57, anchor=north] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{-3}}$} (v0.21.57); \path[->] (v0.158.43) edge node[rotate=333.43, anchor=north] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{0}}$} (v1.328.43); \path[->] (v0.128.69) edge node[rotate=303.69, anchor=north] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{1}}$} (v3.298.69); \path[->] (v0.61.31) edge node[rotate=56.31, anchor=south] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{2}}$} (v4.231.31); \path[->] (v0.31.57) edge node[rotate=26.57, anchor=south] {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0} w_{3}}$} (v2.201.57); \path[->] (v0) edge[loop below] node {${\scriptstyle w_{0}}\mid {\scriptstyle w_{0}}$} (); \end{tikzpicture} sage: view(T) # not tested To actually see this, use the live documentation in the Sage notebook and execute the cells. By changing some of the options, we get the following output:: sage: T.latex_options( ....: format_transition_label=T.default_format_transition_label, ....: accepting_style='accepting by arrow', ....: accepting_show_empty=True ....: ) sage: latex(T) \begin{tikzpicture}[auto, initial text=, >=latex, accepting text=, accepting/.style=accepting by arrow, accepting distance=10ex] \node[state, initial, initial where=above] (v0) at (0.000000, 0.000000) {$\mathcal{I}$}; \node[state] (v1) at (-6.000000, 3.000000) {$\mathbf{0}$}; \path[->] (v1.180.00) edge node[rotate=360.00, anchor=south] {$\$ \mid \varepsilon$} ++(180.00:10ex); \node[state] (v2) at (6.000000, 3.000000) {$\mathbf{3}$}; \path[->] (v2.45.00) edge node[rotate=45.00, anchor=south] {$\$ \mid w_{0} w_{0}$} ++(45.00:10ex); \node[state] (v3) at (-2.000000, 3.000000) {$\mathbf{1}$}; \node[state] (v4) at (2.000000, 3.000000) {$\mathbf{2}$}; \path[->] (v1) edge[loop left] node[rotate=90, anchor=south] {$w_{0}\mid w_{0}$} (); \path[->] (v1.-21.57) edge node[rotate=-26.57, anchor=south] {$w_{0}\mid w_{0} w_{0}$} (v0.148.43); \path[->] (v3) edge[loop above] node {$w_{0}\mid w_{0}$} (); \path[->] (v3.-51.31) edge node[rotate=-56.31, anchor=south] {$w_{0}\mid w_{0} w_{-1}$} (v0.118.69); \path[->] (v4) edge[loop right] node[rotate=90, anchor=north] {$w_{0}\mid w_{0}$} (); \path[->] (v4.-118.69) edge node[rotate=56.31, anchor=north] {$w_{0}\mid w_{0} w_{-2}$} (v0.51.31); \path[->] (v2) edge[loop below] node {$w_{0}\mid w_{0}$} (); \path[->] (v2.-148.43) edge node[rotate=26.57, anchor=north] {$w_{0}\mid w_{0} w_{-3}$} (v0.21.57); \path[->] (v0.158.43) edge node[rotate=333.43, anchor=north] {$w_{0}\mid w_{0} w_{0}$} (v1.328.43); \path[->] (v0.128.69) edge node[rotate=303.69, anchor=north] {$w_{0}\mid w_{0} w_{1}$} (v3.298.69); \path[->] (v0.61.31) edge node[rotate=56.31, anchor=south] {$w_{0}\mid w_{0} w_{2}$} (v4.231.31); \path[->] (v0.31.57) edge node[rotate=26.57, anchor=south] {$w_{0}\mid w_{0} w_{3}$} (v2.201.57); \path[->] (v0) edge[loop below] node {$w_{0}\mid w_{0}$} (); \end{tikzpicture} sage: view(T) # not tested TESTS:: sage: T.latex_options(format_state_label='Nothing') Traceback (most recent call last): ... TypeError: format_state_label must be callable. sage: T.latex_options(format_letter='') Traceback (most recent call last): ... TypeError: format_letter must be callable. sage: T.latex_options(format_transition_label='') Traceback (most recent call last): ... TypeError: format_transition_label must be callable. sage: T.latex_options(loop_where=37) Traceback (most recent call last): ... TypeError: loop_where must be a callable or a dictionary. sage: T.latex_options(loop_where=lambda x: 'top') Traceback (most recent call last): ... ValueError: loop_where for 4 must be in ['below', 'right', 'above', 'left']. sage: T.latex_options(initial_where=90) Traceback (most recent call last): ... TypeError: initial_where must be a callable or a dictionary. sage: T.latex_options(initial_where=lambda x: 'top') Traceback (most recent call last): ... ValueError: initial_where for 4 must be in ['below', 'right', 'above', 'left']. sage: T.latex_options(accepting_style='fancy') Traceback (most recent call last): ... ValueError: accepting_style must be in ['accepting by double', 'accepting by arrow']. sage: T.latex_options(accepting_where=90) Traceback (most recent call last): ... TypeError: accepting_where must be a callable or a dictionary. sage: T.latex_options(accepting_where=lambda x: 'top') Traceback (most recent call last): ... ValueError: accepting_where for 0 must be in ['below', 'right', 'above', 'left']. sage: T.latex_options(accepting_where={0: 'above', 3: 'top'}) Traceback (most recent call last): ... ValueError: accepting_where for 3 must be a real number or be in ['below', 'right', 'above', 'left']. """ if coordinates is not None: self.set_coordinates(coordinates) if format_state_label is not None: if not hasattr(format_state_label, '__call__'): raise TypeError('format_state_label must be callable.') self.format_state_label = format_state_label if format_letter is not None: if not hasattr(format_letter, '__call__'): raise TypeError('format_letter must be callable.') self.format_letter = format_letter if format_transition_label is not None: if not hasattr(format_transition_label, '__call__'): raise TypeError('format_transition_label must be callable.') self.format_transition_label = format_transition_label if loop_where is not None: permissible = list(tikz_automata_where.iterkeys()) for state in self.states(): if hasattr(loop_where, '__call__'): where = loop_where(state.label()) else: try: where = loop_where[state.label()] except TypeError: raise TypeError("loop_where must be a " "callable or a dictionary.") except KeyError: continue if where in permissible: state.loop_where = where else: raise ValueError('loop_where for %s must be in %s.' % (state.label(), permissible)) if initial_where is not None: permissible = list(tikz_automata_where.iterkeys()) for state in self.iter_initial_states(): if hasattr(initial_where, '__call__'): where = initial_where(state.label()) else: try: where = initial_where[state.label()] except TypeError: raise TypeError("initial_where must be a " "callable or a dictionary.") except KeyError: continue if where in permissible: state.initial_where = where else: raise ValueError('initial_where for %s must be in %s.' % (state.label(), permissible)) if accepting_style is not None: permissible = ['accepting by double', 'accepting by arrow'] if accepting_style in permissible: self.accepting_style = accepting_style else: raise ValueError('accepting_style must be in %s.' % permissible) if accepting_distance is not None: self.accepting_distance = accepting_distance if accepting_where is not None: permissible = list(tikz_automata_where.iterkeys()) for state in self.iter_final_states(): if hasattr(accepting_where, '__call__'): where = accepting_where(state.label()) else: try: where = accepting_where[state.label()] except TypeError: raise TypeError("accepting_where must be a " "callable or a dictionary.") except KeyError: continue if where in permissible: state.accepting_where = where elif hasattr(state, 'final_word_out') \ and state.final_word_out: if where in RR: state.accepting_where = where else: raise ValueError('accepting_where for %s must ' 'be a real number or be in %s.' % (state.label(), permissible)) else: raise ValueError('accepting_where for %s must be in %s.' % (state.label(), permissible)) if accepting_show_empty is not None: self.accepting_show_empty = accepting_show_empty def _latex_(self): r""" Returns a LaTeX code for the graph of the finite state machine. INPUT: Nothing. OUTPUT: A string. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 1, 2)], ....: initial_states=['A'], ....: final_states=['B']) sage: F.state('A').initial_where='below' sage: print latex(F) # indirect doctest \begin{tikzpicture}[auto, initial text=, >=latex] \node[state, initial, initial where=below] (v0) at (3.000000, 0.000000) {$\text{\texttt{A}}$}; \node[state, accepting] (v1) at (-3.000000, 0.000000) {$\text{\texttt{B}}$}; \path[->] (v0) edge node[rotate=360.00, anchor=south] {$ $} (v1); \end{tikzpicture} """ def label_rotation(angle, both_directions): """ Given an angle of a transition, compute the TikZ string to rotate the label. """ angle_label = angle anchor_label = "south" if angle > 90 or angle <= -90: angle_label = angle + 180 if both_directions: # if transitions in both directions, the transition to the # left has its label below the transition, otherwise above anchor_label = "north" return "rotate=%.2f, anchor=%s" % (angle_label, anchor_label) setup_latex_preamble() options = ["auto", "initial text=", ">=latex"] nonempty_final_word_out = False for state in self.iter_final_states(): if state.final_word_out: nonempty_final_word_out = True break if hasattr(self, "accepting_style"): accepting_style = self.accepting_style elif nonempty_final_word_out: accepting_style = "accepting by arrow" else: accepting_style = "accepting by double" if accepting_style == "accepting by arrow": options.append("accepting text=") options.append("accepting/.style=%s" % accepting_style) if hasattr(self, "accepting_distance"): accepting_distance = self.accepting_distance elif nonempty_final_word_out: accepting_distance = "7ex" else: accepting_distance = None if accepting_style == "accepting by arrow" and accepting_distance: options.append("accepting distance=%s" % accepting_distance) if hasattr(self, "accepting_show_empty"): accepting_show_empty = self.accepting_show_empty else: accepting_show_empty = False result = "\\begin{tikzpicture}[%s]\n" % ", ".join(options) j = 0; for vertex in self.iter_states(): if not hasattr(vertex, "coordinates"): vertex.coordinates = (3*cos(2*pi*j/len(self.states())), 3*sin(2*pi*j/len(self.states()))) options = "" if vertex.is_final: if not (vertex.final_word_out and accepting_style == "accepting by arrow") \ and not accepting_show_empty: # otherwise, we draw a custom made accepting path # with label below options += ", accepting" if hasattr(vertex, "accepting_where"): options += ", accepting where=%s" % ( vertex.accepting_where,) if vertex.is_initial: options += ", initial" if hasattr(vertex, "initial_where"): options += ", initial where=%s" % vertex.initial_where if hasattr(vertex, "format_label"): label = vertex.format_label() elif hasattr(self, "format_state_label"): label = self.format_state_label(vertex) else: label = latex(vertex.label()) result += "\\node[state%s] (v%d) at (%f, %f) {$%s$};\n" % ( options, j, vertex.coordinates[0], vertex.coordinates[1], label) vertex._number_ = j if vertex.is_final and (vertex.final_word_out or accepting_show_empty): angle = 0 if hasattr(vertex, "accepting_where"): angle = tikz_automata_where.get(vertex.accepting_where, vertex.accepting_where) result += "\\path[->] (v%d.%.2f) edge node[%s] {$%s \mid %s$} ++(%.2f:%s);\n" % ( j, angle, label_rotation(angle, False), EndOfWordLaTeX, self.format_transition_label(vertex.final_word_out), angle, accepting_distance) j += 1 # We use an OrderedDict instead of a dict in order to have a # defined ordering of the transitions in the output. See # http://trac.sagemath.org/ticket/16580#comment:3 . As the # transitions have to be sorted anyway, the performance # penalty should be bearable; nevertheless, this is only # required for doctests. adjacent = OrderedDict( (pair, list(transitions)) for pair, transitions in itertools.groupby( sorted(self.iter_transitions(), key=key_function), key=key_function )) for ((source, target), transitions) in adjacent.iteritems(): if len(transitions) > 0: labels = [] for transition in transitions: if hasattr(transition, "format_label"): labels.append(transition.format_label()) else: labels.append(self._latex_transition_label_( transition, self.format_transition_label)) label = ", ".join(labels) if source != target: angle = atan2( target.coordinates[1] - source.coordinates[1], target.coordinates[0] - source.coordinates[0]) * 180/pi both_directions = (target, source) in adjacent if both_directions: angle_source = ".%.2f" % ((angle + 5).n(),) angle_target = ".%.2f" % ((angle + 175).n(),) else: angle_source = "" angle_target = "" result += "\\path[->] (v%d%s) edge node[%s] {$%s$} (v%d%s);\n" % ( source._number_, angle_source, label_rotation(angle, both_directions), label, target._number_, angle_target) else: loop_where = "above" if hasattr(source, "loop_where"): loop_where = source.loop_where rotation = {'left': '[rotate=90, anchor=south]', 'right': '[rotate=90, anchor=north]'} result += "\\path[->] (v%d) edge[loop %s] node%s {$%s$} ();\n" % ( source._number_, loop_where, rotation.get(loop_where, ''), label) result += "\\end{tikzpicture}" return result def _latex_transition_label_(self, transition, format_function=latex): r""" Returns the proper transition label. INPUT: - ``transition`` - a transition - ``format_function`` - a function formatting the labels OUTPUT: A string. TESTS:: sage: F = FiniteStateMachine([('A', 'B', 0, 1)]) sage: t = F.transitions()[0] sage: F._latex_transition_label_(t) ' ' """ return ' ' def set_coordinates(self, coordinates, default=True): """ Set coordinates of the states for the LaTeX representation by a dictionary or a function mapping labels to coordinates. INPUT: - ``coordinates`` -- a dictionary or a function mapping labels of states to pairs interpreted as coordinates. - ``default`` -- If ``True``, then states not given by ``coordinates`` get a default position on a circle of radius 3. OUTPUT: Nothing. EXAMPLES:: sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]]) sage: F.set_coordinates({0: (0, 0), 1: (2, 0), 2: (1, 1)}) sage: F.state(0).coordinates (0, 0) We can also use a function to determine the coordinates:: sage: F = Automaton([[0, 1, 1], [1, 2, 2], [2, 0, 0]]) sage: F.set_coordinates(lambda l: (l, 3/(l+1))) sage: F.state(2).coordinates (2, 1) """ states_without_coordinates = [] for state in self.iter_states(): try: state.coordinates = coordinates[state.label()] continue except (KeyError, TypeError): pass try: state.coordinates = coordinates(state.label()) continue except TypeError: pass states_without_coordinates.append(state) if default: n = len(states_without_coordinates) for j, state in enumerate(states_without_coordinates): state.coordinates = (3*cos(2*pi*j/n), 3*sin(2*pi*j/n)) #************************************************************************* # other #************************************************************************* def _matrix_(self, R=None): """ Returns the adjacency matrix of the finite state machine. See :meth:`.adjacency_matrix` for more information. EXAMPLES:: sage: B = FiniteStateMachine({0: {0: (0, 0), 'a': (1, 0)}, ....: 'a': {2: (0, 0), 3: (1, 0)}, ....: 2:{0:(1, 1), 4:(0, 0)}, ....: 3:{'a':(0, 1), 2:(1, 1)}, ....: 4:{4:(1, 1), 3:(0, 1)}}, ....: initial_states=[0]) sage: B._matrix_() [1 1 0 0 0] [0 0 1 1 0] [x 0 0 0 1] [0 x x 0 0] [0 0 0 x x] """ return self.adjacency_matrix() def adjacency_matrix(self, input=None, entry=None): """ Returns the adjacency matrix of the underlying graph. INPUT: - ``input`` -- Only transitions with input label ``input`` are respected. - ``entry`` -- The function ``entry`` takes a transition and the return value is written in the matrix as the entry ``(transition.from_state, transition.to_state)``. The default value (``None``) of entry takes the variable ``x`` to the power of the sum of the output word of the transition. OUTPUT: A matrix. If any label of a state is not an integer, the finite state machine is relabeled at the beginning. If there are more than one transitions between two states, then the different return values of ``entry`` are added up. EXAMPLES:: sage: B = FiniteStateMachine({0:{0:(0, 0), 'a':(1, 0)}, ....: 'a':{2:(0, 0), 3:(1, 0)}, ....: 2:{0:(1, 1), 4:(0, 0)}, ....: 3:{'a':(0, 1), 2:(1, 1)}, ....: 4:{4:(1, 1), 3:(0, 1)}}, ....: initial_states=[0]) sage: B.adjacency_matrix() [1 1 0 0 0] [0 0 1 1 0] [x 0 0 0 1] [0 x x 0 0] [0 0 0 x x] This is equivalent to:: sage: matrix(B) [1 1 0 0 0] [0 0 1 1 0] [x 0 0 0 1] [0 x x 0 0] [0 0 0 x x] It is also possible to use other entries in the adjacency matrix:: sage: B.adjacency_matrix(entry=(lambda transition: 1)) [1 1 0 0 0] [0 0 1 1 0] [1 0 0 0 1] [0 1 1 0 0] [0 0 0 1 1] sage: B.adjacency_matrix(1, entry=(lambda transition: ....: exp(I*transition.word_out[0]*var('t')))) [ 0 1 0 0 0] [ 0 0 0 1 0] [e^(I*t) 0 0 0 0] [ 0 0 e^(I*t) 0 0] [ 0 0 0 0 e^(I*t)] sage: a = Automaton([(0, 1, 0), ....: (1, 2, 0), ....: (2, 0, 1), ....: (2, 1, 0)], ....: initial_states=[0], ....: final_states=[0]) sage: a.adjacency_matrix() [0 1 0] [0 0 1] [1 1 0] """ if entry is None: entry = default_function relabeledFSM = self l = len(relabeledFSM.states()) for state in self.iter_states(): if state.label() not in ZZ or state.label() >= l \ or state.label() < 0: relabeledFSM = self.relabeled() break dictionary = {} for transition in relabeledFSM.iter_transitions(): if input is None or transition.word_in == [input]: if (transition.from_state.label(), transition.to_state.label()) in dictionary: dictionary[(transition.from_state.label(), transition.to_state.label())] \ += entry(transition) else: dictionary[(transition.from_state.label(), transition.to_state.label())] \ = entry(transition) return matrix(len(relabeledFSM.states()), dictionary) def determine_alphabets(self, reset=True): """ Determines the input and output alphabet according to the transitions in self. INPUT: - ``reset`` -- If reset is ``True``, then the existing input and output alphabets are erased, otherwise new letters are appended to the existing alphabets. OUTPUT: Nothing. After this operation the input alphabet and the output alphabet of self are a list of letters. .. TODO:: At the moment, the letters of the alphabets need to be hashable. EXAMPLES:: sage: T = Transducer([(1, 1, 1, 0), (1, 2, 2, 1), ....: (2, 2, 1, 1), (2, 2, 0, 0)], ....: final_states=[1], ....: determine_alphabets=False) sage: T.state(1).final_word_out = [1, 4] sage: (T.input_alphabet, T.output_alphabet) (None, None) sage: T.determine_alphabets() sage: (T.input_alphabet, T.output_alphabet) ([0, 1, 2], [0, 1, 4]) """ if reset: ain = set() aout = set() else: ain = set(self.input_alphabet) aout = set(self.output_alphabet) for t in self.iter_transitions(): for letter in t.word_in: ain.add(letter) for letter in t.word_out: aout.add(letter) for s in self.iter_final_states(): for letter in s.final_word_out: aout.add(letter) self.input_alphabet = list(ain) self.output_alphabet = list(aout) #************************************************************************* # get states and transitions #************************************************************************* def states(self): """ Returns the states of the finite state machine. INPUT: Nothing. OUTPUT: The states of the finite state machine as list. EXAMPLES:: sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)]) sage: FSM.states() ['1', '2'] """ return copy(self._states_) def iter_states(self): """ Returns an iterator of the states. INPUT: Nothing. OUTPUT: An iterator of the states of the finite state machine. EXAMPLES:: sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)]) sage: [s.label() for s in FSM.iter_states()] ['1', '2'] """ return iter(self._states_) def transitions(self, from_state=None): """ Returns a list of all transitions. INPUT: - ``from_state`` -- (default: ``None``) If ``from_state`` is given, then a list of transitions starting there is given. OUTPUT: A list of all transitions. EXAMPLES:: sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)]) sage: FSM.transitions() [Transition from '1' to '2': 1|-, Transition from '2' to '2': 0|-] """ return list(self.iter_transitions(from_state)) def iter_transitions(self, from_state=None): """ Returns an iterator of all transitions. INPUT: - ``from_state`` -- (default: ``None``) If ``from_state`` is given, then a list of transitions starting there is given. OUTPUT: An iterator of all transitions. EXAMPLES:: sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)]) sage: [(t.from_state.label(), t.to_state.label()) ....: for t in FSM.iter_transitions('1')] [('1', '2')] sage: [(t.from_state.label(), t.to_state.label()) ....: for t in FSM.iter_transitions('2')] [('2', '2')] sage: [(t.from_state.label(), t.to_state.label()) ....: for t in FSM.iter_transitions()] [('1', '2'), ('2', '2')] """ if from_state is None: return self._iter_transitions_all_() else: return iter(self.state(from_state).transitions) def _iter_transitions_all_(self): """ Returns an iterator over all transitions. INPUT: Nothing. OUTPUT: An iterator over all transitions. EXAMPLES:: sage: FSM = Automaton([('1', '2', 1), ('2', '2', 0)]) sage: [(t.from_state.label(), t.to_state.label()) ....: for t in FSM._iter_transitions_all_()] [('1', '2'), ('2', '2')] """ for state in self.iter_states(): for t in state.transitions: yield t def initial_states(self): """ Returns a list of all initial states. INPUT: Nothing. OUTPUT: A list of all initial states. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial=True) sage: B = FSMState('B') sage: F = FiniteStateMachine([(A, B, 1, 0)]) sage: F.initial_states() ['A'] """ return list(self.iter_initial_states()) def iter_initial_states(self): """ Returns an iterator of the initial states. INPUT: Nothing. OUTPUT: An iterator over all initial states. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial=True) sage: B = FSMState('B') sage: F = FiniteStateMachine([(A, B, 1, 0)]) sage: [s.label() for s in F.iter_initial_states()] ['A'] """ return itertools.ifilter(lambda s:s.is_initial, self.iter_states()) def final_states(self): """ Returns a list of all final states. INPUT: Nothing. OUTPUT: A list of all final states. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_final=True) sage: B = FSMState('B', is_initial=True) sage: C = FSMState('C', is_final=True) sage: F = FiniteStateMachine([(A, B), (A, C)]) sage: F.final_states() ['A', 'C'] """ return list(self.iter_final_states()) def iter_final_states(self): """ Returns an iterator of the final states. INPUT: Nothing. OUTPUT: An iterator over all initial states. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_final=True) sage: B = FSMState('B', is_initial=True) sage: C = FSMState('C', is_final=True) sage: F = FiniteStateMachine([(A, B), (A, C)]) sage: [s.label() for s in F.iter_final_states()] ['A', 'C'] """ return itertools.ifilter(lambda s:s.is_final, self.iter_states()) def state(self, state): """ Returns the state of the finite state machine. INPUT: - ``state`` -- If ``state`` is not an instance of :class:`FSMState`, then it is assumed that it is the label of a state. OUTPUT: Returns the state of the finite state machine corresponding to ``state``. If no state is found, then a ``LookupError`` is thrown. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: FSM = FiniteStateMachine([(A, 'B'), ('C', A)]) sage: FSM.state('A') == A True sage: FSM.state('xyz') Traceback (most recent call last): ... LookupError: No state with label xyz found. """ switch = is_FSMState(state) try: return self._states_dict_[what(state, switch)] except AttributeError: for s in self.iter_states(): if what(s, not switch) == state: return s except KeyError: pass raise LookupError("No state with label %s found." % (what(state, switch),)) def transition(self, transition): """ Returns the transition of the finite state machine. INPUT: - ``transition`` -- If ``transition`` is not an instance of :class:`FSMTransition`, then it is assumed that it is a tuple ``(from_state, to_state, word_in, word_out)``. OUTPUT: Returns the transition of the finite state machine corresponding to ``transition``. If no transition is found, then a ``LookupError`` is thrown. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t = FSMTransition('A', 'B', 0) sage: F = FiniteStateMachine([t]) sage: F.transition(('A', 'B', 0)) Transition from 'A' to 'B': 0|- sage: id(t) == id(F.transition(('A', 'B', 0))) True """ if not is_FSMTransition(transition): transition = FSMTransition(*transition) for s in self.iter_transitions(transition.from_state): if s == transition: return s raise LookupError("No transition found.") #************************************************************************* # properties (state and transitions) #************************************************************************* def has_state(self, state): """ Returns whether ``state`` is one of the states of the finite state machine. INPUT: - ``state`` can be a :class:`FSMState` or a label of a state. OUTPUT: True or False. EXAMPLES:: sage: FiniteStateMachine().has_state('A') False """ try: self.state(state) return True except LookupError: return False def has_transition(self, transition): """ Returns whether ``transition`` is one of the transitions of the finite state machine. INPUT: - ``transition`` has to be a :class:`FSMTransition`. OUTPUT: True or False. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t = FSMTransition('A', 'A', 0, 1) sage: FiniteStateMachine().has_transition(t) False sage: FiniteStateMachine().has_transition(('A', 'A', 0, 1)) Traceback (most recent call last): ... TypeError: Transition is not an instance of FSMTransition. """ if is_FSMTransition(transition): return transition in self.iter_transitions() raise TypeError("Transition is not an instance of FSMTransition.") def has_initial_state(self, state): """ Returns whether ``state`` is one of the initial states of the finite state machine. INPUT: - ``state`` can be a :class:`FSMState` or a label. OUTPUT: True or False. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'A')], initial_states=['A']) sage: F.has_initial_state('A') True """ try: return self.state(state).is_initial except LookupError: return False def has_initial_states(self): """ Returns whether the finite state machine has an initial state. INPUT: Nothing. OUTPUT: True or False. EXAMPLES:: sage: FiniteStateMachine().has_initial_states() False """ return len(self.initial_states()) > 0 def has_final_state(self, state): """ Returns whether ``state`` is one of the final states of the finite state machine. INPUT: - ``state`` can be a :class:`FSMState` or a label. OUTPUT: True or False. EXAMPLES:: sage: FiniteStateMachine(final_states=['A']).has_final_state('A') True """ try: return self.state(state).is_final except LookupError: return False def has_final_states(self): """ Returns whether the finite state machine has a final state. INPUT: Nothing. OUTPUT: True or False. EXAMPLES:: sage: FiniteStateMachine().has_final_states() False """ return len(self.final_states()) > 0 #************************************************************************* # properties #************************************************************************* def is_deterministic(self): """ Returns whether the finite finite state machine is deterministic. INPUT: Nothing. OUTPUT: ``True`` or ``False``. A finite state machine is considered to be deterministic if each transition has input label of length one and for each pair `(q,a)` where `q` is a state and `a` is an element of the input alphabet, there is at most one transition from `q` with input label `a`. TESTS:: sage: fsm = FiniteStateMachine() sage: fsm.add_transition(('A', 'B', 0, [])) Transition from 'A' to 'B': 0|- sage: fsm.is_deterministic() True sage: fsm.add_transition(('A', 'C', 0, [])) Transition from 'A' to 'C': 0|- sage: fsm.is_deterministic() False sage: fsm.add_transition(('A', 'B', [0,1], [])) Transition from 'A' to 'B': 0,1|- sage: fsm.is_deterministic() False """ for state in self.iter_states(): for transition in state.transitions: if len(transition.word_in) != 1: return False transition_classes_by_word_in = full_group_by( state.transitions, key=lambda t: t.word_in) for key,transition_class in transition_classes_by_word_in: if len(transition_class) > 1: return False return True def is_complete(self): """ Returns whether the finite state machine is complete. INPUT: Nothing. OUTPUT: ``True`` or ``False``. A finite state machine is considered to be complete if each transition has an input label of length one and for each pair `(q, a)` where `q` is a state and `a` is an element of the input alphabet, there is exactly one transition from `q` with input label `a`. EXAMPLES:: sage: fsm = FiniteStateMachine([(0, 0, 0, 0), ....: (0, 1, 1, 1), ....: (1, 1, 0, 0)], ....: determine_alphabets=False) sage: fsm.is_complete() Traceback (most recent call last): ... ValueError: No input alphabet is given. Try calling determine_alphabets(). sage: fsm.input_alphabet = [0, 1] sage: fsm.is_complete() False sage: fsm.add_transition((1, 1, 1, 1)) Transition from 1 to 1: 1|1 sage: fsm.is_complete() True sage: fsm.add_transition((0, 0, 1, 0)) Transition from 0 to 0: 1|0 sage: fsm.is_complete() False """ if self.input_alphabet is None: raise ValueError("No input alphabet is given. " "Try calling determine_alphabets().") for state in self.iter_states(): for transition in state.transitions: if len(transition.word_in) != 1: return False transition_classes_by_word_in = full_group_by( state.transitions, key=lambda t: t.word_in) for key, transition_class in transition_classes_by_word_in: if len(transition_class) > 1: return False # all input labels are lists, extract the only element outgoing_alphabet = [key[0] for key, transition_class in transition_classes_by_word_in] if not sorted(self.input_alphabet) == sorted(outgoing_alphabet): return False return True def is_connected(self): """ TESTS:: sage: FiniteStateMachine().is_connected() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError #************************************************************************* # let the finite state machine work #************************************************************************* def process(self, *args, **kwargs): """ Returns whether the finite state machine accepts the input, the state where the computation stops and which output is generated. INPUT: - ``input_tape`` -- The input tape can be a list with entries from the input alphabet. - ``initial_state`` -- (default: ``None``) The state in which to start. If this parameter is ``None`` and there is only one initial state in the machine, then this state is taken. OUTPUT: A triple, where - the first entry is ``True`` if the input string is accepted, - the second gives the reached state after processing the input tape (This is a state with label ``None`` if the input could not be processed, i.e., when at one point no transition to go could be found.), and - the third gives a list of the output labels used during processing (in the case the finite state machine runs as transducer). EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial = True, is_final = True) sage: binary_inverter = FiniteStateMachine({A:[(A, 0, 1), (A, 1, 0)]}) sage: binary_inverter.process([0, 1, 0, 0, 1, 1]) (True, 'A', [1, 0, 1, 1, 0, 0]) Alternatively, we can invoke this function by:: sage: binary_inverter([0, 1, 0, 0, 1, 1]) (True, 'A', [1, 0, 1, 1, 0, 0]) :: sage: NAF_ = FSMState('_', is_initial = True, is_final = True) sage: NAF1 = FSMState('1', is_final = True) sage: NAF = FiniteStateMachine( ....: {NAF_: [(NAF_, 0), (NAF1, 1)], NAF1: [(NAF_, 0)]}) sage: [NAF.process(w)[0] for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1], ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]] [True, True, False, True, False, False] Non-deterministic finite state machines cannot be handeled. :: sage: T = Transducer([(0, 1, 0, 0), (0, 2, 0, 0)], ....: initial_states=[0]) sage: T.process([0]) Traceback (most recent call last): ... NotImplementedError: Non-deterministic path encountered when processing input. sage: T = Transducer([(0, 1, [0, 0], 0), (0, 2, [0, 0, 1], 0), ....: (0, 1, 1, 2), (1, 0, [], 1), (1, 1, 1, 3)], ....: initial_states=[0], final_states=[0, 1]) sage: T.process([0]) (False, None, None) sage: T.process([0, 0]) Traceback (most recent call last): ... NotImplementedError: Non-deterministic path encountered when processing input. sage: T.process([1]) (True, 1, [2]) sage: T.process([1, 1]) Traceback (most recent call last): ... NotImplementedError: process cannot handle epsilon transition leaving state 1. """ it = self.iter_process(*args, **kwargs) for _ in it: pass return (it.accept_input, it.current_state, it.output_tape) def iter_process(self, input_tape=None, initial_state=None, **kwargs): """ See :meth:`.process` for more informations. EXAMPLES:: sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = inverter.iter_process(input_tape=[0, 1, 1]) sage: for _ in it: ....: pass sage: it.output_tape [1, 0, 0] """ return FSMProcessIterator(self, input_tape, initial_state, **kwargs) #************************************************************************* # change finite state machine (add/remove state/transitions) #************************************************************************* def add_state(self, state): """ Adds a state to the finite state machine and returns the new state. If the state already exists, that existing state is returned. INPUT: - ``state`` is either an instance of :class:`FSMState` or, otherwise, a label of a state. OUTPUT: The new or existing state. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: F = FiniteStateMachine() sage: A = FSMState('A', is_initial=True) sage: F.add_state(A) 'A' """ try: return self.state(state) except LookupError: pass # at this point we know that we have a new state if is_FSMState(state): s = state else: s = FSMState(state) s.transitions = list() self._states_.append(s) try: self._states_dict_[s.label()] = s except AttributeError: pass return s def add_states(self, states): """ Adds several states. See add_state for more information. INPUT: - ``states`` -- a list of states or iterator over states. OUTPUT: Nothing. EXAMPLES:: sage: F = FiniteStateMachine() sage: F.add_states(['A', 'B']) sage: F.states() ['A', 'B'] """ for state in states: self.add_state(state) def add_transition(self, *args, **kwargs): """ Adds a transition to the finite state machine and returns the new transition. If the transition already exists, the return value of ``self.on_duplicate_transition`` is returned. See the documentation of :class:`FiniteStateMachine`. INPUT: The following forms are all accepted: :: sage: from sage.combinat.finite_state_machine import FSMState, FSMTransition sage: A = FSMState('A') sage: B = FSMState('B') sage: FSM = FiniteStateMachine() sage: FSM.add_transition(FSMTransition(A, B, 0, 1)) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition(A, B, 0, 1) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition(A, B, word_in=0, word_out=1) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition('A', 'B', {'word_in': 0, 'word_out': 1}) Transition from 'A' to 'B': {'word_in': 0, 'word_out': 1}|- sage: FSM = FiniteStateMachine() sage: FSM.add_transition(from_state=A, to_state=B, ....: word_in=0, word_out=1) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition({'from_state': A, 'to_state': B, ....: 'word_in': 0, 'word_out': 1}) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition((A, B, 0, 1)) Transition from 'A' to 'B': 0|1 sage: FSM = FiniteStateMachine() sage: FSM.add_transition([A, B, 0, 1]) Transition from 'A' to 'B': 0|1 If the states ``A`` and ``B`` are not instances of :class:`FSMState`, then it is assumed that they are labels of states. OUTPUT: The new transition. """ if len(args) + len(kwargs) == 0: return if len(args) + len(kwargs) == 1: if len(args) == 1: d = args[0] if is_FSMTransition(d): return self._add_fsm_transition_(d) else: d = next(kwargs.itervalues()) if hasattr(d, 'iteritems'): args = [] kwargs = d elif hasattr(d, '__iter__'): args = d kwargs = {} else: raise TypeError("Cannot decide what to do with input.") data = dict(zip( ('from_state', 'to_state', 'word_in', 'word_out', 'hook'), args)) data.update(kwargs) data['from_state'] = self.add_state(data['from_state']) data['to_state'] = self.add_state(data['to_state']) return self._add_fsm_transition_(FSMTransition(**data)) def _add_fsm_transition_(self, t): """ Adds a transition. INPUT: - ``t`` -- an instance of :class:`FSMTransition`. OUTPUT: The new transition. TESTS:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: F = FiniteStateMachine() sage: F._add_fsm_transition_(FSMTransition('A', 'B')) Transition from 'A' to 'B': -|- """ try: existing_transition = self.transition(t) except LookupError: pass else: return self.on_duplicate_transition(existing_transition, t) from_state = self.add_state(t.from_state) self.add_state(t.to_state) from_state.transitions.append(t) return t def add_from_transition_function(self, function, initial_states=None, explore_existing_states=True): """ Constructs a finite state machine from a transition function. INPUT: - ``function`` may return a tuple (new_state, output_word) or a list of such tuples. - ``initial_states`` -- If no initial states are given, the already existing initial states of self are taken. - If ``explore_existing_states`` is True (default), then already existing states in self (e.g. already given final states) will also be processed if they are reachable from the initial states. OUTPUT: Nothing. EXAMPLES:: sage: F = FiniteStateMachine(initial_states=['A'], ....: input_alphabet=[0, 1]) sage: def f(state, input): ....: return [('A', input), ('B', 1-input)] sage: F.add_from_transition_function(f) sage: F.transitions() [Transition from 'A' to 'A': 0|0, Transition from 'A' to 'B': 0|1, Transition from 'A' to 'A': 1|1, Transition from 'A' to 'B': 1|0, Transition from 'B' to 'A': 0|0, Transition from 'B' to 'B': 0|1, Transition from 'B' to 'A': 1|1, Transition from 'B' to 'B': 1|0] Initial states can also be given as a parameter:: sage: F = FiniteStateMachine(input_alphabet=[0,1]) sage: def f(state, input): ....: return [('A', input), ('B', 1-input)] sage: F.add_from_transition_function(f,initial_states=['A']) sage: F.initial_states() ['A'] Already existing states in the finite state machine (the final states in the example below) are also explored:: sage: F = FiniteStateMachine(initial_states=[0], ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): ....: return(1-state, []) sage: F.add_from_transition_function(transition_function) sage: F.transitions() [Transition from 0 to 1: 0|-, Transition from 1 to 0: 0|-] If ``explore_existing_states=False``, however, this behavior is turned off, i.e., already existing states are not explored:: sage: F = FiniteStateMachine(initial_states=[0], ....: final_states=[1], ....: input_alphabet=[0]) sage: def transition_function(state, letter): ....: return(1-state, []) sage: F.add_from_transition_function(transition_function, ....: explore_existing_states=False) sage: F.transitions() [Transition from 0 to 1: 0|-] TEST:: sage: F = FiniteStateMachine(initial_states=['A']) sage: def f(state, input): ....: return [('A', input), ('B', 1-input)] sage: F.add_from_transition_function(f) Traceback (most recent call last): ... ValueError: No input alphabet is given. Try calling determine_alphabets(). :: sage: def transition(state, where): ....: return (vector([0, 0]), 1) sage: Transducer(transition, input_alphabet=[0], initial_states=[0]) Traceback (most recent call last): ... TypeError: mutable vectors are unhashable """ if self.input_alphabet is None: raise ValueError("No input alphabet is given. " "Try calling determine_alphabets().") if initial_states is None: not_done = self.initial_states() elif hasattr(initial_states, '__iter__'): not_done = [] for s in initial_states: state = self.add_state(s) state.is_initial = True not_done.append(state) else: raise TypeError('Initial states must be iterable ' \ '(e.g. a list of states).') if len(not_done) == 0: raise ValueError("No state is initial.") if explore_existing_states: ignore_done = self.states() for s in not_done: try: ignore_done.remove(s) except ValueError: pass else: ignore_done = [] while len(not_done) > 0: s = not_done.pop(0) for letter in self.input_alphabet: try: return_value = function(s.label(), letter) except LookupError: continue if not hasattr(return_value, "pop"): return_value = [return_value] try: for (st_label, word) in return_value: pass except TypeError: raise ValueError("The callback function for " "add_from_transition is expected " "to return a pair (new_state, " "output_label) or a list of such pairs. " "For the state %s and the input " "letter %s, it however returned %s, " "which is not acceptable." % (s.label(), letter, return_value)) for (st_label, word) in return_value: if not self.has_state(st_label): not_done.append(self.add_state(st_label)) elif len(ignore_done) > 0: u = self.state(st_label) if u in ignore_done: not_done.append(u) ignore_done.remove(u) self.add_transition(s, st_label, word_in=letter, word_out=word) def add_transitions_from_function(self, function, labels_as_input=True): """ Adds one or more transitions if ``function(state, state)`` says that there are some. INPUT: - ``function`` -- a transition function. Given two states ``from_state`` and ``to_state`` (or their labels if ``label_as_input`` is true), this function shall return a tuple ``(word_in, word_out)`` to add a transition from ``from_state`` to ``to_state`` with input and output labels ``word_in`` and ``word_out``, respectively. If no such addition is to be added, the transition function shall return ``None``. The transition function may also return a list of such tuples in order to add multiple transitions between the pair of states. - ``label_as_input`` -- (default: ``True``) OUTPUT: Nothing. EXAMPLES:: sage: F = FiniteStateMachine() sage: F.add_states(['A', 'B', 'C']) sage: def f(state1, state2): ....: if state1 == 'C': ....: return None ....: return (0, 1) sage: F.add_transitions_from_function(f) sage: len(F.transitions()) 6 Multiple transitions are also possible:: sage: F = FiniteStateMachine() sage: F.add_states([0, 1]) sage: def f(state1, state2): ....: if state1 != state2: ....: return [(0, 1), (1, 0)] ....: else: ....: return None sage: F.add_transitions_from_function(f) sage: F.transitions() [Transition from 0 to 1: 0|1, Transition from 0 to 1: 1|0, Transition from 1 to 0: 0|1, Transition from 1 to 0: 1|0] TESTS:: sage: F = FiniteStateMachine() sage: F.add_state(0) 0 sage: def f(state1, state2): ....: return 1 sage: F.add_transitions_from_function(f) Traceback (most recent call last): ... ValueError: The callback function for add_transitions_from_function is expected to return a pair (word_in, word_out) or a list of such pairs. For states 0 and 0 however, it returned 1, which is not acceptable. """ for s_from in self.iter_states(): for s_to in self.iter_states(): try: if labels_as_input: return_value = function(s_from.label(), s_to.label()) else: return_value = function(s_from, s_to) except LookupError: continue if return_value is None: continue if not hasattr(return_value, "pop"): transitions = [return_value] else: transitions = return_value for t in transitions: if not hasattr(t, '__getitem__'): raise ValueError("The callback function for " "add_transitions_from_function " "is expected to return a " "pair (word_in, word_out) or a " "list of such pairs. For " "states %s and %s however, it " "returned %s, which is not " "acceptable." % (s_from, s_to, return_value)) label_in = t[0] try: label_out = t[1] except LookupError: label_out = None self.add_transition(s_from, s_to, label_in, label_out) def delete_transition(self, t): """ Deletes a transition by removing it from the list of transitions of the state, where the transition starts. INPUT: - ``t`` -- a transition. OUTPUT: Nothing. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 0), ('B', 'A', 1)]) sage: F.delete_transition(('A', 'B', 0)) sage: F.transitions() [Transition from 'B' to 'A': 1|-] """ transition = self.transition(t) transition.from_state.transitions.remove(transition) def delete_state(self, s): """ Deletes a state and all transitions coming or going to this state. INPUT: - ``s`` -- a label of a state or an :class:`FSMState`. OUTPUT: Nothing. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMTransition sage: t1 = FSMTransition('A', 'B', 0) sage: t2 = FSMTransition('B', 'B', 1) sage: F = FiniteStateMachine([t1, t2]) sage: F.delete_state('A') sage: F.transitions() [Transition from 'B' to 'B': 1|-] TESTS:: sage: F._states_ ['B'] sage: F._states_dict_ # This shows that #16024 is fixed. {'B': 'B'} """ state = self.state(s) for transition in self.transitions(): if transition.to_state == state: self.delete_transition(transition) self._states_.remove(state) try: del self._states_dict_[state.label()] except AttributeError: pass def remove_epsilon_transitions(self): """ TESTS:: sage: FiniteStateMachine().remove_epsilon_transitions() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def accessible_components(self): """ Returns a new finite state machine with the accessible states of self and all transitions between those states. INPUT: Nothing. OUTPUT: A finite state machine with the accessible states of self and all transitions between those states. A state is accessible if there is a directed path from an initial state to the state. If self has no initial states then a copy of the finite state machine self is returned. EXAMPLES:: sage: F = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1)], ....: initial_states=[0]) sage: F.accessible_components() Automaton with 2 states :: sage: F = Automaton([(0, 0, 1), (0, 0, 1), (1, 1, 0), (1, 0, 1)], ....: initial_states=[0]) sage: F.accessible_components() Automaton with 1 states TESTS: Check whether input of length > 1 works:: sage: F = Automaton([(0, 1, [0, 1]), (0, 2, 0)], ....: initial_states=[0]) sage: F.accessible_components() Automaton with 3 states """ if len(self.initial_states()) == 0: return deepcopy(self) memo = {} new_initial_states=map(lambda x: deepcopy(x, memo), self.initial_states()) result = self.empty_copy() result.add_from_transition_function(accessible, initial_states=new_initial_states) for final_state in self.iter_final_states(): try: new_final_state=result.state(final_state.label) new_final_state.is_final=True except LookupError: pass return result # ************************************************************************* # creating new finite state machines # ************************************************************************* def disjoint_union(self, other): """ TESTS:: sage: F = FiniteStateMachine([('A', 'A')]) sage: FiniteStateMachine().disjoint_union(F) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def concatenation(self, other): """ TESTS:: sage: F = FiniteStateMachine([('A', 'A')]) sage: FiniteStateMachine().concatenation(F) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def Kleene_closure(self): """ TESTS:: sage: FiniteStateMachine().Kleene_closure() Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def intersection(self, other): """ TESTS:: sage: FiniteStateMachine().intersection(FiniteStateMachine()) Traceback (most recent call last): ... NotImplementedError """ raise NotImplementedError def product_FiniteStateMachine(self, other, function, new_input_alphabet=None, only_accessible_components=True, final_function=None, new_class=None): r""" Returns a new finite state machine whose states are `d`-tuples of states of the original finite state machines. INPUT: - ``other`` -- a finite state machine (for `d=2`) or a list (or iterable) of `d-1` finite state machines. - ``function`` has to accept `d` transitions from `A_j` to `B_j` for `j\in\{1, \ldots, d\}` and returns a pair ``(word_in, word_out)`` which is the label of the transition `A=(A_1, \ldots, A_d)` to `B=(B_1, \ldots, B_d)`. If there is no transition from `A` to `B`, then ``function`` should raise a ``LookupError``. - ``new_input_alphabet`` (optional) -- the new input alphabet as a list. - ``only_accessible_components`` -- If ``True`` (default), then the result is piped through :meth:`.accessible_components`. If no ``new_input_alphabet`` is given, it is determined by :meth:`.determine_alphabets`. - ``final_function`` -- A function mapping `d` final states of the original finite state machines to the final output of the corresponding state in the new finite state machine. By default, the final output is the empty word if both final outputs of the constituent states are empty; otherwise, a ``ValueError`` is raised. - ``new_class`` -- Class of the new finite state machine. By default (``None``), the class of ``self`` is used. OUTPUT: A finite state machine whose states are `d`-tuples of states of the original finite state machines. A state is initial or final if all constituent states are initial or final, respectively. The labels of the transitions are defined by ``function``. The final output of a final state is determined by calling ``final_function`` on the constituent states. The color of a new state is the tuple of colors of the constituent states of ``self`` and ``other``. EXAMPLES:: sage: F = Automaton([('A', 'B', 1), ('A', 'A', 0), ('B', 'A', 2)], ....: initial_states=['A'], final_states=['B'], ....: determine_alphabets=True) sage: G = Automaton([(1, 1, 1)], initial_states=[1], final_states=[1]) sage: def addition(transition1, transition2): ....: return (transition1.word_in[0] + transition2.word_in[0], ....: None) sage: H = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False) sage: H.transitions() [Transition from ('A', 1) to ('B', 1): 2|-, Transition from ('A', 1) to ('A', 1): 1|-, Transition from ('B', 1) to ('A', 1): 3|-] sage: H1 = F.product_FiniteStateMachine(G, addition, [0, 1, 2, 3], only_accessible_components=False) sage: H1.states()[0].label()[0] is F.states()[0] True sage: H1.states()[0].label()[1] is G.states()[0] True :: sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)], ....: initial_states=[0] ) sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)], ....: initial_states=[0] ) sage: H = F.product_FiniteStateMachine( ....: G, lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None)) sage: H.states() [(0, 0), (1, 0)] :: sage: F = Automaton([(0,1,1/4), (0,0,3/4), (1,1,3/4), (1,0,1/4)], ....: initial_states=[0] ) sage: G = Automaton([(0,0,1), (1,1,3/4), (1,0,1/4)], ....: initial_states=[0] ) sage: H = F.product_FiniteStateMachine(G, ....: lambda t1,t2: (t1.word_in[0]*t2.word_in[0], None), ....: only_accessible_components=False) sage: H.states() [(0, 0), (1, 0), (0, 1), (1, 1)] Also final output words are considered according to the function ``final_function``:: sage: F = Transducer([(0, 1, 0, 1), (1, 1, 1, 1), (1, 1, 0, 1)], ....: final_states=[1]) sage: F.state(1).final_word_out = 1 sage: G = Transducer([(0, 0, 0, 1), (0, 0, 1, 0)], final_states=[0]) sage: G.state(0).final_word_out = 1 sage: def minus(t1, t2): ....: return (t1.word_in[0] - t2.word_in[0], ....: t1.word_out[0] - t2.word_out[0]) sage: H = F.product_FiniteStateMachine(G, minus) Traceback (most recent call last): ... ValueError: A final function must be given. sage: def plus(s1, s2): ....: return s1.final_word_out[0] + s2.final_word_out[0] sage: H = F.product_FiniteStateMachine(G, minus, ....: final_function=plus) sage: H.final_states() [(1, 0)] sage: H.final_states()[0].final_word_out [2] Products of more than two finite state machines are also possible:: sage: def plus(s1, s2, s3): ....: if s1.word_in == s2.word_in == s3.word_in: ....: return (s1.word_in, ....: sum(s.word_out[0] for s in (s1, s2, s3))) ....: else: ....: raise LookupError sage: T0 = transducers.CountSubblockOccurrences([0, 0], [0, 1, 2]) sage: T1 = transducers.CountSubblockOccurrences([1, 1], [0, 1, 2]) sage: T2 = transducers.CountSubblockOccurrences([2, 2], [0, 1, 2]) sage: T = T0.product_FiniteStateMachine([T1, T2], plus) sage: T.transitions() [Transition from ((), (), ()) to ((0,), (), ()): 0|0, Transition from ((), (), ()) to ((), (1,), ()): 1|0, Transition from ((), (), ()) to ((), (), (2,)): 2|0, Transition from ((0,), (), ()) to ((0,), (), ()): 0|1, Transition from ((0,), (), ()) to ((), (1,), ()): 1|0, Transition from ((0,), (), ()) to ((), (), (2,)): 2|0, Transition from ((), (1,), ()) to ((0,), (), ()): 0|0, Transition from ((), (1,), ()) to ((), (1,), ()): 1|1, Transition from ((), (1,), ()) to ((), (), (2,)): 2|0, Transition from ((), (), (2,)) to ((0,), (), ()): 0|0, Transition from ((), (), (2,)) to ((), (1,), ()): 1|0, Transition from ((), (), (2,)) to ((), (), (2,)): 2|1] sage: T([0, 0, 1, 1, 2, 2, 0, 1, 2, 2]) [0, 1, 0, 1, 0, 1, 0, 0, 0, 1] ``other`` can also be an iterable:: sage: T == T0.product_FiniteStateMachine(iter([T1, T2]), plus) True TESTS: Check that colors are correctly dealt with. In particular, the new colors have to be hashable such that :meth:`Automaton.determinisation` does not fail:: sage: A = Automaton([[0, 0, 0]], initial_states=[0]) sage: B = A.product_FiniteStateMachine(A, ....: lambda t1, t2: (0, None)) sage: B.states()[0].color (None, None) sage: B.determinisation() Automaton with 1 states Check handling of the parameter ``other``:: sage: A.product_FiniteStateMachine(None, plus) Traceback (most recent call last): ... ValueError: other must be a finite state machine or a list of finite state machines. sage: A.product_FiniteStateMachine([None], plus) Traceback (most recent call last): ... ValueError: other must be a finite state machine or a list of finite state machines. Test whether ``new_class`` works:: sage: T = Transducer() sage: type(T.product_FiniteStateMachine(T, None)) <class 'sage.combinat.finite_state_machine.Transducer'> sage: type(T.product_FiniteStateMachine(T, None, ....: new_class=Automaton)) <class 'sage.combinat.finite_state_machine.Automaton'> """ if final_function is None: final_function = default_final_function result = self.empty_copy(new_class=new_class) if new_input_alphabet is not None: result.input_alphabet = new_input_alphabet else: result.input_alphabet = None if hasattr(other, '__iter__'): machines = [self] machines.extend(other) if not all(is_FiniteStateMachine(m) for m in machines): raise ValueError("other must be a finite state machine " "or a list of finite state machines.") elif is_FiniteStateMachine(other): machines = [self, other] else: raise ValueError("other must be a finite state machine or " "a list of finite state machines.") for transitions in itertools.product( *(m.iter_transitions() for m in machines)): try: word = function(*transitions) except LookupError: continue result.add_transition(tuple(t.from_state for t in transitions), tuple(t.to_state for t in transitions), word[0], word[1]) for state in result.states(): if all(s.is_initial for s in state.label()): state.is_initial = True if all(s.is_final for s in state.label()): state.is_final = True state.final_word_out = final_function(*state.label()) state.color = tuple(s.color for s in state.label()) if only_accessible_components: if result.input_alphabet is None: result.determine_alphabets() return result.accessible_components() else: return result def composition(self, other, algorithm=None, only_accessible_components=True): """ Returns a new transducer which is the composition of ``self`` and ``other``. INPUT: - ``other`` -- a transducer - ``algorithm`` -- can be one of the following - ``direct`` -- The composition is calculated directly. There can be arbitrarily many initial and final states, but the input and output labels must have length 1. WARNING: The output of other is fed into self. - ``explorative`` -- An explorative algorithm is used. At least the following restrictions apply, but are not checked: - both self and other have exactly one initial state - all input labels of transitions have length exactly 1 The input alphabet of self has to be specified. This is a very limited implementation of composition. WARNING: The output of ``other`` is fed into ``self``. If algorithm is ``None``, then the algorithm is chosen automatically (at the moment always ``direct``). OUTPUT: A new transducer. The labels of the new finite state machine are pairs of states of the original finite state machines. The color of a new state is the tuple of colors of the constituent states. EXAMPLES:: sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)], ....: initial_states=['A', 'B'], final_states=['B'], ....: determine_alphabets=True) sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1), ....: (2, 2, 1, 1), (2, 2, 0, 0)], ....: initial_states=[1], final_states=[2], ....: determine_alphabets=True) sage: Hd = F.composition(G, algorithm='direct') sage: Hd.initial_states() [(1, 'B'), (1, 'A')] sage: Hd.transitions() [Transition from (1, 'B') to (1, 'A'): 1|1, Transition from (1, 'A') to (2, 'B'): 0|0, Transition from (2, 'B') to (2, 'A'): 0|1, Transition from (2, 'A') to (2, 'B'): 1|0] :: sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1), ....: ('B', 'B', 0, 0)], ....: initial_states=['A'], final_states=['B']) sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0), ....: (2, 2, 0, 1), (2, 1, 1, 1)], ....: initial_states=[1], final_states=[1]) sage: He = G.composition(F, algorithm='explorative') sage: He.transitions() [Transition from ('A', 1) to ('B', 2): 1|0,1, Transition from ('B', 2) to ('B', 2): 0|1, Transition from ('B', 2) to ('B', 1): 1|1, Transition from ('B', 1) to ('B', 1): 0|0, Transition from ('B', 1) to ('B', 2): 1|0] Also final output words are considered if ``algorithm='direct'`` or ``None``:: sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)], ....: initial_states=['A', 'B'], ....: final_states=['A', 'B']) sage: F.state('A').final_word_out = 0 sage: F.state('B').final_word_out = 1 sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1), ....: (2, 2, 1, 1), (2, 2, 0, 0)], ....: initial_states=[1], final_states=[2]) sage: G.state(2).final_word_out = 0 sage: Hd = F.composition(G, algorithm='direct') sage: Hd.final_states() [(2, 'B')] Note that ``(2, 'A')`` is not final, as the final output `0` of state `2` of `G` cannot be processed in state ``'A'`` of `F`. :: sage: [s.final_word_out for s in Hd.final_states()] [[1, 0]] Be aware that after composition, different transitions may share the same output label (same python object):: sage: F = Transducer([ ('A','B',0,0), ('B','A',0,0)], ....: initial_states=['A'], ....: final_states=['A']) sage: F.transitions()[0].word_out is F.transitions()[1].word_out False sage: G = Transducer([('C','C',0,1)],) ....: initial_states=['C'], ....: final_states=['C']) sage: H = G.composition(F) sage: H.transitions()[0].word_out is H.transitions()[1].word_out True In the explorative algorithm, transducers with non-empty final output words are currently not implemented:: sage: A = transducers.GrayCode() sage: B = transducers.abs([0, 1]) sage: A.composition(B, algorithm='explorative') Traceback (most recent call last): ... NotImplementedError: Explorative composition is not implemented for transducers with non-empty final output words. Try the direct algorithm instead. Similarly, the explorative algorithm cannot handle non-deterministic finite state machines:: sage: A = Transducer([(0, 0, 0, 0), (0, 1, 0, 0)]) sage: B = transducers.Identity([0]) sage: A.composition(B, algorithm='explorative') Traceback (most recent call last): ... NotImplementedError: Explorative composition is currently not implemented for non-deterministic transducers. sage: B.composition(A, algorithm='explorative') Traceback (most recent call last): ... NotImplementedError: Explorative composition is currently not implemented for non-deterministic transducers. TESTS: Due to the limitations of the two algorithms the following (examples from above, but different algorithm used) does not give a full answer or does not work. In the following, ``algorithm='explorative'`` is inadequate, as ``F`` has more than one initial state:: sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)], ....: initial_states=['A', 'B'], final_states=['B'], ....: determine_alphabets=True) sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1), ....: (2, 2, 1, 1), (2, 2, 0, 0)], ....: initial_states=[1], final_states=[2], ....: determine_alphabets=True) sage: He = F.composition(G, algorithm='explorative') sage: He.initial_states() [(1, 'A')] sage: He.transitions() [Transition from (1, 'A') to (2, 'B'): 0|0, Transition from (2, 'B') to (2, 'A'): 0|1, Transition from (2, 'A') to (2, 'B'): 1|0] In the following example, ``algorithm='direct'`` is inappropriate as there are edges with output labels of length greater than 1:: sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1), ....: ('B', 'B', 0, 0)], ....: initial_states=['A'], final_states=['B']) sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0), ....: (2, 2, 0, 1), (2, 1, 1, 1)], ....: initial_states=[1], final_states=[1]) sage: Hd = G.composition(F, algorithm='direct') In the following examples, we compose transducers and automata and check whether the types are correct. :: sage: from sage.combinat.finite_state_machine import ( ....: is_Automaton, is_Transducer) sage: T = Transducer([(0, 0, 0, 0)], initial_states=[0]) sage: A = Automaton([(0, 0, 0)], initial_states=[0]) sage: is_Transducer(T.composition(T, algorithm='direct')) True sage: is_Transducer(T.composition(T, algorithm='explorative')) True sage: T.composition(A, algorithm='direct') Traceback (most recent call last): ... TypeError: Composition with automaton is not possible. sage: T.composition(A, algorithm='explorative') Traceback (most recent call last): ... TypeError: Composition with automaton is not possible. sage: A.composition(A, algorithm='direct') Traceback (most recent call last): ... TypeError: Composition with automaton is not possible. sage: A.composition(A, algorithm='explorative') Traceback (most recent call last): ... TypeError: Composition with automaton is not possible. sage: is_Automaton(A.composition(T, algorithm='direct')) True sage: is_Automaton(A.composition(T, algorithm='explorative')) True """ if not other._allow_composition_: raise TypeError("Composition with automaton is not " "possible.") if algorithm is None: algorithm = 'direct' if algorithm == 'direct': return self._composition_direct_(other, only_accessible_components) elif algorithm == 'explorative': return self._composition_explorative_(other) else: raise ValueError("Unknown algorithm %s." % (algorithm,)) def _composition_direct_(self, other, only_accessible_components=True): """ See :meth:`.composition` for details. TESTS:: sage: F = Transducer([('A', 'B', 1, 0), ('B', 'A', 0, 1)], ....: initial_states=['A', 'B'], final_states=['B'], ....: determine_alphabets=True) sage: G = Transducer([(1, 1, 1, 0), (1, 2, 0, 1), ....: (2, 2, 1, 1), (2, 2, 0, 0)], ....: initial_states=[1], final_states=[2], ....: determine_alphabets=True) sage: Hd = F._composition_direct_(G) sage: Hd.initial_states() [(1, 'B'), (1, 'A')] sage: Hd.transitions() [Transition from (1, 'B') to (1, 'A'): 1|1, Transition from (1, 'A') to (2, 'B'): 0|0, Transition from (2, 'B') to (2, 'A'): 0|1, Transition from (2, 'A') to (2, 'B'): 1|0] """ result = other.product_FiniteStateMachine( self, function, only_accessible_components=only_accessible_components, final_function=lambda s1, s2: [], new_class=self.__class__) for state_result in result.iter_states(): state = state_result.label()[0] if state.is_final: accept, state_to, output = self.process( state.final_word_out, initial_state=self.state(state_result.label()[1])) if not accept: state_result.is_final = False else: state_result.is_final = True state_result.final_word_out = output return result def _composition_explorative_(self, other): """ See :meth:`.composition` for details. TESTS:: sage: F = Transducer([('A', 'B', 1, [1, 0]), ('B', 'B', 1, 1), ....: ('B', 'B', 0, 0)], ....: initial_states=['A'], final_states=['B']) sage: G = Transducer([(1, 1, 0, 0), (1, 2, 1, 0), ....: (2, 2, 0, 1), (2, 1, 1, 1)], ....: initial_states=[1], final_states=[1]) sage: He = G._composition_explorative_(F) sage: He.transitions() [Transition from ('A', 1) to ('B', 2): 1|0,1, Transition from ('B', 2) to ('B', 2): 0|1, Transition from ('B', 2) to ('B', 1): 1|1, Transition from ('B', 1) to ('B', 1): 0|0, Transition from ('B', 1) to ('B', 2): 1|0] Check that colors are correctly dealt with. In particular, the new colors have to be hashable such that :meth:`Automaton.determinisation` does not fail:: sage: T = Transducer([[0, 0, 0, 0]], initial_states=[0]) sage: A = T.input_projection() sage: B = A.composition(T, algorithm='explorative') sage: B.states()[0].color (None, None) sage: B.determinisation() Automaton with 1 states .. TODO:: The explorative algorithm should be re-implemented using the process iterators of both finite state machines. """ if any(s.final_word_out for s in self.iter_final_states()) or \ any(s.final_word_out for s in other.iter_final_states()): raise NotImplementedError("Explorative composition is not " "implemented for transducers with " "non-empty final output words. Try " "the direct algorithm instead.") if not self.is_deterministic() or not other.is_deterministic(): raise NotImplementedError("Explorative composition is " "currently not implemented for " "non-deterministic transducers.") F = other.empty_copy(new_class=self.__class__) new_initial_states = [(other.initial_states()[0], self.initial_states()[0])] F.add_from_transition_function(composition_transition, initial_states=new_initial_states) for state in F.states(): if all(map(lambda s: s.is_final, state.label())): state.is_final = True state.color = tuple(map(lambda s: s.color, state.label())) return F def input_projection(self): """ Returns an automaton where the output of each transition of self is deleted. INPUT: Nothing OUTPUT: An automaton. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1), ....: ('B', 'B', 1, 0)]) sage: G = F.input_projection() sage: G.transitions() [Transition from 'A' to 'B': 0|-, Transition from 'A' to 'A': 1|-, Transition from 'B' to 'B': 1|-] """ return self.projection(what='input') def output_projection(self): """ Returns a automaton where the input of each transition of self is deleted and the new input is the original output. INPUT: Nothing OUTPUT: An automaton. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1), ....: ('B', 'B', 1, 0)]) sage: G = F.output_projection() sage: G.transitions() [Transition from 'A' to 'B': 1|-, Transition from 'A' to 'A': 1|-, Transition from 'B' to 'B': 0|-] Final output words are also considered correctly:: sage: H = Transducer([('A', 'B', 0, 1), ('A', 'A', 1, 1), ....: ('B', 'B', 1, 0), ('A', ('final', 0), 0, 0)], ....: final_states=['A', 'B']) sage: H.state('B').final_word_out = 2 sage: J = H.output_projection() sage: J.states() ['A', 'B', ('final', 0), ('final', 1)] sage: J.transitions() [Transition from 'A' to 'B': 1|-, Transition from 'A' to 'A': 1|-, Transition from 'A' to ('final', 0): 0|-, Transition from 'B' to 'B': 0|-, Transition from 'B' to ('final', 1): 2|-] sage: J.final_states() ['A', ('final', 1)] """ return self.projection(what='output') def projection(self, what='input'): """ Returns an Automaton which transition labels are the projection of the transition labels of the input. INPUT: - ``what`` -- (default: ``input``) either ``input`` or ``output``. OUTPUT: An automaton. EXAMPLES:: sage: F = FiniteStateMachine([('A', 'B', 0, 1), ('A', 'A', 1, 1), ....: ('B', 'B', 1, 0)]) sage: G = F.projection(what='output') sage: G.transitions() [Transition from 'A' to 'B': 1|-, Transition from 'A' to 'A': 1|-, Transition from 'B' to 'B': 0|-] """ new = Automaton() # TODO: use empty_copy() in order to # preserve on_duplicate_transition and future extensions. # for this, empty_copy would need a new optional argument # use_class=None ? if what == 'input': new.input_alphabet = copy(self.input_alphabet) elif what == 'output': new.input_alphabet = copy(self.output_alphabet) else: raise NotImplementedError state_mapping = {} for state in self.iter_states(): state_mapping[state] = new.add_state(deepcopy(state)) for transition in self.iter_transitions(): if what == 'input': new_word_in = transition.word_in elif what == 'output': new_word_in = transition.word_out else: raise NotImplementedError new.add_transition((state_mapping[transition.from_state], state_mapping[transition.to_state], new_word_in, None)) if what == 'output': states = [s for s in self.iter_final_states() if s.final_word_out] if not states: return new number = 0 while new.has_state(('final', number)): number += 1 final = new.add_state(('final', number)) final.is_final = True for state in states: output = state.final_word_out new.state(state_mapping[state]).final_word_out = [] new.state(state_mapping[state]).is_final = False new.add_transition((state_mapping[state], final, output, None)) return new def transposition(self): """ Returns a new finite state machine, where all transitions of the input finite state machine are reversed. INPUT: Nothing. OUTPUT: A new finite state machine. EXAMPLES:: sage: aut = Automaton([('A', 'A', 0), ('A', 'A', 1), ('A', 'B', 0)], ....: initial_states=['A'], final_states=['B']) sage: aut.transposition().transitions('B') [Transition from 'B' to 'A': 0|-] :: sage: aut = Automaton([('1', '1', 1), ('1', '2', 0), ('2', '2', 0)], ....: initial_states=['1'], final_states=['1', '2']) sage: aut.transposition().initial_states() ['1', '2'] TESTS: If a final state of ``self`` has a non-empty final output word, transposition is not implemented:: sage: T = Transducer([('1', '1', 1, 0), ('1', '2', 0, 1), ....: ('2', '2', 0, 2)], ....: initial_states=['1'], ....: final_states=['1', '2']) sage: T.state('1').final_word_out = [2, 5] sage: T.transposition() Traceback (most recent call last): ... NotImplementedError: Transposition for transducers with final output words is not implemented. """ transposition = self.empty_copy() for state in self.iter_states(): transposition.add_state(deepcopy(state)) for transition in self.iter_transitions(): transposition.add_transition( transition.to_state.label(), transition.from_state.label(), transition.word_in, transition.word_out) for initial in self.iter_initial_states(): state = transposition.state(initial.label()) if not initial.is_final: state.is_final = True state.is_initial = False for final in self.iter_final_states(): state = transposition.state(final.label()) if final.final_word_out: raise NotImplementedError("Transposition for transducers " "with final output words is not " "implemented.") if not final.is_initial: state.is_final = False state.is_initial = True return transposition def split_transitions(self): """ Returns a new transducer, where all transitions in self with input labels consisting of more than one letter are replaced by a path of the corresponding length. INPUT: Nothing. OUTPUT: A new transducer. EXAMPLES:: sage: A = Transducer([('A', 'B', [1, 2, 3], 0)], ....: initial_states=['A'], final_states=['B']) sage: A.split_transitions().states() [('A', ()), ('B', ()), ('A', (1,)), ('A', (1, 2))] """ new = self.empty_copy() for state in self.states(): new.add_state(FSMState((state, ()), is_initial=state.is_initial, is_final=state.is_final)) for transition in self.transitions(): for j in range(len(transition.word_in)-1): new.add_transition(( (transition.from_state, tuple(transition.word_in[:j])), (transition.from_state, tuple(transition.word_in[:j+1])), transition.word_in[j], [])) new.add_transition(( (transition.from_state, tuple(transition.word_in[:-1])), (transition.to_state, ()), transition.word_in[-1:], transition.word_out)) return new def final_components(self): """ Returns the final components of a finite state machine as finite state machines. INPUT: Nothing. OUTPUT: A list of finite state machines, each representing a final component of ``self``. A final component of a transducer ``T`` is a strongly connected component ``C`` such that there are no transitions of ``T`` leaving ``C``. The final components are the only parts of a transducer which influence the main terms of the asympotic behaviour of the sum of output labels of a transducer, see [HKP2014]_ and [HKW2014]_. EXAMPLES:: sage: T = Transducer([['A', 'B', 0, 0], ['B', 'C', 0, 1], ....: ['C', 'B', 0, 1], ['A', 'D', 1, 0], ....: ['D', 'D', 0, 0], ['D', 'B', 1, 0], ....: ['A', 'E', 2, 0], ['E', 'E', 0, 0]]) sage: FC = T.final_components() sage: sorted(FC[0].transitions()) [Transition from 'B' to 'C': 0|1, Transition from 'C' to 'B': 0|1] sage: FC[1].transitions() [Transition from 'E' to 'E': 0|0] Another example (cycle of length 2):: sage: T = Automaton([[0, 1, 0], [1, 0, 0]]) sage: len(T.final_components()) == 1 True sage: T.final_components()[0].transitions() [Transition from 0 to 1: 0|-, Transition from 1 to 0: 0|-] REFERENCES: .. [HKP2014] Clemens Heuberger, Sara Kropf, and Helmut Prodinger, *Asymptotic analysis of the sum of the output of transducer*, in preparation. """ DG = self.digraph() condensation = DG.strongly_connected_components_digraph() return [self.induced_sub_finite_state_machine(map(self.state, component)) for component in condensation.vertices() if condensation.out_degree(component) == 0] # ************************************************************************* # simplifications # ************************************************************************* def prepone_output(self): """ For all paths, shift the output of the path from one transition to the earliest possible preceeding transition of the path. INPUT: Nothing. OUTPUT: Nothing. Apply the following to each state `s` (except initial states) of the finite state machine as often as possible: If the letter `a` is a prefix of the output label of all transitions from `s` (including the final output of `s`), then remove it from all these labels and append it to all output labels of all transitions leading to `s`. We assume that the states have no output labels, but final outputs are allowed. EXAMPLES:: sage: A = Transducer([('A', 'B', 1, 1), ....: ('B', 'B', 0, 0), ....: ('B', 'C', 1, 0)], ....: initial_states=['A'], ....: final_states=['C']) sage: A.prepone_output() sage: A.transitions() [Transition from 'A' to 'B': 1|1,0, Transition from 'B' to 'B': 0|0, Transition from 'B' to 'C': 1|-] :: sage: B = Transducer([('A', 'B', 0, 1), ....: ('B', 'C', 1, [1, 1]), ....: ('B', 'C', 0, 1)], ....: initial_states=['A'], ....: final_states=['C']) sage: B.prepone_output() sage: B.transitions() [Transition from 'A' to 'B': 0|1,1, Transition from 'B' to 'C': 1|1, Transition from 'B' to 'C': 0|-] If initial states are not labeled as such, unexpected results may be obtained:: sage: C = Transducer([(0,1,0,0)]) sage: C.prepone_output() verbose 0 (...: finite_state_machine.py, prepone_output) All transitions leaving state 0 have an output label with prefix 0. However, there is no inbound transition and it is not an initial state. This routine (possibly called by simplification) therefore erased this prefix from all outbound transitions. sage: C.transitions() [Transition from 0 to 1: 0|-] Also the final output of final states can be changed:: sage: T = Transducer([('A', 'B', 0, 1), ....: ('B', 'C', 1, [1, 1]), ....: ('B', 'C', 0, 1)], ....: initial_states=['A'], ....: final_states=['B']) sage: T.state('B').final_word_out = [1] sage: T.prepone_output() sage: T.transitions() [Transition from 'A' to 'B': 0|1,1, Transition from 'B' to 'C': 1|1, Transition from 'B' to 'C': 0|-] sage: T.state('B').final_word_out [] :: sage: S = Transducer([('A', 'B', 0, 1), ....: ('B', 'C', 1, [1, 1]), ....: ('B', 'C', 0, 1)], ....: initial_states=['A'], ....: final_states=['B']) sage: S.state('B').final_word_out = [0] sage: S.prepone_output() sage: S.transitions() [Transition from 'A' to 'B': 0|1, Transition from 'B' to 'C': 1|1,1, Transition from 'B' to 'C': 0|1] sage: S.state('B').final_word_out [0] Output labels do not have to be hashable:: sage: C = Transducer([(0, 1, 0, []), ....: (1, 0, 0, [vector([0, 0]), 0]), ....: (1, 1, 1, [vector([0, 0]), 1]), ....: (0, 0, 1, 0)], ....: determine_alphabets=False, ....: initial_states=[0]) sage: C.prepone_output() sage: sorted(C.transitions()) [Transition from 0 to 1: 0|(0, 0), Transition from 0 to 0: 1|0, Transition from 1 to 0: 0|0, Transition from 1 to 1: 1|1,(0, 0)] """ changed = 1 iteration = 0 while changed > 0: changed = 0 iteration += 1 for state in self.iter_states(): if state.is_initial: continue if state.word_out: raise NotImplementedError( "prepone_output assumes that all states have " "empty output word, but state %s has output " "word %s" % (state, state.word_out)) common_output = find_common_output(state) if common_output: changed += 1 if state.is_final: assert state.final_word_out[0] == common_output[0] state.final_word_out = state.final_word_out[1:] for transition in self.transitions(state): assert transition.word_out[0] == common_output[0] transition.word_out = transition.word_out[1:] found_inbound_transition = False for transition in self.iter_transitions(): if transition.to_state == state: transition.word_out = transition.word_out \ + [common_output[0]] found_inbound_transition = True if not found_inbound_transition: verbose( "All transitions leaving state %s have an " "output label with prefix %s. However, " "there is no inbound transition and it is " "not an initial state. This routine " "(possibly called by simplification) " "therefore erased this prefix from all " "outbound transitions." % (state, common_output[0]), level=0) def equivalence_classes(self): r""" Returns a list of equivalence classes of states. INPUT: Nothing. OUTPUT: A list of equivalence classes of states. Two states `a` and `b` are equivalent if and only if there is a bijection `\varphi` between paths starting at `a` and paths starting at `b` with the following properties: Let `p_a` be a path from `a` to `a'` and `p_b` a path from `b` to `b'` such that `\varphi(p_a)=p_b`, then - `p_a.\mathit{word}_\mathit{in}=p_b.\mathit{word}_\mathit{in}`, - `p_a.\mathit{word}_\mathit{out}=p_b.\mathit{word}_\mathit{out}`, - `a'` and `b'` have the same output label, and - `a'` and `b'` are both final or both non-final and have the same final output word. The function :meth:`.equivalence_classes` returns a list of the equivalence classes to this equivalence relation. This is one step of Moore's minimization algorithm. .. SEEALSO:: :meth:`.minimization` EXAMPLES:: sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0), ....: ("B", "C", 0, 0), ("B", "C", 1, 1), ....: ("C", "D", 0, 1), ("C", "D", 1, 0), ....: ("D", "A", 0, 0), ("D", "A", 1, 1)]) sage: sorted(fsm.equivalence_classes()) [['A', 'C'], ['B', 'D']] sage: fsm.state("A").is_final = True sage: sorted(fsm.equivalence_classes()) [['A'], ['B'], ['C'], ['D']] sage: fsm.state("C").is_final = True sage: sorted(fsm.equivalence_classes()) [['A', 'C'], ['B', 'D']] sage: fsm.state("A").final_word_out = 1 sage: sorted(fsm.equivalence_classes()) [['A'], ['B'], ['C'], ['D']] sage: fsm.state("C").final_word_out = 1 sage: sorted(fsm.equivalence_classes()) [['A', 'C'], ['B', 'D']] """ # Two states `a` and `b` are j-equivalent if and only if there # is a bijection `\varphi` between paths of length <= j # starting at `a` and paths starting at `b` with the following # properties: Let `p_a` be a path from `a` to `a'` and `p_b` a # path from `b` to `b'` such that `\varphi(p_a)=p_b`, then # # - `p_a.\mathit{word}_{in}=p_b.\mathit{word}_{in}`, # - `p_a.\mathit{word}_{out}=p_b.\mathit{word}_{out}`, # - `a'` and `b'` have the same output label, and # - `a'` and `b'` are both final or both non-final. # If for some j the relations j-1 equivalent and j-equivalent # coincide, then they are equal to the equivalence relation # described in the docstring. # classes_current holds the equivalence classes of # j-equivalence, classes_previous holds the equivalence # classes of j-1 equivalence. # initialize with 0-equivalence classes_previous = [] key_0 = lambda state: (state.is_final, state.color, state.word_out, state.final_word_out) states_grouped = full_group_by(self.states(), key=key_0) classes_current = [equivalence_class for (key,equivalence_class) in states_grouped] while len(classes_current) != len(classes_previous): class_of = {} classes_previous = classes_current classes_current = [] for k in range(len(classes_previous)): for state in classes_previous[k]: class_of[state] = k key_current = lambda state: sorted( [(transition.word_in, transition.word_out, class_of[transition.to_state]) for transition in state.transitions]) for class_previous in classes_previous: states_grouped = full_group_by(class_previous, key=key_current) classes_current.extend([equivalence_class for (key,equivalence_class) in states_grouped]) return classes_current def quotient(self, classes): r""" Constructs the quotient with respect to the equivalence classes. INPUT: - ``classes`` is a list of equivalence classes of states. OUTPUT: A finite state machine. The labels of the new states are tuples of states of the ``self``, corresponding to ``classes``. Assume that `c` is a class, and `a` and `b` are states in `c`. Then there is a bijection `\varphi` between the transitions from `a` and the transitions from `b` with the following properties: if `\varphi(t_a)=t_b`, then - `t_a.\mathit{word}_\mathit{in}=t_b.\mathit{word}_\mathit{in}`, - `t_a.\mathit{word}_\mathit{out}=t_b.\mathit{word}_\mathit{out}`, and - `t_a` and `t_b` lead to some equivalent states `a'` and `b'`. Non-initial states may be merged with initial states, the resulting state is an initial state. All states in a class must have the same ``is_final``, ``final_word_out`` and ``word_out`` values. EXAMPLES:: sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0), ....: ("B", "C", 0, 0), ("B", "C", 1, 1), ....: ("C", "D", 0, 1), ("C", "D", 1, 0), ....: ("D", "A", 0, 0), ("D", "A", 1, 1)]) sage: fsmq = fsm.quotient([[fsm.state("A"), fsm.state("C")], ....: [fsm.state("B"), fsm.state("D")]]) sage: fsmq.transitions() [Transition from ('A', 'C') to ('B', 'D'): 0|1, Transition from ('A', 'C') to ('B', 'D'): 1|0, Transition from ('B', 'D') to ('A', 'C'): 0|0, Transition from ('B', 'D') to ('A', 'C'): 1|1] sage: fsmq.relabeled().transitions() [Transition from 0 to 1: 0|1, Transition from 0 to 1: 1|0, Transition from 1 to 0: 0|0, Transition from 1 to 0: 1|1] sage: fsmq1 = fsm.quotient(fsm.equivalence_classes()) sage: fsmq1 == fsmq True sage: fsm.quotient([[fsm.state("A"), fsm.state("B"), fsm.state("C"), fsm.state("D")]]) Traceback (most recent call last): ... AssertionError: Transitions of state 'A' and 'B' are incompatible. TESTS:: sage: fsm = FiniteStateMachine([("A", "B", 0, 1), ("A", "B", 1, 0), ....: ("B", "C", 0, 0), ("B", "C", 1, 1), ....: ("C", "D", 0, 1), ("C", "D", 1, 0), ....: ("D", "A", 0, 0), ("D", "A", 1, 1)], ....: final_states=["A", "C"]) sage: fsm.state("A").final_word_out = 1 sage: fsm.state("C").final_word_out = 2 sage: fsmq = fsm.quotient([[fsm.state("A"), fsm.state("C")], ....: [fsm.state("B"), fsm.state("D")]]) Traceback (most recent call last): ... AssertionError: Class ['A', 'C'] mixes final states with different final output words. """ new = self.empty_copy() state_mapping = {} # Create new states and build state_mapping for c in classes: new_label = tuple(c) new_state = c[0].relabeled(new_label) new.add_state(new_state) for state in c: state_mapping[state] = new_state # Copy data from old transducer for c in classes: new_state = state_mapping[c[0]] sorted_transitions = sorted( [(state_mapping[t.to_state], t.word_in, t.word_out) for t in c[0].transitions]) for transition in self.iter_transitions(c[0]): new.add_transition( from_state = new_state, to_state = state_mapping[transition.to_state], word_in = transition.word_in, word_out = transition.word_out) # check that all class members have the same information (modulo classes) for state in c: new_state.is_initial = new_state.is_initial or state.is_initial assert new_state.is_final == state.is_final, \ "Class %s mixes final and non-final states" % (c,) assert new_state.word_out == state.word_out, \ "Class %s mixes different word_out" % (c,) assert new_state.color == state.color, \ "Class %s mixes different colors" % (c,) assert sorted_transitions == sorted( [(state_mapping[t.to_state], t.word_in, t.word_out) for t in state.transitions]), \ "Transitions of state %s and %s are incompatible." % (c[0], state) assert new_state.final_word_out == state.final_word_out, \ "Class %s mixes final states with different " \ "final output words." % (c,) return new def merged_transitions(self): """ Merges transitions which have the same ``from_state``, ``to_state`` and ``word_out`` while adding their ``word_in``. INPUT: Nothing. OUTPUT: A finite state machine with merged transitions. If no mergers occur, return ``self``. EXAMPLE:: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: T = Transducer([[1, 2, 1/4, 1], [1, -2, 1/4, 1], [1, -2, 1/2, 1], ....: [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1], ....: [-2, 2, 1/4, 1], [2, 3, 1/2, 1], [-2, 3, 1/2, 1]], ....: on_duplicate_transition=duplicate_transition_add_input) sage: T1 = T.merged_transitions() sage: T1 is T False sage: sorted(T1.transitions()) [Transition from -2 to -2: 1/4|1, Transition from -2 to 2: 1/4|1, Transition from -2 to 3: 1/2|1, Transition from 1 to 2: 1/4|1, Transition from 1 to -2: 3/4|1, Transition from 2 to -2: 1/4|1, Transition from 2 to 2: 1/4|1, Transition from 2 to 3: 1/2|1] Applying the function again does not change the result:: sage: T2 = T1.merged_transitions() sage: T2 is T1 True """ new = self.empty_copy() changed = False state_dict = {} memo = {} for state in self.states(): new_state = deepcopy(state,memo) state_dict[state] = new_state new.add_state(new_state) for state in self.states(): grouped_transitions = itertools.groupby(sorted(state.transitions, key=key), key=key) for (to_state, word_out), transitions in grouped_transitions: transition_list = list(transitions) changed = changed or len(transition_list) > 1 word_in = 0 for transition in transition_list: if hasattr(transition.word_in, '__iter__') and len(transition.word_in) == 1: word_in += transition.word_in[0] else: raise TypeError('%s does not have a list of length 1 as word_in' % transition) new.add_transition((state, to_state, word_in, word_out)) if changed: return new else: return self def markov_chain_simplification(self): """ Consider ``self`` as Markov chain with probabilities as input labels and simplify it. INPUT: Nothing. OUTPUT: Simplified version of ``self``. EXAMPLE:: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: T = Transducer([[1, 2, 1/4, 0], [1, -2, 1/4, 0], [1, -2, 1/2, 0], ....: [2, 2, 1/4, 1], [2, -2, 1/4, 1], [-2, -2, 1/4, 1], ....: [-2, 2, 1/4, 1], [2, 3, 1/2, 2], [-2, 3, 1/2, 2]], ....: initial_states=[1], ....: final_states=[3], ....: on_duplicate_transition=duplicate_transition_add_input) sage: T1 = T.markov_chain_simplification() sage: sorted(T1.transitions()) [Transition from ((1,),) to ((2, -2),): 1|0, Transition from ((2, -2),) to ((2, -2),): 1/2|1, Transition from ((2, -2),) to ((3,),): 1/2|2] """ current = self.merged_transitions() number_states = len(current.states()) while True: current = current.simplification() new_number_states = len(current.states()) new = current.merged_transitions() if new is current and number_states == new_number_states: return new current = new number_states = new_number_states def with_final_word_out(self, letters, allow_non_final=True): """ Constructs a new finite state machine with final output words for all states by implicitly reading trailing letters until a final state is reached. INPUT: - ``letters`` -- either an element of the input alphabet or a list of such elements. This is repeated cyclically when needed. - ``allow_non_final`` -- a boolean (default: ``True``) which indicates whether we allow that some states may be non-final in the resulting finite state machine. I.e., if ``False`` then each state has to have a path to a final state with input label matching ``letters``. OUTPUT: A finite state machine. The inplace version of this function is :meth:`.construct_final_word_out`. Suppose for the moment a single element ``letter`` as input for ``letters``. This is equivalent to ``letters = [letter]``. We will discuss the general case below. Let ``word_in`` be a word over the input alphabet and assume that the original finite state machine transforms ``word_in`` to ``word_out`` reaching a possibly non-final state ``s``. Let further `k` be the minimum number of letters ``letter`` such that there is a path from ``s`` to some final state ``f`` whose input label consists of `k` copies of ``letter`` and whose output label is ``path_word_out``. Then the state ``s`` of the resulting finite state machine is a final state with final output ``path_word_out + f.final_word_out``. Therefore, the new finite state machine transforms ``word_in`` to ``word_out + path_word_out + f.final_word_out``. This is e.g. useful for finite state machines operating on digit expansions: there, it is sometimes required to read a sufficient number of trailing zeros (at the most significant positions) in order to reach a final state and to flush all carries. In this case, this method constructs an essentially equivalent finite state machine in the sense that it not longer requires adding sufficiently many trailing zeros. However, it is the responsibility of the user to make sure that if adding trailing zeros to the input anyway, the output is equivalent. If ``letters`` consists of more than one letter, then it is assumed that (not necessarily complete) cycles of ``letters`` are appended as trailing input. .. SEEALSO:: :ref:`example on Gray code <finite_state_machine_gray_code_example>` EXAMPLES: #. A simple transducer transforming `00` blocks to `01` blocks:: sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 1)], ....: initial_states=[0], ....: final_states=[0]) sage: T.process([0, 0, 0]) (False, 1, [0, 1, 0]) sage: T.process([0, 0, 0, 0]) (True, 0, [0, 1, 0, 1]) sage: F = T.with_final_word_out(0) sage: for f in F.iter_final_states(): ....: print f, f.final_word_out 0 [] 1 [1] sage: F.process([0, 0, 0]) (True, 1, [0, 1, 0, 1]) sage: F.process([0, 0, 0, 0]) (True, 0, [0, 1, 0, 1]) #. A more realistic example: Addition of `1` in binary. We construct a transition function transforming the input to its binary expansion:: sage: def binary_transition(carry, input): ....: value = carry + input ....: if value.mod(2) == 0: ....: return (value/2, 0) ....: else: ....: return ((value-1)/2, 1) Now, we only have to start with a carry of `1` to get the required transducer:: sage: T = Transducer(binary_transition, ....: input_alphabet=[0, 1], ....: initial_states=[1], ....: final_states=[0]) We test this for the binary expansion of `7`:: sage: T.process([1, 1, 1]) (False, 1, [0, 0, 0]) The final carry `1` has not be flushed yet, we have to add a trailing zero:: sage: T.process([1, 1, 1, 0]) (True, 0, [0, 0, 0, 1]) We check that with this trailing zero, the transducer performs as advertised:: sage: all(ZZ(T(k.bits()+[0]), base=2) == k + 1 ....: for k in srange(16)) True However, most of the time, we produce superfluous trailing zeros:: sage: T(11.bits()+[0]) [0, 0, 1, 1, 0] We now use this method:: sage: F = T.with_final_word_out(0) sage: for f in F.iter_final_states(): ....: print f, f.final_word_out 1 [1] 0 [] The same tests as above, but we do not have to pad with trailing zeros anymore:: sage: F.process([1, 1, 1]) (True, 1, [0, 0, 0, 1]) sage: all(ZZ(F(k.bits()), base=2) == k + 1 ....: for k in srange(16)) True No more trailing zero in the output:: sage: F(11.bits()) [0, 0, 1, 1] sage: all(F(k.bits())[-1] == 1 ....: for k in srange(16)) True #. Here is an example, where we allow trailing repeated `10`:: sage: T = Transducer([(0, 1, 0, 'a'), ....: (1, 2, 1, 'b'), ....: (2, 0, 0, 'c')], ....: initial_states=[0], ....: final_states=[0]) sage: F = T.with_final_word_out([1, 0]) sage: for f in F.iter_final_states(): ....: print f, ''.join(f.final_word_out) 0 1 bc Trying this with trailing repeated `01` does not produce a ``final_word_out`` for state ``1``, but for state ``2``:: sage: F = T.with_final_word_out([0, 1]) sage: for f in F.iter_final_states(): ....: print f, ''.join(f.final_word_out) 0 2 c #. Here another example with a more-letter trailing input:: sage: T = Transducer([(0, 1, 0, 'a'), ....: (1, 2, 0, 'b'), (1, 2, 1, 'b'), ....: (2, 3, 0, 'c'), (2, 0, 1, 'e'), ....: (3, 1, 0, 'd'), (3, 1, 1, 'd')], ....: initial_states=[0], ....: final_states=[0], ....: with_final_word_out=[0, 0, 1, 1]) sage: for f in T.iter_final_states(): ....: print f, ''.join(f.final_word_out) 0 1 bcdbcdbe 2 cdbe 3 dbe TESTS: #. Reading copies of ``letter`` may result in a cycle. In this simple example, we have no final state at all:: sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)], ....: initial_states=[0]) sage: T.with_final_word_out(0) Traceback (most recent call last): ... ValueError: The finite state machine contains a cycle starting at state 0 with input label 0 and no final state. #. A unique transition with input word ``letter`` is required:: sage: T = Transducer([(0, 1, 0, 0), (0, 2, 0, 0)]) sage: T.with_final_word_out(0) Traceback (most recent call last): ... ValueError: No unique transition leaving state 0 with input label 0. It is not a problem if there is no transition starting at state ``1`` with input word ``letter``:: sage: T = Transducer([(0, 1, 0, 0)]) sage: F = T.with_final_word_out(0) sage: for f in F.iter_final_states(): ....: print f, f.final_word_out Anyhow, you can override this by:: sage: T = Transducer([(0, 1, 0, 0)]) sage: T.with_final_word_out(0, allow_non_final=False) Traceback (most recent call last): ... ValueError: No unique transition leaving state 1 with input label 0. #. All transitions must have input labels of length `1`:: sage: T = Transducer([(0, 0, [], 0)]) sage: T.with_final_word_out(0) Traceback (most recent call last): ... NotImplementedError: All transitions must have input labels of length 1. Consider calling split_transitions(). sage: T = Transducer([(0, 0, [0, 1], 0)]) sage: T.with_final_word_out(0) Traceback (most recent call last): ... NotImplementedError: All transitions must have input labels of length 1. Consider calling split_transitions(). #. An empty list as input is not allowed:: sage: T = Transducer([(0, 0, [], 0)]) sage: T.with_final_word_out([]) Traceback (most recent call last): ... ValueError: letters is not allowed to be an empty list. """ new = deepcopy(self) new.construct_final_word_out(letters, allow_non_final) return new def construct_final_word_out(self, letters, allow_non_final=True): """ This is an inplace version of :meth:`.with_final_word_out`. See :meth:`.with_final_word_out` for documentation and examples. TESTS:: sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 1)], ....: initial_states=[0], ....: final_states=[0]) sage: F = T.with_final_word_out(0) sage: T.construct_final_word_out(0) sage: T == F # indirect doctest True sage: T = Transducer([(0, 1, 0, None)], ....: final_states=[1]) sage: F = T.with_final_word_out(0) sage: F.state(0).final_word_out [] """ from itertools import cycle, izip_longest if not isinstance(letters, list): letters = [letters] elif not letters: raise ValueError( "letters is not allowed to be an empty list.") in_progress = set() cache = {} for state in self.iter_states(): assert(not in_progress) # trailing_letters is an infinite iterator additionally # marking positions trailing_letters = cycle(enumerate(letters)) find_final_word_out(state) # actual modifications can only be carried out after all final words # have been computed as it may not be permissible to stop at a # formerly non-final state unless a cycle has been completed. for (state, position), final_word_out in cache.iteritems(): if position == 0 and final_word_out is not None: state.is_final = True state.final_word_out = final_word_out # ************************************************************************* # other # ************************************************************************* def graph(self, edge_labels='words_in_out'): """ Returns the graph of the finite state machine with labeled vertices and labeled edges. INPUT: - ``edge_label``: (default: ``'words_in_out'``) can be - ``'words_in_out'`` (labels will be strings ``'i|o'``) - a function with which takes as input a transition and outputs (returns) the label OUTPUT: A graph. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A') sage: T = Transducer() sage: T.graph() Digraph on 0 vertices sage: T.add_state(A) 'A' sage: T.graph() Digraph on 1 vertex sage: T.add_transition(('A', 'A', 0, 1)) Transition from 'A' to 'A': 0|1 sage: T.graph() Looped digraph on 1 vertex """ if edge_labels == 'words_in_out': label_fct = lambda t:t._in_out_label_() elif hasattr(edge_labels, '__call__'): label_fct = edge_labels else: raise TypeError('Wrong argument for edge_labels.') graph_data = [] isolated_vertices = [] for state in self.iter_states(): transitions = state.transitions if len(transitions) == 0: isolated_vertices.append(state.label()) for t in transitions: graph_data.append((t.from_state.label(), t.to_state.label(), label_fct(t))) G = DiGraph(graph_data) G.add_vertices(isolated_vertices) return G digraph = graph def plot(self): """ Plots a graph of the finite state machine with labeled vertices and labeled edges. INPUT: Nothing. OUTPUT: A plot of the graph of the finite state machine. TESTS:: sage: FiniteStateMachine([('A', 'A', 0)]).plot() """ return self.graph(edge_labels='words_in_out').plot() def predecessors(self, state, valid_input=None): """ Lists all predecessors of a state. INPUT: - ``state`` -- the state from which the predecessors should be listed. - ``valid_input`` -- If ``valid_input`` is a list, then we only consider transitions whose input labels are contained in ``valid_input``. ``state`` has to be a :class:`FSMState` (not a label of a state). If input labels of length larger than `1` are used, then ``valid_input`` has to be a list of lists. OUTPUT: A list of states. EXAMPLES:: sage: A = Transducer([('I', 'A', 'a', 'b'), ('I', 'B', 'b', 'c'), ....: ('I', 'C', 'c', 'a'), ('A', 'F', 'b', 'a'), ....: ('B', 'F', ['c', 'b'], 'b'), ('C', 'F', 'a', 'c')], ....: initial_states=['I'], final_states=['F']) sage: A.predecessors(A.state('A')) ['A', 'I'] sage: A.predecessors(A.state('F'), valid_input=['b', 'a']) ['F', 'C', 'A', 'I'] sage: A.predecessors(A.state('F'), valid_input=[['c', 'b'], 'a']) ['F', 'C', 'B'] """ if valid_input is not None: valid_list = list() for input in valid_input: input_list = input if not isinstance(input_list, list): input_list = [input] valid_list.append(input_list) valid_input = valid_list unhandeled_direct_predecessors = {s:[] for s in self.states() } for t in self.transitions(): if valid_input is None or t.word_in in valid_input: unhandeled_direct_predecessors[t.to_state].append(t.from_state) done = [] open = [state] while len(open) > 0: s = open.pop() candidates = unhandeled_direct_predecessors[s] if candidates is not None: open.extend(candidates) unhandeled_direct_predecessors[s] = None done.append(s) return(done) def asymptotic_moments(self, variable=SR.symbol('n')): r""" Returns the main terms of expectation and variance of the sum of output labels and its covariance with the sum of input labels. INPUT: - ``variable`` -- a symbol denoting the length of the input, by default `n`. OUTPUT: A dictionary consisting of - ``expectation`` -- `e n + \operatorname{Order}(1)`, - ``variance`` -- `v n + \operatorname{Order}(1)`, - ``covariance`` -- `c n + \operatorname{Order}(1)` for suitable constants `e`, `v` and `c`. Assume that all input and output labels are numbers and that ``self`` is complete and has only one final component. Assume further that this final component is aperiodic. Furthermore, assume that there is exactly one initial state and that all states are final. Denote by `X_n` the sum of output labels written by the finite state machine when reading a random input word of length `n` over the input alphabet (assuming equidistribution). Then the expectation of `X_n` is `en+O(1)`, the variance of `X_n` is `vn+O(1)` and the covariance of `X_n` and the sum of input labels is `cn+O(1)`, cf. [HKW2014]_, Theorem 2. In the case of non-integer input or output labels, performance degrades significantly. For rational input and output labels, consider rescaling to integers. This limitation comes from the fact that determinants over polynomial rings can be computed much more efficiently than over the symbolic ring. In fact, we compute (parts) of a trivariate generating function where the input and output labels are exponents of some indeterminates, see [HKW2014]_, Theorem 2 for details. If those exponents are integers, we can use a polynomial ring. EXAMPLES: #. A trivial example: write the negative of the input:: sage: T = Transducer([(0, 0, 0, 0), (0, 0, 1, -1)], ....: initial_states=[0], ....: final_states=[0]) sage: T([0, 1, 1]) [0, -1, -1] sage: moments = T.asymptotic_moments() sage: moments['expectation'] -1/2*n + Order(1) sage: moments['variance'] 1/4*n + Order(1) sage: moments['covariance'] -1/4*n + Order(1) #. For the case of the Hamming weight of the non-adjacent-form (NAF) of integers, cf. the :wikipedia:`Non-adjacent_form` and the :ref:`example on recognizing NAFs <finite_state_machine_recognizing_NAFs_example>`, the following agrees with the results in [HP2007]_. We first use the transducer to convert the standard binary expansion to the NAF given in [HP2007]_. We use the parameter ``with_final_word_out`` such that we do not have to add sufficiently many trailing zeros:: sage: NAF = Transducer([(0, 0, 0, 0), ....: (0, '.1', 1, None), ....: ('.1', 0, 0, [1, 0]), ....: ('.1', 1, 1, [-1, 0]), ....: (1, 1, 1, 0), ....: (1, '.1', 0, None)], ....: initial_states=[0], ....: final_states=[0], ....: with_final_word_out=[0]) As an example, we compute the NAF of `27` by this transducer. :: sage: binary_27 = 27.bits() sage: binary_27 [1, 1, 0, 1, 1] sage: NAF_27 = NAF(binary_27) sage: NAF_27 [-1, 0, -1, 0, 0, 1, 0] sage: ZZ(NAF_27, base=2) 27 Next, we are only interested in the Hamming weight:: sage: def weight(state, input): ....: if input is None: ....: result = 0 ....: else: ....: result = ZZ(input != 0) ....: return (0, result) sage: weight_transducer = Transducer(weight, ....: input_alphabet=[-1, 0, 1], ....: initial_states=[0], ....: final_states=[0]) At the moment, we can not use composition with ``NAF``, because it has non-empty final output words:: sage: NAFweight = weight_transducer.composition( ....: NAF, ....: algorithm='explorative') Traceback (most recent call last): ... NotImplementedError: Explorative composition is not implemented for transducers with non-empty final output words. Try the direct algorithm instead. Thus, we change ``NAF``, then compose and again construct the final output words:: sage: for s in NAF.final_states(): ....: s.final_word_out = [] sage: NAFweight = weight_transducer.composition( ....: NAF, ....: algorithm='explorative').relabeled() sage: NAFweight.construct_final_word_out(0) sage: sorted(NAFweight.transitions()) [Transition from 0 to 0: 0|0, Transition from 0 to 1: 1|-, Transition from 1 to 0: 0|1,0, Transition from 1 to 2: 1|1,0, Transition from 2 to 1: 0|-, Transition from 2 to 2: 1|0] sage: NAFweight(binary_27 + [0, 0]) [1, 0, 1, 0, 0, 1, 0] Now, we actually compute the asymptotic moments:: sage: moments = NAFweight.asymptotic_moments() sage: moments['expectation'] 1/3*n + Order(1) sage: moments['variance'] 2/27*n + Order(1) sage: moments['covariance'] Order(1) #. This is Example 3.1 in [HKW2014]_, where a transducer with variable output labels is given. There, the aim was to choose the output labels of this very simple transducer such that the input and output sum are asymptotically independent, i.e., the constant `c` vanishes. :: sage: var('a_1, a_2, a_3, a_4') (a_1, a_2, a_3, a_4) sage: T = Transducer([[0, 0, 0, a_1], [0, 1, 1, a_3], ....: [1, 0, 0, a_4], [1, 1, 1, a_2]], ....: initial_states=[0], final_states=[0, 1]) sage: moments = T.asymptotic_moments() verbose 0 (...) Non-integer output weights lead to significant performance degradation. sage: moments['expectation'] 1/4*(a_1 + a_2 + a_3 + a_4)*n + Order(1) sage: moments['covariance'] -1/4*(a_1 - a_2)*n + Order(1) Therefore, the asymptotic covariance vanishes if and only if `a_2=a_1`. #. This is Example 6.2 in [HKW2014]_, dealing with the transducer converting the binary expansion of an integer into Gray code (cf. the :wikipedia:`Gray_code` and the :ref:`example on Gray code <finite_state_machine_gray_code_example>`):: sage: moments = transducers.GrayCode().asymptotic_moments() sage: moments['expectation'] 1/2*n + Order(1) sage: moments['variance'] 1/4*n + Order(1) sage: moments['covariance'] Order(1) #. This is the first part of Example 6.3 in [HKW2014]_, counting the number of 10 blocks in the standard binary expansion. The least significant digit is at the left-most position:: sage: block10 = transducers.CountSubblockOccurrences( ....: [1, 0], ....: input_alphabet=[0, 1]) sage: sorted(block10.transitions()) [Transition from () to (): 0|0, Transition from () to (1,): 1|0, Transition from (1,) to (): 0|1, Transition from (1,) to (1,): 1|0] sage: moments = block10.asymptotic_moments() sage: moments['expectation'] 1/4*n + Order(1) sage: moments['variance'] 1/16*n + Order(1) sage: moments['covariance'] Order(1) #. This is the second part of Example 6.3 in [HKW2014]_, counting the number of 11 blocks in the standard binary expansion. The least significant digit is at the left-most position:: sage: block11 = transducers.CountSubblockOccurrences( ....: [1, 1], ....: input_alphabet=[0, 1]) sage: sorted(block11.transitions()) [Transition from () to (): 0|0, Transition from () to (1,): 1|0, Transition from (1,) to (): 0|0, Transition from (1,) to (1,): 1|1] sage: var('N') N sage: moments = block11.asymptotic_moments(N) sage: moments['expectation'] 1/4*N + Order(1) sage: moments['variance'] 5/16*N + Order(1) sage: correlation = (moments['covariance'].coefficient(N) / ....: (1/2 * sqrt(moments['variance'].coefficient(N)))) sage: correlation 2/5*sqrt(5) #. This is Example 6.4 in [HKW2014]_, counting the number of 01 blocks minus the number of 10 blocks in the standard binary expansion. The least significant digit is at the left-most position:: sage: block01 = transducers.CountSubblockOccurrences( ....: [0, 1], ....: input_alphabet=[0, 1]) sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = False sage: product_01x10 = block01.cartesian_product(block10) sage: block_difference = transducers.sub([0, 1])(product_01x10) sage: T = block_difference.simplification().relabeled() sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = True sage: T.transitions() [Transition from 0 to 1: 0|-1, Transition from 0 to 0: 1|0, Transition from 1 to 1: 0|0, Transition from 1 to 0: 1|1, Transition from 2 to 1: 0|0, Transition from 2 to 0: 1|0] sage: moments = T.asymptotic_moments() sage: moments['expectation'] Order(1) sage: moments['variance'] Order(1) sage: moments['covariance'] Order(1) #. The finite state machine must have a unique final component:: sage: T = Transducer([(0, -1, -1, -1), (0, 1, 1, 1), ....: (-1, -1, -1, -1), (-1, -1, 1, -1), ....: (1, 1, -1, 1), (1, 1, 1, 1)], ....: initial_states=[0], ....: final_states=[0, 1, -1]) sage: T.asymptotic_moments() Traceback (most recent call last): ... NotImplementedError: asymptotic_moments is only implemented for finite state machines with one final component. In this particular example, the first letter of the input decides whether we reach the loop at `-1` or the loop at `1`. In the first case, we have `X_n = -n`, while we have `X_n = n` in the second case. Therefore, the expectation `E(X_n)` of `X_n` is `E(X_n) = 0`. We get `(X_n-E(X_n))^2 = n^2` in all cases, which results in a variance of `n^2`. So this example shows that the variance may be non-linear if there is more than one final component. TESTS: #. An input alphabet must be given:: sage: T = Transducer([[0, 0, 0, 0]], ....: initial_states=[0], final_states=[0], ....: determine_alphabets=False) sage: T.asymptotic_moments() Traceback (most recent call last): ... ValueError: No input alphabet is given. Try calling determine_alphabets(). #. The finite state machine must have a unique initial state:: sage: T = Transducer([(0, 0, 0, 0)]) sage: T.asymptotic_moments() Traceback (most recent call last): ... ValueError: A unique initial state is required. #. The finite state machine must be complete:: sage: T = Transducer([[0, 0, 0, 0]], ....: initial_states=[0], final_states=[0], ....: input_alphabet=[0, 1]) sage: T.asymptotic_moments() Traceback (most recent call last): ... NotImplementedError: This finite state machine is not complete. #. The final component of the finite state machine must be aperiodic:: sage: T = Transducer([(0, 1, 0, 0), (1, 0, 0, 0)], ....: initial_states=[0], final_states=[0, 1]) sage: T.asymptotic_moments() Traceback (most recent call last): ... NotImplementedError: asymptotic_moments is only implemented for finite state machines whose unique final component is aperiodic. #. Non-integer input or output labels lead to a warning:: sage: T = Transducer([[0, 0, 0, 0], [0, 0, 1, -1/2]], ....: initial_states=[0], final_states=[0]) sage: moments = T.asymptotic_moments() verbose 0 (...) Non-integer output weights lead to significant performance degradation. sage: moments['expectation'] -1/4*n + Order(1) sage: moments['variance'] 1/16*n + Order(1) sage: moments['covariance'] -1/8*n + Order(1) This warning can be silenced by :func:`~sage.misc.misc.set_verbose`:: sage: set_verbose(-1, "finite_state_machine.py") sage: moments = T.asymptotic_moments() sage: moments['expectation'] -1/4*n + Order(1) sage: moments['variance'] 1/16*n + Order(1) sage: moments['covariance'] -1/8*n + Order(1) sage: set_verbose(0, "finite_state_machine.py") #. Check whether ``word_out`` of ``FSMState`` are correctly dealt with:: sage: from sage.combinat.finite_state_machine import FSMState sage: s = FSMState(0, word_out=2, ....: is_initial=True, ....: is_final=True) sage: T = Transducer([(s, s, 0, 1)], ....: initial_states=[s], final_states=[s]) sage: T([0, 0]) [2, 1, 2, 1, 2] sage: T.asymptotic_moments()['expectation'] 3*n + Order(1) The same test for non-integer output:: sage: from sage.combinat.finite_state_machine import FSMState sage: s = FSMState(0, word_out=2/3) sage: T = Transducer([(s, s, 0, 1/2)], ....: initial_states=[s], final_states=[s]) sage: T.asymptotic_moments()['expectation'] verbose 0 (...) Non-integer output weights lead to significant performance degradation. 7/6*n + Order(1) #. All states of ``self`` have to be final:: sage: T = Transducer([(0, 1, 1, 4)], initial_states=[0]) sage: T.asymptotic_moments() Traceback (most recent call last): ... ValueError: Not all states are final. ALGORITHM: See [HKW2014]_, Theorem 2. REFERENCES: .. [HKW2014] Clemens Heuberger, Sara Kropf and Stephan Wagner, *Combinatorial Characterization of Independent Transducers via Functional Digraphs*, :arxiv:`1404.3680`. .. [HP2007] Clemens Heuberger and Helmut Prodinger, *The Hamming Weight of the Non-Adjacent-Form under Various Input Statistics*, Periodica Mathematica Hungarica Vol. 55 (1), 2007, pp. 81–96, :doi:`10.1007/s10998-007-3081-z`. """ from sage.calculus.functional import derivative from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing from sage.rings.rational_field import QQ if self.input_alphabet is None: raise ValueError("No input alphabet is given. " "Try calling determine_alphabets().") if len(self.initial_states()) != 1: raise ValueError("A unique initial state is required.") if not all(state.is_final for state in self.iter_states()): raise ValueError("Not all states are final.") if not self.is_complete(): raise NotImplementedError("This finite state machine is " "not complete.") final_components = self.final_components() if len(final_components) != 1: raise NotImplementedError("asymptotic_moments is only " "implemented for finite state machines " "with one final component.") final_component = final_components[0] if not final_component.digraph().is_aperiodic(): raise NotImplementedError("asymptotic_moments is only " "implemented for finite state machines " "whose unique final component is " "aperiodic.") K = len(self.input_alphabet) R = PolynomialRing(QQ, ("x", "y", "z")) (x, y, z) = R.gens() try: M = get_matrix(self, x, y) except TypeError: verbose("Non-integer output weights lead to " "significant performance degradation.", level=0) # fall back to symbolic ring R = SR x = R.symbol() y = R.symbol() z = R.symbol() M = get_matrix(self, x, y) else: f = (M.parent().identity_matrix() - z/K*M).det() f_x = substitute_one(derivative(f, x)) f_y = substitute_one(derivative(f, y)) f_z = substitute_one(derivative(f, z)) f_xy = substitute_one(derivative(f, x, y)) f_xz = substitute_one(derivative(f, x, z)) f_yz = substitute_one(derivative(f, y, z)) f_yy = substitute_one(derivative(f, y, y)) f_zz = substitute_one(derivative(f, z, z)) e_2 = f_y / f_z v_2 = (f_y**2 * (f_zz+f_z) + f_z**2 * (f_yy+f_y) - 2*f_y*f_z*f_yz) / f_z**3 c = (f_x * f_y * (f_zz+f_z) + f_z**2 * f_xy - f_y*f_z*f_xz - f_x*f_z*f_yz) / f_z**3 return {'expectation': e_2*variable + SR(1).Order(), 'variance': v_2*variable + SR(1).Order(), 'covariance': c*variable + SR(1).Order()} def is_monochromatic(self): """ Checks whether the colors of all states are equal. INPUT: Nothing. OUTPUT: ``True`` or ``False``. EXAMPLES:: sage: G = transducers.GrayCode() sage: [s.color for s in G.iter_states()] [None, None, None] sage: G.is_monochromatic() True sage: G.state(1).color = 'blue' sage: G.is_monochromatic() False """ return equal(s.color for s in self.iter_states()) #***************************************************************************** def is_Automaton(FSM): """ Tests whether or not ``FSM`` inherits from :class:`Automaton`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Automaton sage: is_Automaton(FiniteStateMachine()) False sage: is_Automaton(Automaton()) True sage: is_FiniteStateMachine(Automaton()) True """ return isinstance(FSM, Automaton) class Automaton(FiniteStateMachine): """ This creates an automaton, which is a finite state machine, whose transitions have input labels. An automaton has additional features like creating a deterministic and a minimized automaton. See class :class:`FiniteStateMachine` for more information. EXAMPLES: We can create an automaton recognizing even numbers (given in binary and read from left to right) in the following way:: sage: A = Automaton([('P', 'Q', 0), ('P', 'P', 1), ....: ('Q', 'P', 1), ('Q', 'Q', 0)], ....: initial_states=['P'], final_states=['Q']) sage: A Automaton with 2 states sage: A([0]) True sage: A([1, 1, 0]) True sage: A([1, 0, 1]) False Note that the full output of the commands can be obtained by calling :meth:`.process` and looks like this:: sage: A.process([1, 0, 1]) (False, 'P') TESTS:: sage: Automaton() Automaton with 0 states """ def __init__(self, *args, **kwargs): """ Initialize an automaton. See :class:`Automaton` and its parent :class:`FiniteStateMachine` for more information. TESTS:: sage: Transducer()._allow_composition_ True sage: Automaton()._allow_composition_ False """ super(Automaton, self).__init__(*args, **kwargs) self._allow_composition_ = False def _repr_(self): """ Represents the finite state machine as "Automaton with n states" where n is the number of states. INPUT: Nothing. OUTPUT: A string. EXAMPLES:: sage: Automaton()._repr_() 'Automaton with 0 states' """ return "Automaton with %s states" % len(self._states_) def _latex_transition_label_(self, transition, format_function=latex): r""" Returns the proper transition label. INPUT: - ``transition`` - a transition - ``format_function`` - a function formatting the labels OUTPUT: A string. EXAMPLES:: sage: F = Automaton([('A', 'B', 1)]) sage: print latex(F) # indirect doctest \begin{tikzpicture}[auto, initial text=, >=latex] \node[state] (v0) at (3.000000, 0.000000) {$\text{\texttt{A}}$}; \node[state] (v1) at (-3.000000, 0.000000) {$\text{\texttt{B}}$}; \path[->] (v0) edge node[rotate=360.00, anchor=south] {$1$} (v1); \end{tikzpicture} TESTS:: sage: F = Automaton([('A', 'B', 0, 1)]) sage: t = F.transitions()[0] sage: F._latex_transition_label_(t) \left[0\right] """ return format_function(transition.word_in) def intersection(self, other, only_accessible_components=True): """ Returns a new automaton which accepts an input if it is accepted by both given automata. INPUT: - ``other`` -- an automaton - ``only_accessible_components`` -- If ``True`` (default), then the result is piped through :meth:`.accessible_components`. If no ``new_input_alphabet`` is given, it is determined by :meth:`.determine_alphabets`. OUTPUT: A new automaton which computes the intersection (see below) of the languages of ``self`` and ``other``. The set of states of the new automaton is the cartesian product of the set of states of both given automata. There is a transition `((A, B), (C, D), a)` in the new automaton if there are transitions `(A, C, a)` and `(B, D, a)` in the old automata. The methods :meth:`.intersection` and :meth:`.cartesian_product` are the same (for automata). EXAMPLES:: sage: aut1 = Automaton([('1', '2', 1), ....: ('2', '2', 1), ....: ('2', '2', 0)], ....: initial_states=['1'], ....: final_states=['2'], ....: determine_alphabets=True) sage: aut2 = Automaton([('A', 'A', 1), ....: ('A', 'B', 0), ....: ('B', 'B', 0), ....: ('B', 'A', 1)], ....: initial_states=['A'], ....: final_states=['B'], ....: determine_alphabets=True) sage: res = aut1.intersection(aut2) sage: (aut1([1, 1]), aut2([1, 1]), res([1, 1])) (True, False, False) sage: (aut1([1, 0]), aut2([1, 0]), res([1, 0])) (True, True, True) sage: res.transitions() [Transition from ('1', 'A') to ('2', 'A'): 1|-, Transition from ('2', 'A') to ('2', 'B'): 0|-, Transition from ('2', 'A') to ('2', 'A'): 1|-, Transition from ('2', 'B') to ('2', 'B'): 0|-, Transition from ('2', 'B') to ('2', 'A'): 1|-] For automata with epsilon-transitions, intersection is not well defined. But for any finite state machine, epsilon-transitions can be removed by :meth:`.remove_epsilon_transitions`. :: sage: a1 = Automaton([(0, 0, 0), ....: (0, 1, None), ....: (1, 1, 1), ....: (1, 2, 1)], ....: initial_states=[0], ....: final_states=[1], ....: determine_alphabets=True) sage: a2 = Automaton([(0, 0, 0), (0, 1, 1), (1, 1, 1)], ....: initial_states=[0], ....: final_states=[1], ....: determine_alphabets=True) sage: a1.intersection(a2) Traceback (most recent call last): ... ValueError: An epsilon-transition (with empty input) was found. sage: a1.remove_epsilon_transitions() # not tested (since not implemented yet) sage: a1.intersection(a2) # not tested """ if not is_Automaton(other): raise TypeError( "Only an automaton can be intersected with an automaton.") return self.product_FiniteStateMachine( other, function, only_accessible_components=only_accessible_components) cartesian_product = intersection def determinisation(self): """ Returns a deterministic automaton which accepts the same input words as the original one. INPUT: Nothing. OUTPUT: A new automaton, which is deterministic. The labels of the states of the new automaton are frozensets of states of ``self``. The color of a new state is the frozenset of colors of the constituent states of ``self``. Therefore, the colors of the constituent states have to be hashable. The input alphabet must be specified. EXAMPLES:: sage: aut = Automaton([('A', 'A', 0), ('A', 'B', 1), ('B', 'B', 1)], ....: initial_states=['A'], final_states=['B']) sage: aut.determinisation().transitions() [Transition from frozenset(['A']) to frozenset(['A']): 0|-, Transition from frozenset(['A']) to frozenset(['B']): 1|-, Transition from frozenset(['B']) to frozenset([]): 0|-, Transition from frozenset(['B']) to frozenset(['B']): 1|-, Transition from frozenset([]) to frozenset([]): 0|-, Transition from frozenset([]) to frozenset([]): 1|-] :: sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1), ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)], ....: initial_states=['A'], final_states=['C']) sage: A.determinisation().states() [frozenset(['A']), frozenset(['A', 'B']), frozenset(['A', 'C']), frozenset(['A', 'C', 'B'])] :: sage: A = Automaton([(0, 1, 1), (0, 2, [1, 1]), (0, 3, [1, 1, 1]), ....: (1, 0, -1), (2, 0, -2), (3, 0, -3)], ....: initial_states=[0], final_states=[0, 1, 2, 3]) sage: B = A.determinisation().relabeled() sage: all(t.to_state.label() == 2 for t in ....: B.state(2).transitions) True sage: B.state(2).is_final False sage: B.delete_state(2) # this is a sink sage: sorted(B.transitions()) [Transition from 0 to 1: 1|-, Transition from 1 to 0: -1|-, Transition from 1 to 3: 1|-, Transition from 3 to 0: -2|-, Transition from 3 to 4: 1|-, Transition from 4 to 0: -3|-] Note that colors of states have to be hashable:: sage: A = Automaton([[0, 0, 0]], initial_states=[0]) sage: A.state(0).color = [] sage: A.determinisation() Traceback (most recent call last): ... TypeError: unhashable type: 'list' sage: A.state(0).color = () sage: A.determinisation() Automaton with 1 states TESTS: This is from #15078, comment 13. :: sage: D = {'A': [('A', 'a'), ('B', 'a'), ('A', 'b')], ....: 'C': [], 'B': [('C', 'b')]} sage: auto = Automaton(D, initial_states=['A'], final_states=['C']) sage: auto.is_deterministic() False sage: auto.process(list('aaab')) Traceback (most recent call last): ... NotImplementedError: Non-deterministic path encountered when processing input. sage: auto.states() ['A', 'C', 'B'] sage: Ddet = auto.determinisation() sage: Ddet Automaton with 3 states sage: Ddet.is_deterministic() True sage: sorted(Ddet.transitions()) [Transition from frozenset(['A']) to frozenset(['A', 'B']): 'a'|-, Transition from frozenset(['A']) to frozenset(['A']): 'b'|-, Transition from frozenset(['A', 'B']) to frozenset(['A', 'B']): 'a'|-, Transition from frozenset(['A', 'B']) to frozenset(['A', 'C']): 'b'|-, Transition from frozenset(['A', 'C']) to frozenset(['A', 'B']): 'a'|-, Transition from frozenset(['A', 'C']) to frozenset(['A']): 'b'|-] sage: Ddet.initial_states() [frozenset(['A'])] sage: Ddet.final_states() [frozenset(['A', 'C'])] """ if any(len(t.word_in) > 1 for t in self.iter_transitions()): return self.split_transitions().determinisation() epsilon_successors = {} direct_epsilon_successors = {} for state in self.iter_states(): direct_epsilon_successors[state] = set( t.to_state for t in self.iter_transitions(state) if not t.word_in) epsilon_successors[state] = set([state]) old_count_epsilon_successors = 0 count_epsilon_successors = len(epsilon_successors) while old_count_epsilon_successors < count_epsilon_successors: old_count_epsilon_successors = count_epsilon_successors count_epsilon_successors = 0 for state in self.iter_states(): for direct_successor in direct_epsilon_successors[state]: epsilon_successors[state] = epsilon_successors[state].union(epsilon_successors[direct_successor]) count_epsilon_successors += len(epsilon_successors[state]) result = self.empty_copy() new_initial_states = [frozenset(self.iter_initial_states())] result.add_from_transition_function(set_transition, initial_states=new_initial_states) for state in result.iter_states(): state.is_final = any(s.is_final for s in state.label()) state.color = frozenset(s.color for s in state.label()) return result def minimization(self, algorithm=None): """ Returns the minimization of the input automaton as a new automaton. INPUT: - ``algorithm`` -- Either Moore's algorithm (by ``algorithm='Moore'`` or as default for deterministic automata) or Brzozowski's algorithm (when ``algorithm='Brzozowski'`` or when the automaton is not deterministic) is used. OUTPUT: A new automaton. The resulting automaton is deterministic and has a minimal number of states. EXAMPLES:: sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1), ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)], ....: initial_states=['A'], final_states=['C']) sage: B = A.minimization(algorithm='Brzozowski') sage: B.transitions(B.states()[1]) [Transition from frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]) to frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C']), frozenset(['C'])]): 0|-, Transition from frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]) to frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]): 1|-] sage: len(B.states()) 3 sage: C = A.minimization(algorithm='Brzozowski') sage: C.transitions(C.states()[1]) [Transition from frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]) to frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C']), frozenset(['C'])]): 0|-, Transition from frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]) to frozenset([frozenset(['A', 'C', 'B']), frozenset(['C', 'B']), frozenset(['A', 'C'])]): 1|-] sage: len(C.states()) 3 :: sage: aut = Automaton([('1', '2', 'a'), ('2', '3', 'b'), ....: ('3', '2', 'a'), ('2', '1', 'b'), ....: ('3', '4', 'a'), ('4', '3', 'b')], ....: initial_states=['1'], final_states=['1']) sage: min = aut.minimization(algorithm='Brzozowski') sage: [len(min.states()), len(aut.states())] [3, 4] sage: min = aut.minimization(algorithm='Moore') Traceback (most recent call last): ... NotImplementedError: Minimization via Moore's Algorithm is only implemented for deterministic finite state machines """ deterministic = self.is_deterministic() if algorithm == "Moore" or (algorithm is None and deterministic): return self._minimization_Moore_() elif algorithm == "Brzozowski" or (algorithm is None and not deterministic): return self._minimization_Brzozowski_() else: raise NotImplementedError("Algorithm '%s' is not implemented. Choose 'Moore' or 'Brzozowski'" % algorithm) def _minimization_Brzozowski_(self): """ Returns a minimized automaton by using Brzozowski's algorithm. See also :meth:`.minimization`. TESTS:: sage: A = Automaton([('A', 'A', 1), ('A', 'A', 0), ('A', 'B', 1), ....: ('B', 'C', 0), ('C', 'C', 1), ('C', 'C', 0)], ....: initial_states=['A'], final_states=['C']) sage: B = A._minimization_Brzozowski_() sage: len(B.states()) 3 """ return self.transposition().determinisation().transposition().determinisation() def _minimization_Moore_(self): """ Returns a minimized automaton by using Moore's algorithm. See also :meth:`.minimization`. TESTS:: sage: aut = Automaton([('1', '2', 'a'), ('2', '3', 'b'), ....: ('3', '2', 'a'), ('2', '1', 'b'), ....: ('3', '4', 'a'), ('4', '3', 'b')], ....: initial_states=['1'], final_states=['1']) sage: min = aut._minimization_Moore_() Traceback (most recent call last): ... NotImplementedError: Minimization via Moore's Algorithm is only implemented for deterministic finite state machines """ if self.is_deterministic(): return self.quotient(self.equivalence_classes()) else: raise NotImplementedError("Minimization via Moore's Algorithm is only " \ "implemented for deterministic finite state machines") def process(self, *args, **kwargs): """ .. WARNING:: The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting ``FSMOldProcessOutput`` to ``False``. Returns whether the automaton accepts the input and the state where the computation stops. INPUT: - ``input_tape`` -- The input tape can be a list with entries from the input alphabet. - ``initial_state`` -- (default: ``None``) The state in which to start. If this parameter is ``None`` and there is only one initial state in the machine, then this state is taken. - ``full_output`` -- (default: ``True``) If set, then the full output is given, otherwise only whether the sequence is accepted or not (the first entry below only). OUTPUT: The full output is a pair, where - the first entry is ``True`` if the input string is accepted and - the second gives the state reached after processing the input tape (This is a state with label ``None`` if the input could not be processed, i.e., when at one point no transition to go could be found.). By setting ``FSMOldProcessOutput`` to ``False`` the new desired output is produced. EXAMPLES:: sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False # activate new output behavior sage: from sage.combinat.finite_state_machine import FSMState sage: NAF_ = FSMState('_', is_initial = True, is_final = True) sage: NAF1 = FSMState('1', is_final = True) sage: NAF = Automaton( ....: {NAF_: [(NAF_, 0), (NAF1, 1)], NAF1: [(NAF_, 0)]}) sage: [NAF.process(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1], ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]] [(True, '_'), (True, '1'), (False, None), (True, '1'), (False, None), (False, None)] If we just want a condensed output, we use:: sage: [NAF.process(w, full_output=False) ....: for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1], ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]] [True, True, False, True, False, False] It is equivalent to:: sage: [NAF(w) for w in [[0], [0, 1], [1, 1], [0, 1, 0, 1], ....: [0, 1, 1, 1, 0], [1, 0, 0, 1, 1]]] [True, True, False, True, False, False] The following example illustrates the difference between non-existing paths and reaching a non-final state:: sage: NAF.process([2]) (False, None) sage: NAF.add_transition(('_', 's', 2)) Transition from '_' to 's': 2|- sage: NAF.process([2]) (False, 's') """ if FSMOldProcessOutput: from sage.misc.superseded import deprecation deprecation(16132, "The output of Automaton.process " "(and thus of Automaton.__call__) " "will change. Please use the corresponding " "functions from FiniteStateMachine " "for the original output.") return super(Automaton, self).process(*args, **kwargs) if not kwargs.has_key('full_output'): kwargs['full_output'] = True it = self.iter_process(*args, **kwargs) for _ in it: pass # process output if kwargs['full_output']: return (it.accept_input, it.current_state) else: return it.accept_input #***************************************************************************** def is_Transducer(FSM): """ Tests whether or not ``FSM`` inherits from :class:`Transducer`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FiniteStateMachine, is_Transducer sage: is_Transducer(FiniteStateMachine()) False sage: is_Transducer(Transducer()) True sage: is_FiniteStateMachine(Transducer()) True """ return isinstance(FSM, Transducer) class Transducer(FiniteStateMachine): """ This creates a transducer, which is a finite state machine, whose transitions have input and output labels. An transducer has additional features like creating a simplified transducer. See class :class:`FiniteStateMachine` for more information. EXAMPLES: We can create a transducer performing the addition of 1 (for numbers given in binary and read from right to left) in the following way:: sage: T = Transducer([('C', 'C', 1, 0), ('C', 'N', 0, 1), ....: ('N', 'N', 0, 0), ('N', 'N', 1, 1)], ....: initial_states=['C'], final_states=['N']) sage: T Transducer with 2 states sage: T([0]) [1] sage: T([1,1,0]) [0, 0, 1] sage: ZZ(T(15.digits(base=2)+[0]), base=2) 16 Note that we have padded the binary input sequence by a `0` so that the transducer can reach its final state. TESTS:: sage: Transducer() Transducer with 0 states """ def _repr_(self): """ Represents the transducer as "Transducer with n states" where n is the number of states. INPUT: Nothing. OUTPUT: A string. EXAMPLES:: sage: Transducer()._repr_() 'Transducer with 0 states' """ return "Transducer with %s states" % len(self._states_) def _latex_transition_label_(self, transition, format_function=latex): r""" Returns the proper transition label. INPUT: - ``transition`` - a transition - ``format_function`` - a function formatting the labels OUTPUT: A string. EXAMPLES:: sage: F = Transducer([('A', 'B', 1, 2)]) sage: print latex(F) # indirect doctest \begin{tikzpicture}[auto, initial text=, >=latex] \node[state] (v0) at (3.000000, 0.000000) {$\text{\texttt{A}}$}; \node[state] (v1) at (-3.000000, 0.000000) {$\text{\texttt{B}}$}; \path[->] (v0) edge node[rotate=360.00, anchor=south] {$1\mid 2$} (v1); \end{tikzpicture} TESTS:: sage: F = Transducer([('A', 'B', 0, 1)]) sage: t = F.transitions()[0] sage: F._latex_transition_label_(t) \left[0\right] \mid \left[1\right] """ return (format_function(transition.word_in) + "\\mid " + format_function(transition.word_out)) def intersection(self, other, only_accessible_components=True): """ Returns a new transducer which accepts an input if it is accepted by both given finite state machines producing the same output. INPUT: - ``other`` -- a transducer - ``only_accessible_components`` -- If ``True`` (default), then the result is piped through :meth:`.accessible_components`. If no ``new_input_alphabet`` is given, it is determined by :meth:`.determine_alphabets`. OUTPUT: A new transducer which computes the intersection (see below) of the languages of ``self`` and ``other``. The set of states of the transducer is the cartesian product of the set of states of both given transducer. There is a transition `((A, B), (C, D), a, b)` in the new transducer if there are transitions `(A, C, a, b)` and `(B, D, a, b)` in the old transducers. EXAMPLES:: sage: transducer1 = Transducer([('1', '2', 1, 0), ....: ('2', '2', 1, 0), ....: ('2', '2', 0, 1)], ....: initial_states=['1'], ....: final_states=['2']) sage: transducer2 = Transducer([('A', 'A', 1, 0), ....: ('A', 'B', 0, 0), ....: ('B', 'B', 0, 1), ....: ('B', 'A', 1, 1)], ....: initial_states=['A'], ....: final_states=['B']) sage: res = transducer1.intersection(transducer2) sage: res.transitions() [Transition from ('1', 'A') to ('2', 'A'): 1|0, Transition from ('2', 'A') to ('2', 'A'): 1|0] In general, transducers are not closed under intersection. But for transducer which do not have epsilon-transitions, the intersection is well defined (cf. [BaWo2012]_). However, in the next example the intersection of the two transducers is not well defined. The intersection of the languages consists of `(a^n, b^n c^n)`. This set is not recognizable by a *finite* transducer. :: sage: t1 = Transducer([(0, 0, 'a', 'b'), ....: (0, 1, None, 'c'), ....: (1, 1, None, 'c')], ....: initial_states=[0], ....: final_states=[0, 1]) sage: t2 = Transducer([('A', 'A', None, 'b'), ....: ('A', 'B', 'a', 'c'), ....: ('B', 'B', 'a', 'c')], ....: initial_states=['A'], ....: final_states=['A', 'B']) sage: t2.intersection(t1) Traceback (most recent call last): ... ValueError: An epsilon-transition (with empty input or output) was found. TESTS:: sage: transducer1 = Transducer([('1', '2', 1, 0)], ....: initial_states=['1'], ....: final_states=['2']) sage: transducer2 = Transducer([('A', 'B', 1, 0)], ....: initial_states=['A'], ....: final_states=['B']) sage: res = transducer1.intersection(transducer2) sage: res.final_states() [('2', 'B')] sage: transducer1.state('2').final_word_out = 1 sage: transducer2.state('B').final_word_out = 2 sage: res = transducer1.intersection(transducer2) sage: res.final_states() [] REFERENCES: .. [BaWo2012] Javier Baliosian and Dina Wonsever, *Finite State Transducers*, chapter in *Handbook of Finite State Based Models and Applications*, edited by Jiacun Wang, Chapman and Hall/CRC, 2012. """ if not is_Transducer(other): raise TypeError( "Only a transducer can be intersected with a transducer.") new = self.product_FiniteStateMachine( other, function, only_accessible_components=only_accessible_components, final_function=lambda s1, s2: s1.final_word_out) for state in new.iter_final_states(): state0 = self.state(state.label()[0]) state1 = other.state(state.label()[1]) if state0.final_word_out != state1.final_word_out: state.final_word_out = None state.is_final = False return new def cartesian_product(self, other, only_accessible_components=True): """ .. WARNING:: The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting ``FSMOldCodeTransducerCartesianProduct`` to ``False``. Return a new transducer which can simultaneously process an input with the machines ``self`` and ``other`` where the output labels are `d`-tuples of the original output labels. INPUT: - ``other`` - a finite state machine (if `d=2`) or a list (or other iterable) of `d-1` finite state machines - ``only_accessible_components`` -- If ``True`` (default), then the result is piped through :meth:`.accessible_components`. If no ``new_input_alphabet`` is given, it is determined by :meth:`.determine_alphabets`. OUTPUT: A transducer which can simultaneously process an input with ``self`` and the machine(s) in ``other``. The set of states of the new transducer is the cartesian product of the set of states of ``self`` and ``other``. Let `(A_j, B_j, a_j, b_j)` for `j\in\{1, \ldots, d\}` be transitions in the machines ``self`` and in ``other``. Then there is a transition `((A_1, \ldots, A_d), (B_1, \ldots, B_d), a, (b_1, \ldots, b_d))` in the new transducer if `a_1 = \cdots = a_d =: a`. EXAMPLES: Originally a different output was constructed by :meth:`Transducer.cartesian_product`. This output is now produced by :meth:`Transducer.intersection`. :: sage: transducer1 = Transducer([('A', 'A', 0, 0), ....: ('A', 'A', 1, 1)], ....: initial_states=['A'], ....: final_states=['A'], ....: determine_alphabets=True) sage: transducer2 = Transducer([(0, 1, 0, ['b', 'c']), ....: (0, 0, 1, 'b'), ....: (1, 1, 0, 'a')], ....: initial_states=[0], ....: final_states=[1], ....: determine_alphabets=True) sage: result = transducer1.cartesian_product(transducer2) doctest:...: DeprecationWarning: The output of Transducer.cartesian_product will change. Please use Transducer.intersection for the original output. See http://trac.sagemath.org/16061 for details. sage: result Transducer with 0 states By setting ``FSMOldCodeTransducerCartesianProduct`` to ``False`` the new desired output is produced. :: sage: sage.combinat.finite_state_machine.FSMOldCodeTransducerCartesianProduct = False sage: result = transducer1.cartesian_product(transducer2) sage: result Transducer with 2 states sage: result.transitions() [Transition from ('A', 0) to ('A', 1): 0|(0, 'b'),(None, 'c'), Transition from ('A', 0) to ('A', 0): 1|(1, 'b'), Transition from ('A', 1) to ('A', 1): 0|(0, 'a')] sage: result([1, 0, 0]) [(1, 'b'), (0, 'b'), (None, 'c'), (0, 'a')] sage: (transducer1([1, 0, 0]), transducer2([1, 0, 0])) ([1, 0, 0], ['b', 'b', 'c', 'a']) Also final output words are correctly processed:: sage: transducer1.state('A').final_word_out = 2 sage: result = transducer1.cartesian_product(transducer2) sage: result.final_states()[0].final_word_out [(2, None)] The following transducer counts the number of 11 blocks minus the number of 10 blocks over the alphabet ``[0, 1]``. :: sage: count_11 = transducers.CountSubblockOccurrences( ....: [1, 1], ....: input_alphabet=[0, 1]) sage: count_10 = transducers.CountSubblockOccurrences( ....: [1, 0], ....: input_alphabet=[0, 1]) sage: count_11x10 = count_11.cartesian_product(count_10) sage: difference = transducers.sub([0, 1])(count_11x10) sage: T = difference.simplification().relabeled() sage: T.initial_states() [1] sage: sorted(T.transitions()) [Transition from 0 to 1: 0|-1, Transition from 0 to 0: 1|1, Transition from 1 to 1: 0|0, Transition from 1 to 0: 1|0] sage: input = [0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0] sage: output = [0, 0, 1, -1, 0, -1, 0, 0, 0, 1, 1, -1] sage: T(input) == output True If ``other`` is an automaton, then :meth:`.cartesian_product` returns ``self`` where the input is restricted to the input accepted by ``other``. For example, if the transducer transforms the standard binary expansion into the non-adjacent form and the automaton recognizes the binary expansion without adjacent ones, then the cartesian product of these two is a transducer which does not change the input (except for changing ``a`` to ``(a, None)`` and ignoring a leading `0`). :: sage: NAF = Transducer([(0, 1, 0, None), ....: (0, 2, 1, None), ....: (1, 1, 0, 0), ....: (1, 2, 1, 0), ....: (2, 1, 0, 1), ....: (2, 3, 1, -1), ....: (3, 2, 0, 0), ....: (3, 3, 1, 0)], ....: initial_states=[0], ....: final_states=[1], ....: determine_alphabets=True) sage: aut11 = Automaton([(0, 0, 0), (0, 1, 1), (1, 0, 0)], ....: initial_states=[0], ....: final_states=[0, 1], ....: determine_alphabets=True) sage: res = NAF.cartesian_product(aut11) sage: res([1, 0, 0, 1, 0, 1, 0]) [(1, None), (0, None), (0, None), (1, None), (0, None), (1, None)] This is obvious because if the standard binary expansion does not have adjacent ones, then it is the same as the non-adjacent form. Be aware that :meth:`.cartesian_product` is not commutative. :: sage: aut11.cartesian_product(NAF) Traceback (most recent call last): ... TypeError: Only an automaton can be intersected with an automaton. The cartesian product of more than two finite state machines can also be computed:: sage: T0 = transducers.CountSubblockOccurrences([0, 0], [0, 1, 2]) sage: T1 = transducers.CountSubblockOccurrences([1, 1], [0, 1, 2]) sage: T2 = transducers.CountSubblockOccurrences([2, 2], [0, 1, 2]) sage: T = T0.cartesian_product([T1, T2]) sage: T.transitions() [Transition from ((), (), ()) to ((0,), (), ()): 0|(0, 0, 0), Transition from ((), (), ()) to ((), (1,), ()): 1|(0, 0, 0), Transition from ((), (), ()) to ((), (), (2,)): 2|(0, 0, 0), Transition from ((0,), (), ()) to ((0,), (), ()): 0|(1, 0, 0), Transition from ((0,), (), ()) to ((), (1,), ()): 1|(0, 0, 0), Transition from ((0,), (), ()) to ((), (), (2,)): 2|(0, 0, 0), Transition from ((), (1,), ()) to ((0,), (), ()): 0|(0, 0, 0), Transition from ((), (1,), ()) to ((), (1,), ()): 1|(0, 1, 0), Transition from ((), (1,), ()) to ((), (), (2,)): 2|(0, 0, 0), Transition from ((), (), (2,)) to ((0,), (), ()): 0|(0, 0, 0), Transition from ((), (), (2,)) to ((), (1,), ()): 1|(0, 0, 0), Transition from ((), (), (2,)) to ((), (), (2,)): 2|(0, 0, 1)] sage: T([0, 0, 1, 1, 2, 2, 0, 1, 2, 2]) [(0, 0, 0), (1, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 0), (0, 0, 1), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 1)] """ if FSMOldCodeTransducerCartesianProduct: from sage.misc.superseded import deprecation deprecation(16061, "The output of Transducer.cartesian_product " "will change. Please use " "Transducer.intersection for the original " "output.") return self.intersection( other, only_accessible_components=only_accessible_components) return self.product_FiniteStateMachine( other, function, final_function=final_function, only_accessible_components=only_accessible_components) def simplification(self): """ Returns a simplified transducer. INPUT: Nothing. OUTPUT: A new transducer. This function simplifies a transducer by Moore's algorithm, first moving common output labels of transitions leaving a state to output labels of transitions entering the state (cf. :meth:`.prepone_output`). The resulting transducer implements the same function as the original transducer. EXAMPLES:: sage: fsm = Transducer([("A", "B", 0, 1), ("A", "B", 1, 0), ....: ("B", "C", 0, 0), ("B", "C", 1, 1), ....: ("C", "D", 0, 1), ("C", "D", 1, 0), ....: ("D", "A", 0, 0), ("D", "A", 1, 1)]) sage: fsms = fsm.simplification() sage: fsms Transducer with 2 states sage: fsms.transitions() [Transition from ('A', 'C') to ('B', 'D'): 0|1, Transition from ('A', 'C') to ('B', 'D'): 1|0, Transition from ('B', 'D') to ('A', 'C'): 0|0, Transition from ('B', 'D') to ('A', 'C'): 1|1] sage: fsms.relabeled().transitions() [Transition from 0 to 1: 0|1, Transition from 0 to 1: 1|0, Transition from 1 to 0: 0|0, Transition from 1 to 0: 1|1] :: sage: fsm = Transducer([("A", "A", 0, 0), ....: ("A", "B", 1, 1), ....: ("A", "C", 1, -1), ....: ("B", "A", 2, 0), ....: ("C", "A", 2, 0)]) sage: fsm_simplified = fsm.simplification() sage: fsm_simplified Transducer with 2 states sage: fsm_simplified.transitions() [Transition from ('A',) to ('A',): 0|0, Transition from ('A',) to ('B', 'C'): 1|1,0, Transition from ('A',) to ('B', 'C'): 1|-1,0, Transition from ('B', 'C') to ('A',): 2|-] :: sage: from sage.combinat.finite_state_machine import duplicate_transition_add_input sage: T = Transducer([('A', 'A', 1/2, 0), ....: ('A', 'B', 1/4, 1), ....: ('A', 'C', 1/4, 1), ....: ('B', 'A', 1, 0), ....: ('C', 'A', 1, 0)], ....: initial_states=[0], ....: final_states=['A', 'B', 'C'], ....: on_duplicate_transition=duplicate_transition_add_input) sage: sorted(T.simplification().transitions()) [Transition from ('A',) to ('A',): 1/2|0, Transition from ('A',) to ('B', 'C'): 1/2|1, Transition from ('B', 'C') to ('A',): 1|0] Illustrating the use of colors in order to avoid identification of states:: sage: T = Transducer( [[0,0,0,0], [0,1,1,1], ....: [1,0,0,0], [1,1,1,1]], ....: initial_states=[0], ....: final_states=[0,1]) sage: sorted(T.simplification().transitions()) [Transition from (0, 1) to (0, 1): 0|0, Transition from (0, 1) to (0, 1): 1|1] sage: T.state(0).color = 0 sage: T.state(0).color = 1 sage: sorted(T.simplification().transitions()) [Transition from (0,) to (0,): 0|0, Transition from (0,) to (1,): 1|1, Transition from (1,) to (0,): 0|0, Transition from (1,) to (1,): 1|1] """ fsm = deepcopy(self) fsm.prepone_output() return fsm.quotient(fsm.equivalence_classes()) def process(self, *args, **kwargs): """ .. WARNING:: The default output of this method is scheduled to change. This docstring describes the new default behaviour, which can already be achieved by setting ``FSMOldProcessOutput`` to ``False``. Returns whether the transducer accepts the input, the state where the computation stops and which output is generated. INPUT: - ``input_tape`` -- The input tape can be a list with entries from the input alphabet. - ``initial_state`` -- (default: ``None``) The state in which to start. If this parameter is ``None`` and there is only one initial state in the machine, then this state is taken. - ``full_output`` -- (default: ``True``) If set, then the full output is given, otherwise only the generated output (the third entry below only). If the input is not accepted, a ``ValueError`` is raised. OUTPUT: The full output is a triple, where - the first entry is ``True`` if the input string is accepted, - the second gives the reached state after processing the input tape (This is a state with label ``None`` if the input could not be processed, i.e., when at one point no transition to go could be found.), and - the third gives a list of the output labels used during processing. By setting ``FSMOldProcessOutput`` to ``False`` the new desired output is produced. EXAMPLES:: sage: sage.combinat.finite_state_machine.FSMOldProcessOutput = False # activate new output behavior sage: from sage.combinat.finite_state_machine import FSMState sage: A = FSMState('A', is_initial = True, is_final = True) sage: binary_inverter = Transducer({A:[(A, 0, 1), (A, 1, 0)]}) sage: binary_inverter.process([0, 1, 0, 0, 1, 1]) (True, 'A', [1, 0, 1, 1, 0, 0]) If we are only interested in the output, we can also use:: sage: binary_inverter([0, 1, 0, 0, 1, 1]) [1, 0, 1, 1, 0, 0] The following transducer transforms `0^n 1` to `1^n 2`:: sage: T = Transducer([(0, 0, 0, 1), (0, 1, 1, 2)]) sage: T.state(0).is_initial = True sage: T.state(1).is_final = True We can see the different possibilites of the output by:: sage: [T.process(w) for w in [[1], [0, 1], [0, 0, 1], [0, 1, 1], ....: [0], [0, 0], [2, 0], [0, 1, 2]]] [(True, 1, [2]), (True, 1, [1, 2]), (True, 1, [1, 1, 2]), (False, None, None), (False, 0, [1]), (False, 0, [1, 1]), (False, None, None), (False, None, None)] If we just want a condensed output, we use:: sage: [T.process(w, full_output=False) ....: for w in [[1], [0, 1], [0, 0, 1]]] [[2], [1, 2], [1, 1, 2]] sage: T.process([0, 1, 2], full_output=False) Traceback (most recent call last): ... ValueError: Invalid input sequence. It is equivalent to:: sage: [T(w) for w in [[1], [0, 1], [0, 0, 1]]] [[2], [1, 2], [1, 1, 2]] sage: T([0, 1, 2]) Traceback (most recent call last): ... ValueError: Invalid input sequence. """ if FSMOldProcessOutput: from sage.misc.superseded import deprecation deprecation(16132, "The output of Transducer.process " "(and thus of Transducer.__call__) " "will change. Please use the corresponding " "functions from FiniteStateMachine " "for the original output.") return super(Transducer, self).process(*args, **kwargs) if not kwargs.has_key('full_output'): kwargs['full_output'] = True it = self.iter_process(*args, **kwargs) for _ in it: pass # process output if kwargs['full_output']: if it.current_state.label() is None: return (it.accept_input, it.current_state, None) else: return (it.accept_input, it.current_state, it.output_tape) else: if not it.accept_input: raise ValueError("Invalid input sequence.") return it.output_tape #***************************************************************************** def is_FSMProcessIterator(PI): """ Tests whether or not ``PI`` inherits from :class:`FSMProcessIterator`. TESTS:: sage: from sage.combinat.finite_state_machine import is_FSMProcessIterator, FSMProcessIterator sage: is_FSMProcessIterator(FSMProcessIterator(FiniteStateMachine([[0, 0, 0, 0]], initial_states=[0]))) True """ return isinstance(PI, FSMProcessIterator) class FSMProcessIterator(SageObject): """ This class is for processing an input string on a finite state machine. An instance of this class is generated when :meth:`FiniteStateMachine.process` or :meth:`FiniteStateMachine.iter_process` of the finite state machine is invoked. It behaves like an iterator which, in each step, takes one letter of the input and runs (one step on) the finite state machine with this input. More precisely, in each step, the process iterator takes an outgoing transition of the current state, whose input label equals the input letter of the tape. The output label of the transition, if present, is written on the output tape. INPUT: - ``fsm`` -- The finite state machine on which the input should be processed. - ``input_tape`` -- The input tape. It can be anything that is iterable. - ``initial_state`` -- The initial state in which the machine starts. If this is ``None``, the unique inital state of the finite state machine is takes. If there are several, a ``ValueError`` is raised. The process (iteration) stops if there are no more input letters on the tape. In this case a StopIteration exception is thrown. As result the following attributes are available: - ``accept_input`` -- Is ``True`` if the reached state is a final state. - ``current_state`` -- The current/reached state in the process. - ``output_tape`` -- The written output. Current values of those attributes (except ``accept_input``) are (also) available during the iteration. OUTPUT: An iterator. EXAMPLES: The following transducer reads binary words and outputs a word, where blocks of ones are replaced by just a single one. Further only words that end with a zero are accepted. :: sage: T = Transducer({'A': [('A', 0, 0), ('B', 1, None)], ....: 'B': [('B', 1, None), ('A', 0, [1, 0])]}, ....: initial_states=['A'], final_states=['A']) sage: input = [1, 1, 0, 0, 1, 0, 1, 1, 1, 0] sage: T.process(input) (True, 'A', [1, 0, 0, 1, 0, 1, 0]) The function :meth:`FiniteStateMachine.process` created a new ``FSMProcessIterator``. We can do that manually, too, and get full access to the iteration process:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: it = FSMProcessIterator(T, input_tape=input) sage: for _ in it: ....: print (it.current_state, it.output_tape) ('B', []) ('B', []) ('A', [1, 0]) ('A', [1, 0, 0]) ('B', [1, 0, 0]) ('A', [1, 0, 0, 1, 0]) ('B', [1, 0, 0, 1, 0]) ('B', [1, 0, 0, 1, 0]) ('B', [1, 0, 0, 1, 0]) ('A', [1, 0, 0, 1, 0, 1, 0]) sage: it.accept_input True TESTS:: sage: T = Transducer([[0, 0, 0, 0]]) sage: T.process([]) Traceback (most recent call last): ... ValueError: No state is initial. :: sage: T = Transducer([[0, 1, 0, 0]], initial_states=[0, 1]) sage: T.process([]) Traceback (most recent call last): ... ValueError: Several initial states. """ def __init__(self, fsm, input_tape=None, initial_state=None, **kwargs): """ See :class:`FSMProcessIterator` for more information. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: for _ in it: ....: pass sage: it.output_tape [1, 0] """ self.fsm = fsm if initial_state is None: fsm_initial_states = self.fsm.initial_states() try: self.current_state = fsm_initial_states[0] except IndexError: raise ValueError("No state is initial.") if len(fsm_initial_states) > 1: raise ValueError("Several initial states.") else: self.current_state = initial_state self.output_tape = [] if input_tape is None: self._input_tape_iter_ = iter([]) else: if hasattr(input_tape, '__iter__'): self._input_tape_iter_ = iter(input_tape) else: raise ValueError("Given input tape is not iterable.") def __iter__(self): """ Returns ``self``. TESTS:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: id(it) == id(iter(it)) True """ return self def next(self): """ Makes one step in processing the input tape. INPUT: Nothing. OUTPUT: It returns the taken transition. A ``StopIteration`` exception is thrown when there is nothing more to read. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: it.next() Transition from 'A' to 'A': 0|1 sage: it.next() Transition from 'A' to 'A': 1|0 sage: it.next() Traceback (most recent call last): ... StopIteration TESTS:: sage: Z = Transducer() sage: s = Z.add_state(0) sage: s.is_initial = True sage: s.is_final = True sage: s.final_word_out = [1, 2] sage: Z.process([]) (True, 0, [1, 2]) """ if hasattr(self, 'accept_input'): raise StopIteration try: # process current state transition = None try: transition = self.current_state.hook( self.current_state, self) except AttributeError: pass self.write_word(self.current_state.word_out) # get next if not isinstance(transition, FSMTransition): next_word = [] found = False try: while not found: next_word.append(self.read_letter()) if len(next_word) == 1 and any(not t.word_in for t in self.current_state.transitions): raise NotImplementedError( "process cannot handle epsilon transition " "leaving state %s." % self.current_state.label()) try: transition = self.get_next_transition( next_word) found = True except ValueError: pass if found and any( t is not transition and startswith(t.word_in, next_word) for t in self.current_state.transitions): raise NotImplementedError("Non-deterministic " "path encountered " "when processing " "input.") except StopIteration: # this means input tape is finished if len(next_word) > 0: self.current_state = FSMState(None, allow_label_None=True) raise StopIteration # process transition try: transition.hook(transition, self) except AttributeError: pass self.write_word(transition.word_out) # go to next state self.current_state = transition.to_state except StopIteration: # this means, either input tape is finished or # someone has thrown StopIteration manually (in one # of the hooks) if self.current_state.label is None or not self.current_state.is_final: self.accept_input = False if not hasattr(self, 'accept_input'): self.accept_input = True if self.current_state.is_final: self.write_word(self.current_state.final_word_out) raise StopIteration # return return transition def read_letter(self): """ Reads a letter from the input tape. INPUT: Nothing. OUTPUT: A letter. Exception ``StopIteration`` is thrown if tape has reached the end. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: it.read_letter() 0 """ return self._input_tape_iter_.next() def write_letter(self, letter): """ Writes a letter on the output tape. INPUT: - ``letter`` -- the letter to be written. OUTPUT: Nothing. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: it.write_letter(42) sage: it.output_tape [42] """ self.output_tape.append(letter) def write_word(self, word): """ Writes a word on the output tape. INPUT: - ``word`` -- the word to be written. OUTPUT: Nothing. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: it.write_word([4, 2]) sage: it.output_tape [4, 2] """ for letter in word: self.write_letter(letter) def get_next_transition(self, word_in): """ Returns the next transition according to ``word_in``. It is assumed that we are in state ``self.current_state``. INPUT: - ``word_in`` -- the input word. OUTPUT: The next transition according to ``word_in``. It is assumed that we are in state ``self.current_state``. If no transition matches, a ``ValueError`` is thrown. EXAMPLES:: sage: from sage.combinat.finite_state_machine import FSMProcessIterator sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]}, ....: initial_states=['A'], final_states=['A']) sage: it = FSMProcessIterator(inverter, input_tape=[0, 1]) sage: it.get_next_transition([0]) Transition from 'A' to 'A': 0|1 sage: it.get_next_transition([2]) Traceback (most recent call last): ... ValueError: No transition with input [2] found. """ for transition in self.current_state.transitions: if transition.word_in == word_in: return transition raise ValueError("No transition with input %s found." % (word_in,)) #***************************************************************************** @cached_function def setup_latex_preamble(): r""" This function adds the package ``tikz`` with support for automata to the preamble of Latex so that the finite state machines can be drawn nicely. INPUT: Nothing. OUTPUT: Nothing. See the section on :ref:`finite_state_machine_LaTeX_output` in the introductory examples of this module. TESTS:: sage: from sage.combinat.finite_state_machine import setup_latex_preamble sage: setup_latex_preamble() sage: ("\usepackage{tikz}" in latex.extra_preamble()) == latex.has_file("tikz.sty") True """ latex.add_package_to_preamble_if_available('tikz') latex.add_to_mathjax_avoid_list("tikz") if latex.has_file("tikz.sty"): latex.add_to_preamble(r'\usetikzlibrary{automata}') #*****************************************************************************
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 81, 37811, 198, 37, 9504, 1812, 31182, 11, 17406, 1045, 11, 3602, 41213, 198, 198, 1212, 8265, 6673, 1104, 329, 27454, 1181, 8217, 11, 3557, 1045, 290, 198, 7645, 41213,...
2.051147
168,787
import json import os import boto3 import secrets import time def lambda_handler(event, context): """ Sends an email notification to user with MAL OAuth link. Args: event (dict): AWS triggering event context (dict): AWS context Returns: (dict): JSON response to triggering event """ try: user = event['user'] except KeyError as e: print(e) return create_response(400, "Need to provide user to email.") # Fetch config file s3 = boto3.client('s3') bucket = 'anilist-to-mal-config' key = 'config.json' try: data = s3.get_object(Bucket=bucket, Key=key) config = json.loads(data['Body'].read()) except (s3.exceptions.NoSuchKey, s3.exceptions.InvalidObjectState) as e: print(e) return create_response(500, "The server failed to fetch config.") except JSONDecodeError as e: print(e) return create_response(500, "The config file could not be decoded.") try: user_email = config['users'][user]['email'] except KeyError as e: print(e) return create_response(404, "Could not find user email in config.") mal_id = config['MAL_CLIENT_ID'] mal_secret = config['MAL_CLIENT_SECRET'] # Generate and send email ses = boto3.client('ses', region_name=os.environ['AWS_REGION']) code_challenge = secrets.token_urlsafe(100)[:128] auth_url = f"https://myanimelist.net/v1/oauth2/authorize?response_type=code&client_id={mal_id}&code_challenge={code_challenge}&state={user}" print(f"Code Challenge for {user}: {code_challenge}") try: ses.send_email( Destination={ 'ToAddresses': [user_email] }, Message={ 'Body': { 'Text': { 'Charset': 'UTF-8', 'Data': f"Click this link to authorize Anilist-to-MAL-sync to be able to update your MAL: {auth_url}" } }, 'Subject': { 'Charset': 'UTF-8', 'Data': "Anilist-to-MAL-Sync Authorization" } }, Source='defcoding@gmail.com' ) except ses.exceptions.MessageRejected as e: print(e) return create_response(500, "Could not send notification email.") config['users'][user]['code_verifier'] = code_challenge config['users'][user]['last_notified'] = int(time.time()) config['users'][user]['auth_failed'] = False s3.put_object(Body=json.dumps(config), Bucket=bucket, Key=key) return create_response(200, "Email successfully sent!") def create_response(code: int, body: str) -> dict: """ Creates a JSON response for HTTP. Args: code (int): The HTTP status code body (str): The HTTP body as a string Returns: (dict): JSON HTTP response """ return { 'headers': { 'Content-Type': 'text/html' }, 'statusCode': code, 'body': body }
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 275, 2069, 18, 198, 11748, 13141, 198, 11748, 640, 198, 198, 4299, 37456, 62, 30281, 7, 15596, 11, 4732, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 311, 2412, 281, 3053, 14483, 28...
2.103811
1,522
# -*- coding: utf-8 -*- from datetime import datetime import ruamel.yaml
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 7422, 17983, 13, 88, 43695, 628, 628 ]
2.566667
30
from flask import Blueprint, render_template, url_for, request, redirect from werkzeug.security import generate_password_hash from .models import User from . import db auth = Blueprint('auth', __name__) @auth.route('/signup') @auth.route('/signup', methods=['POST']) @ auth.route('/login') @ auth.route('/login', methods=['POST']) @ auth.route('/logout')
[ 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 11, 19016, 62, 1640, 11, 2581, 11, 18941, 198, 6738, 266, 9587, 2736, 1018, 13, 12961, 1330, 7716, 62, 28712, 62, 17831, 198, 6738, 764, 27530, 1330, 11787, 198, 6738, 764, 1330, 20613, 1...
3.07563
119
from interlib.utility import key_var_check from interlib.utility import print_line from interlib.utility import inter_data_type from interlib.utility import list_dict_checker help_manual = " Syntax: \n" \ " Set <variable_name> [equal] to (<variable>/<number>/<string>/<list>/<table>) \n" \ " \n" \ " Examples: \n" \ " Set x to \"Hello World\" \n" \ " Set y equal to 1232 \n" \ " Set z to [1, 3 , 4, \"hmm\"] \n" \ " Set recipe to {\"Milk\" : \"2 lbs\", \"Crackers\" : \"Handful\"} \n" ''' Set keyword: used as a more advanced create option Requires: . line_numb = The line number we are looking at in the Psudo code file . line_list = The line we took from the Psudo code file, but in list format . all_variables = The dictionary that contains all of the variables for that Psudo code file . indent = The indentation to correctly format the line of python code . py_lines = The python code that we will append our finalized parsed code to it Returns: . A boolean value. This is used in the interpreter.py file to make sure that the parsing of the code executes correctly. Otherwise the parsing stops and ends it prematurely. '''
[ 6738, 987, 8019, 13, 315, 879, 1330, 1994, 62, 7785, 62, 9122, 198, 6738, 987, 8019, 13, 315, 879, 1330, 3601, 62, 1370, 198, 6738, 987, 8019, 13, 315, 879, 1330, 987, 62, 7890, 62, 4906, 198, 6738, 987, 8019, 13, 315, 879, 1330, ...
2.811236
445
import json try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request
[ 11748, 33918, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 11, 19390, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 422, 2956, 297, 571, 17, 1330, 19016, 9654, 11, 19390, 198 ]
3.097561
41
''' >>> heap = BikeHeap([4, 2, 1, 3]) >>> heap.pop() 1 >>> heap.pop() 2 ''' import heapq if __name__ == '__main__': import doctest print(doctest.testmod())
[ 7061, 6, 198, 33409, 24575, 796, 26397, 1544, 499, 26933, 19, 11, 362, 11, 352, 11, 513, 12962, 198, 33409, 24575, 13, 12924, 3419, 198, 16, 198, 33409, 24575, 13, 12924, 3419, 198, 17, 198, 7061, 6, 198, 198, 11748, 24575, 80, 628,...
2.210526
76
#!/usr/bin/env python import os from setuptools import setup, find_packages version = __import__('philo').VERSION setup( name = 'philo', version = '.'.join([str(v) for v in version]), url = "http://philocms.org/", description = "A foundation for developing web content management systems.", long_description = open(os.path.join(os.path.dirname(__file__), 'README')).read(), maintainer = "iThink Software", maintainer_email = "contact@ithinksw.com", packages = find_packages(), classifiers = [ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], platforms = ['OS Independent'], license = 'ISC License (ISCL)', install_requires = [ 'django>=1.3', 'django-mptt>0.4.2,==dev', ], extras_require = { 'docs': ["sphinx>=1.0"], 'grappelli': ['django-grappelli>=2.3'], 'migrations': ['south>=0.7.2'], 'waldo-recaptcha': ['recaptcha-django'], 'sobol-eventlet': ['eventlet'], 'sobol-scrape': ['BeautifulSoup'], 'penfield': ['django-taggit>=0.9'], }, dependency_links = [ 'https://github.com/django-mptt/django-mptt/tarball/master#egg=django-mptt-dev' ] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 628, 198, 9641, 796, 11593, 11748, 834, 10786, 746, 18526, 27691, 43717, 628, 198, 40406, 7, 198, ...
2.615385
533
from winning.lattice_plot import densitiesPlot from winning.lattice import skew_normal_density, mean_of_density, implicit_state_prices, winner_of_many, sample_winner_of_many from winning.lattice_calibration import solve_for_implied_offsets, state_prices_from_offsets, densities_from_offsets import numpy as np PLOTS=True import math unit = 0.05 L = 500 if __name__=='__main__': demo()
[ 6738, 5442, 13, 75, 1078, 501, 62, 29487, 1330, 220, 29509, 871, 43328, 198, 6738, 5442, 13, 75, 1078, 501, 1330, 43370, 62, 11265, 62, 43337, 11, 1612, 62, 1659, 62, 43337, 11, 16992, 62, 5219, 62, 1050, 1063, 11, 8464, 62, 1659, ...
2.882353
136
# A set of Python commands to pre-run for the galpy.org/repl redirect # Install astroquery import micropip await micropip.install('astroquery') # Install galpy await micropip.install('https://www.galpy.org/wheelhouse/galpy-latest-py3-none-any.whl') # Turn off warnings import warnings from galpy.util import galpyWarning warnings.simplefilter(action='ignore',category=galpyWarning) # Import units from astropy to have them handy from astropy import units import astropy.units as u # Set up galpy to return outputs as astropy Quantities import galpy.util.conversion galpy.util.conversion._APY_UNITS=True # Also need to set the following, because pyodide SkyCoord failure prevents this from being set correctly in Orbits import galpy.orbit.Orbits galpy.orbit.Orbits._APY_LOADED= True # Inline plots %matplotlib inline
[ 2, 317, 900, 286, 11361, 9729, 284, 662, 12, 5143, 329, 262, 9426, 9078, 13, 2398, 14, 35666, 18941, 198, 2, 15545, 6468, 305, 22766, 198, 11748, 12314, 1773, 541, 198, 707, 4548, 12314, 1773, 541, 13, 17350, 10786, 459, 305, 22766, ...
3.317073
246
from fishfeeder import FishFeeder import firebase url = "{your firebase url}" while True: result = firebase.get(url) if (result['action'] == True): FishFeeder().FeedNow(0, 90) firebase.put(url, {'action': False})
[ 6738, 5916, 12363, 263, 1330, 13388, 18332, 263, 198, 198, 11748, 2046, 8692, 198, 198, 6371, 796, 45144, 14108, 2046, 8692, 19016, 36786, 198, 198, 4514, 6407, 25, 198, 220, 220, 220, 1255, 796, 2046, 8692, 13, 1136, 7, 6371, 8, 628,...
2.553191
94
from __future__ import division import unittest import numpy as np from numpy import testing as np_testing from pax.plugins.peak_processing.BasicProperties import integrate_until_fraction, put_w_in_center_of_field if __name__ == '__main__': unittest.main()
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 555, 715, 395, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 1330, 4856, 355, 45941, 62, 33407, 198, 198, 6738, 279, 897, 13, 37390, 13, 36729, 62, 36948, 13, 26416, 2964, ...
3.117647
85
import time import pytest from pyprofile import profile @pytest.fixture def test_profile_decorator(dump_dir): """Only test if the profile decorator is written correctly. """ @profile(dump_dir=dump_dir) @profile() assert fn() == 2, "fn with no parameters failed." assert fn_with_parameters(5) == 5, "fn with parameters failed."
[ 11748, 640, 198, 198, 11748, 12972, 9288, 198, 6738, 12972, 13317, 1330, 7034, 628, 198, 31, 9078, 9288, 13, 69, 9602, 628, 198, 4299, 1332, 62, 13317, 62, 12501, 273, 1352, 7, 39455, 62, 15908, 2599, 198, 220, 220, 220, 37227, 10049,...
2.991667
120
"""Externalized strings for better structure and easier localization""" setup_greeting = """ Dwarf - First run configuration Insert your bot's token, or enter 'cancel' to cancel the setup:""" not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process." choose_prefix = """Choose a prefix. A prefix is what you type before a command. A typical prefix would be the exclamation mark. Can be multiple characters. You will be able to change it later and add more of them. Choose your prefix:""" confirm_prefix = """Are you sure you want {0} as your prefix? You will be able to issue commands like this: {0}help Type yes to confirm or no to change it""" setup_finished = """ The configuration is done. Leave this window always open to keep your bot online. All commands will have to be issued through Discord's chat, *this window will now be read only*. Press enter to continue""" prefix_singular = "Prefix" prefix_plural = "Prefixes" use_this_url = "Use this url to bring your bot to a server:" bot_is_online = "{} is now online." connected_to = "Connected to:" connected_to_servers = "{} servers" connected_to_channels = "{} channels" connected_to_users = "{} users" no_prefix_set = "No prefix set. Defaulting to !" logging_into_discord = "Logging into Discord..." invalid_credentials = """Invalid login credentials. If they worked before Discord might be having temporary technical issues. In this case, press enter and try again later. Otherwise you can type 'reset' to delete the current configuration and redo the setup process again the next start. > """ keep_updated_win = """Make sure to keep your bot updated by running the file update.bat""" keep_updated = """Make sure to keep Dwarf updated by using:\n git pull\npip3 install --upgrade git+https://github.com/Rapptz/discord.py@async""" official_server = "Official server: {}" invite_link = "https://discord.me/AileenLumina" update_the_api = """\nYou are using an outdated discord.py.\n Update your discord.py with by running this in your cmd prompt/terminal:\npip3 install --upgrade git+https:// github.com/Rapptz/discord.py@async""" command_disabled = "That command is disabled." exception_in_command = "Exception in command '{}'" error_in_command = "Error in command '{}' - {}: {}" not_available_in_dm = "That command is not available in DMs." owner_recognized = "{} has been recognized and set as owner."
[ 37811, 41506, 1143, 13042, 329, 1365, 4645, 290, 4577, 42842, 37811, 628, 198, 40406, 62, 70, 2871, 278, 796, 37227, 198, 35, 5767, 69, 532, 3274, 1057, 8398, 198, 198, 44402, 534, 10214, 338, 11241, 11, 393, 3802, 705, 66, 21130, 6, ...
3.140373
805
# pylint: disable=redefined-outer-name import collections import functools import itertools import pytest import slash from slash.core.scope_manager import ScopeManager, get_current_scope from .utils import make_runnable_tests from .utils.suite_writer import Suite def test_requirement_mismatch_end_of_module(): """Test that unmet requirements at end of file(module) still enable scope manager to detect the end and properly pop contextx""" suite = Suite() num_files = 3 num_tests_per_file = 5 for i in range(num_files): # pylint: disable=unused-variable file1 = suite.add_file() for j in range(num_tests_per_file): # pylint: disable=unused-variable file1.add_function_test() t = file1.add_function_test() t.add_decorator('slash.requires(lambda: False)') t.expect_skip() suite.run() @pytest.fixture @pytest.fixture @pytest.fixture
[ 2, 279, 2645, 600, 25, 15560, 28, 445, 18156, 12, 39605, 12, 3672, 198, 11748, 17268, 198, 11748, 1257, 310, 10141, 198, 11748, 340, 861, 10141, 198, 198, 11748, 12972, 9288, 198, 11748, 24632, 198, 6738, 24632, 13, 7295, 13, 29982, 6...
2.689855
345
from __future__ import print_function import fns import numpy as np import os import matplotlib.pyplot as plt import matplotlib import scipy.signal from scipy import signal #from sklearn.model_selection import LeavePOut #from sklearn.model_selection import KFold from sklearn.model_selection import ShuffleSplit from sklearn.model_selection import LeaveOneOut from sklearn.linear_model import ElasticNet import sklearn.metrics import types from math import sqrt import copy import sys import importlib from .libs import PLSRsave from .libs import PLSRGeneticAlgorithm from .libs import PLSRNN from .libs import PLSRRNN from .libs import PLSRCNN from .libs import PLSR_file_import from .libs import PLSRregressionMethods from .libs import PLSRregressionVisualization from .libs import PLSRpreprocessing from .libs import PLSRwavelengthSelection from .libs import PLSRsequential_feature_selectors from .libs import PLSRclassifiers #### this '''functions_to_wrap = [[matplotlib.axes.Axes,'pcolormesh'], [matplotlib.figure.Figure,'colorbar'], [matplotlib.figure.Figure,'clf'], [matplotlib.figure.Figure,'set_size_inches'], [matplotlib.figure.Figure,'add_subplot'], [matplotlib.figure.Figure,'subplots'], [matplotlib.figure.Figure,'subplots_adjust'], [matplotlib.axes.Axes,'invert_yaxis'], [matplotlib.axes.Axes,'invert_xaxis'], [matplotlib.axes.Axes,'set_title'], [matplotlib.axes.Axes,'axis'], [matplotlib.axes.Axes,'cla'], [matplotlib.axes.Axes,'plot'], [matplotlib.figure.Figure,'savefig'], [matplotlib.axes.Axes,'set_xlim'], [matplotlib.axes.Axes,'set_position'], [matplotlib.axes.Axes,'bar'], [matplotlib.figure.Figure,'add_axes'], [plt,'figure'], ] for function in functions_to_wrap: if not 'function rimt.<locals>.rimt_this' in str(getattr(function[0], function[1])): setattr(function[0], function[1], fns.rimt(getattr(function[0], function[1])))''' #from multiprocessing import Pool #import datetime #matplotlib.rc('text', usetex=True) #matplotlib.rc('text.latex', preamble=r'\usepackage{upgreek}') def set_training(event): """Sets the training data set(s) in the GUI.""" frame=event.widget.master.master.master frame.nav.clear_color('color1') frame.nav.color_selected('color1') frame.training_files=frame.nav.get_paths_of_selected_items() frame.nav.deselect() return def set_validation(event): """Sets the validation data set(s) in the GUI.""" frame=event.widget.master.master.master frame.nav.clear_color('color3') frame.nav.color_selected('color3') frame.validation_files=frame.nav.get_paths_of_selected_items() frame.nav.deselect() return
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 277, 5907, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 198, 11748, 629, 5...
2.235207
1,352
#!python """Check if docker container is running""" import argparse import subprocess import re import nagiosplugin @nagiosplugin.guarded if __name__ == '__main__': main()
[ 2, 0, 29412, 198, 198, 37811, 9787, 611, 36253, 9290, 318, 2491, 37811, 198, 198, 11748, 1822, 29572, 198, 11748, 850, 14681, 198, 11748, 302, 198, 198, 11748, 299, 363, 4267, 33803, 628, 628, 198, 31, 77, 363, 4267, 33803, 13, 5162, ...
3
62
import pymongo import json import numpy import plotly.graph_objs as go from datetime import datetime,timedelta import plotly import os from fedn.common.storage.db.mongo import connect_to_mongodb
[ 11748, 279, 4948, 25162, 198, 11748, 33918, 198, 11748, 299, 32152, 198, 11748, 7110, 306, 13, 34960, 62, 672, 8457, 355, 467, 198, 6738, 4818, 8079, 1330, 4818, 8079, 11, 16514, 276, 12514, 198, 11748, 7110, 306, 198, 11748, 28686, 198...
3.145161
62
# -*- coding: utf-8 -*- """ Created on Wed Jul 29 07:57:54 2020 @author: papalk """ # Code logbook # 10.02.2021 - Handover from Alkistis # changed filename to filename[0] due to variable type error # Changing from df.ix[...,0] to df.loc[..., df.columns[0]] due to a newer pandas version import sys import datetime as dt import matplotlib.pyplot as plt import matplotlib.pylab as pylab from matplotlib.dates import DateFormatter from matplotlib.ticker import StrMethodFormatter import pandas as pd import numpy as np import xarray as xr from mpl_toolkits.mplot3d import Axes3D import glob # import user modules usermodPath = r'../../userModules' sys.path.append(usermodPath) import pythonAssist from pythonAssist import * plt.style.use('seaborn-whitegrid') SMALL_SIZE = 17 MEDIUM_SIZE = 22 BIGGER_SIZE = 22 AppendLog=1 plt.rc('font', size=SMALL_SIZE,weight = 'bold') # controls default text sizes plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title plt.rc('figure', figsize = (8, 8)) #%% Import data dt_start ='2021-10-22 00:00:00' # Select start date in the form yyyy-mm-dd_HH-MM-SS dt_end = dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S') + dt.timedelta(days=7)# Select end date in the form yyyy-mm-dd_HH-MM-SS dt_end = dt_end.strftime('%Y-%m-%d %H:%M:%S') # Import csv path = r'Z:\Projekte\109797-TestfeldBHV\30_Technical_execution_Confidential\TP3\AP2_Aufbau_Infrastruktur\Infrastruktur_Windmessung\02_Equipment\02_iSpin\Data\10min_Data' filename = glob.glob(path+'\Bremerhaven WTG01*.csv') df=pd.read_csv(filename[0], sep = ';',decimal = ',',header=0) df['TimeStamp'] = [dt.datetime.strptime(date, '%Y-%m-%d %H:%M:%S') for date in df['TimeStamp']] ## Filtering conditions cond0 = df['WS_free_avg'].notnull() # non-zero values cond1 = (df["TimeStamp"]>=dt_start)&(df["TimeStamp"]<dt_end) # time interval filtering cond2 = (df["SaDataValid"]==True) # 95% availability of 10 Hz data, wind vector +-90° in front of turbine within 10 min cond3 = (df["DataOK"]==True) # data.TotalCountNoRotation=0, 95% availability, min & max rotor rpm, avg rotor rpm, free wind speed > 3.5 m/s, sample ID!= 0 cond4 = (df['WS_free_avg'] > 0) & (df['WS_free_avg'] < 50) # wind speed physical limits ## extra parameters for logbook # no. of pts during the last week Npts = df.loc[(cond0 & cond1),:].shape[0] Nvalid = df.loc[(cond0 & cond1 & cond2),:].shape[0] Nws_valid = df.loc[(cond0 & cond1 & cond2),df.columns.values[1]].shape[0] Nwt_valid = df.loc[(cond0 & cond1 & cond2 & cond3),:].shape[0] Nyaw_valid = df.loc[(cond0 & cond1 & cond3),:].shape[0] # filling in the weekly availabiliy as 1/0 based on number of points weekly_avail = [] import more_itertools step= 144 length = 144 idx = cond1[cond1==True].index N_win = np.int64(len(df.loc[cond1,'WS_free_avg'])/step) window = np.transpose(list(more_itertools.windowed(df.loc[cond1,'WS_free_avg'], n=length, fillvalue=np.nan, step=step))) condn = np.transpose(list(more_itertools.windowed(np.array(cond0[idx] & cond1[idx] & cond2[idx] & cond4[idx]), n=length, fillvalue=np.nan, step=step))).astype(bool) for i in np.arange(N_win): daily_avail = window[condn[:,i],i].shape[0]/length if daily_avail >= 0.6: weekly_avail.append(1) else: weekly_avail.append(0) #%% Plots # Plot all # for i in range(len(df.columns)): # # date-ws_free_avg # fig = plt.figure(figsize = (20, 8)) # ax = fig.add_subplot(111) # ax.plot(df.loc[ cond1,df.columns[0]],df.loc[cond1,i],'.',color = 'gray',label = 'Invalid data'); # ax.plot(df.loc[ cond1&cond2,df.columns[0]],df.loc[cond1&cond2,i],'.',label = 'Valid data'); # ax.set_xlabel(df.columns[0],labelpad=40,weight= 'bold') # ax.set_ylabel(df.columns[i],labelpad=40,weight= 'bold') # date_form = DateFormatter("%d/%m") # ax.xaxis.set_major_formatter(date_form) # # ax.set_xlim([ dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S'), dt.datetime.strptime(dt_end, '%Y-%m-%d %H:%M:%S')]) # # ax.set_ylim([0,25]) # ax.legend() # # plt.savefig(r'Z:\Projekte\109797-TestfeldBHV\30_Technical_execution_Confidential\TP3\AP2_Aufbau_Infrastruktur\Infrastruktur_Windmessung\02_Equipment\02_iSpin\Data\QM\TS_' + path[155:165]+'_'+df.columns[i]+'.png',bbox_inches='tight') fig,ax = plt.subplots(4,1, figsize = (10, 10),sharex=True) ax[0].plot(df.loc[ cond1&cond2,df.columns[0]],df.loc[cond1&cond2,'WS_free_avg'],'.',label = 'Valid data'); ax[0].set_xlabel('date',labelpad=40,weight= 'bold') ax[0].set_ylabel("WS_free_avg [m/s]",labelpad=40,weight= 'bold') date_form = DateFormatter("%d/%m") ax[0].xaxis.set_major_formatter(date_form) ax[0].set_xlim([ dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S'), dt.datetime.strptime(dt_end, '%Y-%m-%d %H:%M:%S')]) ax[0].set_ylim([0,25]) ax[1].plot(df.loc[ cond1&cond2,df.columns[0]],df.loc[cond1&cond2,'YA_corr_avg'],'.',label = 'Valid data'); ax[1].set_xlabel('date',labelpad=40,weight= 'bold') ax[1].set_ylabel("YA_corr_avg [$^o$]",labelpad=40,weight= 'bold') date_form = DateFormatter("%d/%m") ax[1].xaxis.set_major_formatter(date_form) ax[1].set_xlim([ dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S'), dt.datetime.strptime(dt_end, '%Y-%m-%d %H:%M:%S')]) ax[1].set_ylim([-45,45]) ax[2].plot(df.loc[ cond1&cond2,df.columns[0]],df.loc[cond1&cond2,'ARS_avg'],'.',label = 'Valid data'); ax[2].set_xlabel('date',labelpad=40,weight= 'bold') ax[2].set_ylabel("ARS_avg [$^o$/s]",labelpad=40,weight= 'bold') date_form = DateFormatter("%d/%m") ax[2].xaxis.set_major_formatter(date_form) ax[2].set_xlim([ dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S'), dt.datetime.strptime(dt_end, '%Y-%m-%d %H:%M:%S')]) ax[2].set_ylim([0,55]) ax[3].plot(df.loc[ cond1,df.columns[0]],df.notnull().values[cond1,1]*100,'.',color = 'limegreen', label = 'Valid data'); ax[3].plot(df.loc[ cond1&(df.isnull().values[:,1]),df.columns[0]],df.notnull().values[cond1&(df.isnull().values[:,1]),1]*100,'.',color = 'red', label = 'invalid data'); ax[3].set_xlabel('date',labelpad=40,weight= 'bold') ax[3].set_ylabel("Availability [%]",labelpad=40,weight= 'bold') date_form = DateFormatter("%d/%m") ax[3].xaxis.set_major_formatter(date_form) ax[3].set_xlim([ dt.datetime.strptime(dt_start, '%Y-%m-%d %H:%M:%S'), dt.datetime.strptime(dt_end, '%Y-%m-%d %H:%M:%S')]) ax[3].set_ylim([-5,110]) plt.xlabel('date',labelpad=10,weight= 'bold') plt.subplots_adjust(wspace=0, hspace=0.1) plt.savefig(r'Z:\Projekte\109797-TestfeldBHV\30_Technical_execution_Confidential\TP3\AP2_Aufbau_Infrastruktur\Infrastruktur_Windmessung\02_Equipment\02_iSpin\Data\10min_Data\QM\\'+dt_start[0:10]+'_'+dt_end[0:10]+'.png', bbox_inches='tight',dpi = 100) plt.show() ## Append the quality check at the end of verification # extracting the worksheet import openpyxl as opl xl_filepath = r'z:\Projekte\109797-TestfeldBHV\30_Technical_execution_Confidential\TP3\AP2_Aufbau_Infrastruktur\Infrastruktur_Windmessung\02_Equipment\02_iSpin\Documentation\Logbook_iSpin.xlsx' wb = opl.load_workbook(xl_filepath) # grab the active worksheet ws = wb['Datenabholung'] # grab the workshet title ws_title = ws.title print('[{}] - Active sheet title: {} \n'.format(now(), ws_title)) # appending the worksheet Str = '{} - {}'.format(dt_start[0:10], dt_end[0:10]) purpose = ('{}'.format(input('Please enter purpose: 0-Überwachung/Observation, 1-Datenabholung (default): '))) if purpose == '0': pStr = 'Überwachung' elif purpose == '1': pStr = 'Datenabholung' else: pStr = 'Datenabholung' print('[{}] - Input not in the list! Assumed purpose= {} \n'.format(now(), pStr)) test_Data = ('Data {}'.format(input('Please enter OK or not OK plus any comments:'))) appData = [today(), pStr, Str, test_Data,Npts,Nvalid,Nws_valid, Nwt_valid, Nyaw_valid] appData.extend(np.transpose(weekly_avail)) # target = wb.copy_worksheet(ws) % making a copy of existing worksheet # iteration to find the last row with values in it nrows = ws.max_row lastrow = 0 if nrows > 1000: nrows = 1000 while True: if ws.cell(nrows, 3).value != None: lastrow = nrows break else: nrows -= 1 # appending to the worksheet and saving it if AppendLog==1: # if AppendLog is wished at start count=0 # iterate over all entries in appData array which contains variables for appending the excel for ncol, entry in enumerate(appData,start=1): # print(ncol, entry) ws.cell(row=1+nrows, column=ncol, value=entry) count += 1 print('[{}] - No. of entries made: {} \n'.format(now(), count)) wb.save(xl_filepath) # file should be closed to save print('[{}] - Changes saved to: {} \n'.format(now(), ws_title)) else: print('[{}] - Changes not saved to: {} \n'.format(now(), ws_title)) ## References: # https://realpython.com/openpyxl-excel-spreadsheets-python/ ## Links to data and logbook # z:\Projekte\109797-TestfeldBHV\30_Technical_execution_Confidential\TP3\AP2_Aufbau_Infrastruktur\Infrastruktur_Windmessung\02_Equipment\04_Nacelle-Lidars-Inflow_CONFIDENTIAL\30_Data\Logbook_NacelleLidars.xlsx'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 5979, 2808, 8753, 25, 3553, 25, 4051, 12131, 198, 198, 31, 9800, 25, 20461, 971, 198, 37811, 198, 2, 6127, 2604, 2070, 198, 2, 838, 13, ...
2.274002
4,135
# Uses python3 import sys if __name__ == '__main__': input = sys.stdin.readline() n = int(input) print(fibonacci_sum_faster(n))
[ 2, 36965, 21015, 18, 198, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 5128, 796, 25064, 13, 19282, 259, 13, 961, 1370, 3419, 198, 220, 220, 220, 299, 796, 493, 7, 15414,...
2.253968
63
# encoding: utf-8 import re from django import template register = template.Library() @register.filter def truncchar(value, arg): ''' Truncate after a certain number of characters. Source: http://www.djangosnippets.org/snippets/194/ Notes ----- Super stripped down filter to truncate after a certain number of letters. Example ------- {{ long_blurb|truncchar:20 }} The above will display 20 characters of the long blurb followed by "..." ''' if not isinstance(value, basestring): value = unicode(value) if len(value) < arg: return value else: return value[:arg] + u'…' @register.filter def re_sub(string, args): """ Provide a full regular expression replace on strings in templates Usage: {{ my_variable|re_sub:"/(foo|bar)/baaz/" }} """ old = args.split(args[0])[1] new = args.split(args[0])[2] return re.sub(old, new, string) @register.filter def replace(string, args): """ Provide a standard Python string replace in templates Usage: {{ my_variable|replace:"/foo/bar/" }} """ old = args.split(args[0])[1] new = args.split(args[0])[2] return string.replace(old, new)
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 302, 198, 198, 6738, 42625, 14208, 1330, 11055, 198, 198, 30238, 796, 11055, 13, 23377, 3419, 628, 198, 31, 30238, 13, 24455, 198, 4299, 40122, 10641, 7, 8367, 11, 1822, 2599, 198, 22...
2.648069
466
#!/usr/bin/env python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(27,GPIO.OUT) GPIO.output(27,GPIO.HIGH) time.sleep(2) GPIO.output(27,GPIO.LOW)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 25812, 72, 13, 16960, 9399, 355, 50143, 198, 11748, 640, 198, 16960, 9399, 13, 2617, 14171, 7, 16960, 9399, 13, 2749, 44, 8, 198, 16960, 9399, 13, 2617, 40539, 654, 7, 25...
2.073684
95
# Copyright 2018 Jetperch LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjls import Reader, DataType, AnnotationType, SignalType, SourceDef, SignalDef, SummaryFSR from PySide2 import QtCore from joulescope import span from .widgets.waveform.annotations import AnnotationLoader import os import numpy as np import threading import queue import weakref import logging TIMEOUT = 10.0 class RecordingView: """A user-interface-compatible device that displays previous recorded data""" @property @property @property def limits(self): """Get the (x_min, x_max) limits for the view.""" if self._span is not None: return list(self._span.limits) return None @property @property def _get(self, start, stop, incr=None): """Get the statistics data. :param start: The starting sample id (inclusive). :param stop: The stop sample id (exclusive). :param incr: The increment for each returned value. None (default) is equivalent to 1. :return: A statistics data structure. """ self._log.info('get: x_range=%r => (%s, %s, %s)', self._x_range, start, stop, incr) reader = self._reader fs = self.sampling_frequency if incr is None: incr = 1 elif incr < 1: msg = f'incr {incr} < 1' self._log.warning(msg) raise RuntimeError(msg) if stop < (start + incr): msg = f'invalid range {start}, {stop}, {incr}' self._log.warning(msg) raise RuntimeError(msg) x_len = (stop - start) // incr stop = start + x_len * incr t_start = start / fs x = np.arange(x_len, dtype=np.float64) x *= incr / fs x += t_start dx = (x[-1] - x[0]) + (incr - 1) / fs result = { 'time': { 'x': {'value': x, 'units': 's'}, 'delta': {'value': dx, 'units': 's'}, 'samples': {'value': [start, stop], 'units': 'samples'}, 'limits': {'value': self.limits, 'units': 's'}, }, 'state': {'source_type': 'buffer'}, 'signals': {}, } for signal in reader.signals.values(): signal_id = signal.signal_id if signal_id == 0: continue if signal.signal_type != SignalType.FSR: continue units = signal.units try: if incr > 1: data = reader.fsr_statistics(signal_id, start, incr, x_len) dmean = data[:, SummaryFSR.MEAN] s = { 'µ': {'value': dmean, 'units': units}, 'σ2': {'value': data[:, SummaryFSR.STD] * data[:, SummaryFSR.STD], 'units': units}, 'min': {'value': data[:, SummaryFSR.MIN], 'units': units}, 'max': {'value': data[:, SummaryFSR.MAX], 'units': units}, 'p2p': {'value': data[:, SummaryFSR.MAX] - data[:, SummaryFSR.MIN], 'units': units}, # '∫': {'value': 0.0, 'units': units}, # todo } else: data = reader.fsr(signal_id, start, x_len) zeros = np.zeros(len(data), dtype=np.float32) s = { 'µ': {'value': data, 'units': units}, 'σ2': {'value': zeros, 'units': units}, 'min': {'value': data, 'units': units}, 'max': {'value': data, 'units': units}, 'p2p': {'value': zeros, 'units': units}, # '∫': {'value': 0.0, 'units': units}, # todo } result['signals'][signal.name] = s except Exception: self._log.warning('view could not get %s', signal.name) return result def _statistics_get(self, start=None, stop=None, units=None): """Get the statistics for the collected sample data over a time range. :param start: The starting time relative to the streaming start time. :param stop: The ending time. :param units: The units for start and stop. 'seconds' or None is in floating point seconds relative to the view. 'samples' is in stream buffer sample indices. :return: The statistics data structure. """ self._log.info('_statistics_get(%s, %s, %s)', start, stop, units) if units == 'seconds': t_start, t_stop = start, stop fs = self.sampling_frequency start = int(round(start * fs)) stop = int(round(stop * fs + 1)) # make exclusive self._log.info('_statistics_get(%s, %s, %s) => (%s, %s)', t_start, t_stop, units, start, stop) else: self._log.info('_statistics_get(%s, %s, %s)', start, stop, units) s = self._get(start, stop, stop - start) return s def samples_get(self, start=None, stop=None, units=None, fields=None): """Get exact samples over a range. :param start: The starting time. :param stop: The ending time. :param units: The units for start and stop. 'seconds' or None is in floating point seconds relative to the view. 'samples' is in stream buffer sample indices. :param fields: The list of field names to get. """ args = {'start': start, 'stop': stop, 'units': units, 'fields': fields} return self._parent()._post_block('samples_get', self, args) def statistics_get(self, start=None, stop=None, units=None, callback=None): """Get statistics over a range. :param start: The starting time. :param stop: The ending time. :param units: The units for start and stop. 'seconds' or None is in floating point seconds relative to the view. 'samples' is in stream buffer sample indicies. :param callback: The optional callable. When provided, this method will not block and the callable will be called with the statistics data structure from the view thread. :return: The statistics data structure or None if callback is provided. """ args = {'start': start, 'stop': stop, 'units': units} if callback is None: return self._parent()._post_block('statistics_get', self, args) else: self._parent()._post('statistics_get', self, args, callback) return class RecordingViewerDeviceV2: """A user-interface-compatible device that displays previous recorded data :param filename: The filename path to the pre-recorded data. """ @property @property @property @property @property
[ 2, 15069, 2864, 19013, 525, 354, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921...
2.218591
3,335
# Copyright 2019 the gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An example of cancelling requests in gRPC.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import signal import sys import grpc from examples.python.cancellation import hash_name_pb2 from examples.python.cancellation import hash_name_pb2_grpc _DESCRIPTION = "A client for finding hashes similar to names." _LOGGER = logging.getLogger(__name__) if __name__ == "__main__": logging.basicConfig() main()
[ 2, 15069, 13130, 262, 308, 49, 5662, 7035, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198,...
3.550162
309
# Generated by Django 3.0.6 on 2020-05-14 20:41 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 21, 319, 12131, 12, 2713, 12, 1415, 1160, 25, 3901, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
#MenuTitle: New Tab with Overlaps # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Opens a new Edit tab containing all glyphs that contain overlaps. """ import copy thisFont = Glyphs.font # frontmost font master_ids = [master.id for master in thisFont.masters] # all the master ids try: # Glyphs.clearLog() # clears log in Macro window thisFont.disableUpdateInterface() # suppresses UI updates in Font View text = "" for thisGlyph in thisFont.glyphs: # thisGlyph.beginUndo() # begin undo grouping thisLayer = thisGlyph.layers[0] if not thisLayer.paths: continue if thisLayer.layerId in master_ids or thisLayer.isSpecialLayer: has_overlaps = check_for_overlaps(thisLayer) if has_overlaps: text += "/%s " % (thisGlyph.name) # thisGlyph.endUndo() # end undo grouping thisFont.newTab(text) finally: thisFont.enableUpdateInterface() # re-enables UI updates in Font View
[ 2, 23381, 19160, 25, 968, 16904, 351, 3827, 75, 1686, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 834, 15390, 8...
2.824926
337
import random import datetime import asyncio import math import matplotlib.pyplot as plt import numpy as np import os import json import discord from discord.ext import commands intents = discord.Intents.default() intents.members = True intents.reactions = True intents.messages = True client = commands.Bot(command_prefix = '//', intents = intents) client.remove_command("help") @client.event @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @client.command() @commands.has_role("Owner") #requires a role named Owner in the server , you can change it to has_permission @client.command() @client.command() @client.command() @client.command() @client.command() client.run("bot token here")
[ 11748, 4738, 198, 11748, 4818, 8079, 198, 11748, 30351, 952, 198, 11748, 10688, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 36446, 198...
3.071672
293
#coding=utf-8 import numpy import random import torch from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import Matern from scipy.stats import norm import random import os from numpy import argmax import argparse global accuracy_loss_constraint, latency_constraint,optimal_scheme,avaliable_scheme,avaliable_evaluated_scheme import warnings warnings.filterwarnings("ignore") # User define the following parameters, 10000 as a loose constraint means the constraint actually has no influence parser = argparse.ArgumentParser() parser.add_argument('-accuracy_or_latency', type=bool, default=False) parser.add_argument('-accuracy_loss', type=float, default=10000) parser.add_argument('-latency', type=float, default=10000) parser.add_argument('-bandwidth', type=float, default=1) parser.add_argument('-gpu', type=int, default=0) args = parser.parse_args() data_base_address='./latency_search.txt' #The latency profiler of the IoT-Cloud system bandwidth=args.bandwidth/8 #MB/s accuracy_loss_base = 0.151 only_pi_latency=3.2571 only_cloud=360*240*3/1024/1024/bandwidth base_transmission=224*224/8/1024/1024 #MB layer=[64, 64,'M', 128, 128,'M', 256, 256, 256,'M', 512, 512, 512,'M', 512, 512, 512] pi_layer_latency=[] pi_latency=[0.0597,0.0937,0.1179,0.5048,0.5054,0.5074,0.51,0.5382,0.5557,0.5682,0.9844,1.0018,1.0142,1.055,1.2156,1.2246,1.2318,1.5411,1.5501,1.5577,1.8679,1.8768,1.8845,1.9072,2.0437,2.0484,2.0532,2.3183,2.3231,2.3279,2.5918,2.5966,2.6014,2.6134,2.6898,2.6913,2.6938,2.7694,2.7709,2.7735,2.8487,2.8503,2.8528,2.8569,3.2571] gpu_layer_latency=[] gpu_latency=[ 0.0001, 0.0002, 0.0002, 0.0003, 0.0003, 0.0004, 0.0004, 0.0005, 0.0006, 0.0006, 0.0008, 0.0008, 0.0008, 0.0009, 0.0010, 0.0010, 0.0011, 0.0011, 0.0012, 0.0012, 0.0013, 0.0014, 0.0014, 0.0014, 0.0015, 0.0018, 0.0019, 0.0020, 0.0020, 0.0020, 0.0021, 0.0022, 0.0022, 0.0023, 0.0023, 0.0024, 0.0024, 0.0025, 0.0026, 0.0026, 0.0027, 0.0028, 0.0028, 0.0029, 0.0032] layer_latency_index=[3,7,10,14,17,20,24,27,30,34,37,40,44] # probability of improvement acquisition function for i in layer_latency_index: gpu_layer_latency.append(gpu_latency[i-1]) pi_layer_latency.append(pi_latency[i-1]) if __name__ == "__main__": accuracy_or_latency_demand=args.accuracy_or_latency #True for accuracy demand if accuracy_or_latency_demand: accuracy_loss_constraint = args.accuracy_loss latency_constraint = min(only_cloud,only_pi_latency) else: accuracy_loss_constraint = 0.1 latency_constraint = min(only_cloud,only_pi_latency)*args.latency #True for accuracy demand gpu = args.gpu ##initialize the scheme space search_times=0 optimal_scheme = [] all_scheme, all_transmission, all_latency, all_layer_start_index = scheme_generation(pi_layer_latency) all_evaluated_scheme = [[i, None] for i in all_scheme]#evaluated_scheme=[[scheme],accuracy_loss] avaliable_scheme = all_scheme avaliable_evaluated_scheme = [i for i in all_evaluated_scheme if i[1] != None]#avaliable_evaluated_scheme=[[scheme],accuracy_loss] print('The whole searching space =',len(avaliable_scheme)) # filter schemes satisfying the latency constraint avaliable_index = index_conut_latency() avaliable_scheme = [all_scheme[i] for i in avaliable_index] for i in avaliable_evaluated_scheme: if i[0] in avaliable_scheme: avaliable_scheme.remove(i[0]) ##start searching main()
[ 2, 66, 7656, 28, 40477, 12, 23, 201, 198, 11748, 299, 32152, 201, 198, 11748, 4738, 201, 198, 11748, 28034, 201, 198, 6738, 1341, 35720, 13, 4908, 31562, 62, 14681, 1330, 12822, 31562, 18709, 8081, 44292, 201, 198, 6738, 1341, 35720, ...
2.192742
1,681
""" This is the module where the model is defined. It uses the nn.Module as backbone to create the network structure """ # Own modules # Built in import math # Libs import numpy as np # Pytorch module import torch.nn as nn import torch.nn.functional as F import torch """ class Decoder(nn.Module): def __init__(self, flags): super(Decoder, self).__init__() "" This part is the Decoder model layers definition: "" # Linear Layer and Batch_norm Layer definitions here self.linears_d = nn.ModuleList([]) self.bn_linears_d = nn.ModuleList([]) for ind, fc_num in enumerate(flags.linear_d[0:-1]): # Excluding the last one as we need intervals self.linears_d.append(nn.Linear(fc_num, flags.linear_d[ind + 1])) self.bn_linears_d.append(nn.BatchNorm1d(flags.linear_d[ind + 1])) def forward(self, z, S_enc): "" The forward function which defines how the network is connected :param S_enc: The encoded spectra input :return: G: Geometry output "" out = torch.concatenate(z, S_enc) # initialize the out # For the linear part for ind, (fc, bn) in enumerate(zip(self.linears_d, self.bn_linears_d)): # print(out.size()) out = F.relu(bn(fc(out))) # ReLU + BN + Linear return out class Encoder(nn.Module): def __init__(self, flags): super(Encoder, self).__init__() "" This part is the Decoder model layers definition: "" # Linear Layer and Batch_norm Layer definitions here self.linears_e = nn.ModuleList([]) self.bn_linears_e = nn.ModuleList([]) for ind, fc_num in enumerate(flags.linear_e[0:-1]): # Excluding the last one as we need intervals self.linears_e.append(nn.Linear(fc_num, flags.linear_e[ind + 1])) self.bn_linears_e.append(nn.BatchNorm1d(flags.linear_e[ind + 1])) # Re-parameterization self.zmean_layer = nn.Linear(flags.linear_e[-1], flags.dim_latent_z) self.z_log_var_layer = nn.Linear(flags.linear_e[-1], flags.dim_latent_z) def forward(self, G, S_enc): "" The forward function which defines how the network is connected :param S_enc: The encoded spectra input :param G: Geometry output :return: Z_mean, Z_log_var: the re-parameterized mean and variance of the "" out = torch.concatenate(G, S_enc) # initialize the out # For the linear part for ind, (fc, bn) in enumerate(zip(self.linears_e, self.bn_linears_e)): # print(out.size()) out = F.relu(bn(fc(out))) # ReLU + BN + Linear z_mean = self.zmean_layer(out) z_log_var = self.z_log_var_layer(out) return z_mean, z_log_var class SpectraEncoder(nn.Module): def __init__(self, flags): super(SpectraEncoder, self).__init__() "" This part if the backward model layers definition: "" # Linear Layer and Batch_norm Layer definitions here self.linears_se = nn.ModuleList([]) self.bn_linears_se = nn.ModuleList([]) for ind, fc_num in enumerate(flags.linear_se[0:-1]): # Excluding the last one as we need intervals self.linears_se.append(nn.Linear(fc_num, flags.linear_se[ind + 1])) self.bn_linears_se.append(nn.BatchNorm1d(flags.linear_se[ind + 1])) # Conv Layer definitions here self.convs_se = nn.ModuleList([]) in_channel = 1 # Initialize the in_channel number for ind, (out_channel, kernel_size, stride) in enumerate(zip(flags.conv_out_channel_se, flags.conv_kernel_size_se, flags.conv_stride_se)): if stride == 2: # We want to double the number pad = int(kernel_size/2 - 1) elif stride == 1: # We want to keep the number unchanged pad = int((kernel_size - 1)/2) else: Exception("Now only support stride = 1 or 2, contact Ben") self.convs_se.append(nn.Conv1d(in_channel, out_channel, kernel_size, stride=stride, padding=pad)) in_channel = out_channel # Update the out_channel def forward(self, S): "" The backward function defines how the backward network is connected :param S: The 300-d input spectrum :return: S_enc: The n-d output encoded spectrum "" out = S.unsqueeze(1) # For the Conv Layers for ind, conv in enumerate(self.convs_se): out = conv(out) out = out.squeeze() # For the linear part for ind, (fc, bn) in enumerate(zip(self.linears_se, self.bn_linears_se)): out = F.relu(bn(fc(out))) S_enc = out return S_enc """
[ 37811, 201, 198, 1212, 318, 262, 8265, 810, 262, 2746, 318, 5447, 13, 632, 3544, 262, 299, 77, 13, 26796, 355, 32774, 284, 2251, 262, 3127, 4645, 201, 198, 37811, 201, 198, 2, 11744, 13103, 201, 198, 201, 198, 2, 28477, 287, 201, ...
2.000758
2,638
""" * This file is part of the subhajeet2107/pylexer package. * * (c) Subhajeet Dey <subhajeet2107@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. """ from pylex.config.lexer_config import LexerConfig from pylex.config.token_defination import TokenDefination class LexerDictConfig(LexerConfig): """ Lexer Configuration using a dictionary """
[ 37811, 198, 1635, 770, 2393, 318, 636, 286, 262, 850, 71, 1228, 68, 316, 17, 15982, 14, 79, 2349, 87, 263, 5301, 13, 198, 1635, 198, 1635, 357, 66, 8, 3834, 71, 1228, 68, 316, 1024, 88, 1279, 7266, 71, 1228, 68, 316, 17, 15982, ...
3.020979
143
''' Generate an 0.1.x cortex for testing migration to 0.2.x ''' import os import json import shutil import asyncio import hashlib import synapse.common as s_common import synapse.cortex as s_cortex import synapse.lib.cell as s_cell import synapse.lib.module as s_module import synapse.lib.version as s_version import synapse.lib.modelrev as s_modelrev import synapse.lib.stormsvc as s_stormsvc import synapse.tools.backup as s_backup assert s_version.version == (0, 1, 56) DESTPATH_CORTEX = 'cortexes/0.1.56-migr' DESTPATH_SVC = 'cortexes/0.1.56-migr/stormsvc' DESTPATH_ASSETS = 'assets/0.1.56-migr' if __name__ == '__main__': asyncio.run(main())
[ 7061, 6, 198, 8645, 378, 281, 657, 13, 16, 13, 87, 20223, 329, 4856, 13472, 284, 657, 13, 17, 13, 87, 198, 7061, 6, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 4423, 346, 198, 11748, 30351, 952, 198, 11748, 12234, 8019, 198, ...
2.55642
257
import PySimpleGUI as sg from support import Velocity, Distance, Time, Acceleration from os import getlogin from re import sub error_count = 0 sg.set_options(element_padding=(5,5),icon="images/icon.ico",) sg.change_look_and_feel('blueMono') layout = [ [sg.Text('Initial Velocity'), sg.InputText(focus=True,key='ivelocity'), sg.InputCombo(('m/s','km/h'),default_value='m/s',readonly=True,disabled=True) ], [sg.Text('Final Velocity '), sg.InputText(key='velocity'), sg.InputCombo(('m/s','km/h'),default_value='m/s',readonly=True,disabled=True) ], [sg.Text('Acceleration '), sg.InputText(key='acceleration',disabled=True), sg.InputCombo(('m/s²','km/h²'),default_value='m/s²',readonly=True,disabled=True) ], [sg.Text('Elapsed Time'), sg.InputText(key='time'),sg.InputCombo(('seconds','hours'),default_value='seconds',readonly=True,disabled=True),], [sg.Text('Distance '), sg.InputText(key='distance'),sg.InputCombo(('meters','kilometers'),default_value='meters',readonly=True,disabled=True),], [sg.Text('Determine '), sg.Radio('Acceleration',0,default=True,key='is_acceleration',enable_events='True'), sg.Radio('Velocity',0,key='is_velocity',enable_events='True'), sg.Radio('Time',0,key='is_time',enable_events='True'), sg.Radio('Distance',0,key='is_distance',enable_events='True'), ], [sg.Output(size=(88, 10),key='log',font=("Segoe UI Bold",10),text_color='#221255')], [sg.Text('Acceleration Rate:',key="output",size=(50,1),font=('Segoe UI Bold',10))], [sg.Button(button_text='Calculate'),sg.Button(button_text='Clear'), sg.Button(button_text='Help'), sg.Button(button_text='Exit')] ] window = sg.Window('PhysicsX', layout) while True: event, values = window.read() if values['is_acceleration'] is True: window.find('acceleration').update("",disabled = True) window.find('output').update('Acceleration Rate:') window.find('velocity').update(disabled = False) window.find('distance').update(disabled = False) window.find('time').update(disabled = False) elif values['is_velocity'] is True: window.find('acceleration').update(disabled = False) window.find('output').update('Final Velocity:') window.find('velocity').update("",disabled = True) window.find('distance').update(disabled = False) window.find('time').update(disabled = False) elif values['is_distance'] is True: window.find('acceleration').update(disabled = False) window.find('velocity').update(disabled = False) window.find('distance').update("",disabled = True) window.find('output').update('Distance:') window.find('time').update(disabled = False) elif values['is_time'] is True: window.find('acceleration').update(disabled = False) window.find('velocity').update(disabled = False) window.find('distance').update(disabled = False) window.find('time').update("",disabled = True) window.find('output').update('Elapsed Time:') if event in (None, 'Exit', 'Cancel'): break if event == 'Calculate': initial_velocity = parse_data(values['ivelocity'],default=0) final_velocity = parse_data(values['velocity']) time = parse_data(values['time']) distance = parse_data(values['distance']) acceleration = parse_data(values['acceleration']) if values['is_acceleration'] is True: result = Acceleration(initial_velocity= initial_velocity, final_velocity= final_velocity, time=time,distance=distance) ans = result.calculate() if ans is not None: answer_digit_only = sub(r"[^0123456789\.-]","",ans) if answer_digit_only != "": window.find('output').update(f'Acceleration Rate: {answer_digit_only} meters/second²') print(f"[Calculated_Result]: {ans}") else: print (ans) elif values['is_velocity'] is True: result = Velocity(initial_velocity= initial_velocity, acceleration=acceleration, time=time,distance=distance) ans = result.calculate() if ans is not None: answer_digit_only = sub(r"[^0123456789\.-]","",ans) if answer_digit_only != "": window.find('output').update(f'Final Velocity: {answer_digit_only} meters/second') print(f"[Calculated_Result]: {ans}") else: print(ans) elif values['is_time'] is True: result = Time(initial_velocity= initial_velocity, final_velocity= final_velocity, acceleration=acceleration,distance=distance) ans = result.calculate() if ans is not None: answer_digit_only = sub(r"[^0123456789\.-]","",ans) if answer_digit_only != "": window.find('output').update(f'Elapsed Time: {answer_digit_only} seconds') print(f"[Calculated_Result]: {ans}") else: print(ans) elif values['is_distance'] is True: result = Distance(initial_velocity= initial_velocity, final_velocity= final_velocity, time=time,acceleration=acceleration) ans = result.calculate() if ans is not None: answer_digit_only = sub(r"[^0123456789\.-]","",ans) if answer_digit_only != "": window.find('output').update(f'Distance: {answer_digit_only} meters') print(f"[Calculated_Result]: {ans}") else: print(ans) else: sg.PopupError('No Operation Selected',title='Critical Error') if event == 'Clear': window.find('ivelocity').update('') window.find('velocity').update('') window.find('distance').update('') window.find('time').update('') window.find('acceleration').update('') window.find('log').update('') if event == 'Debug': for i in values: print(f"values[{i}]--> {values[i]}") if event == "Help": user = getlogin() msg = (f'Hello {user}\n\nTo Calculate The Value Of A Property Just Click On The Dot Next To It\nIf You Don\'t Have A Value For Something: Leave It Blank!\n') sg.popup(msg,title="Help",background_color='#000000',text_color='#FFFFFF') window.close()
[ 11748, 9485, 26437, 40156, 355, 264, 70, 201, 198, 6738, 1104, 1330, 43137, 11, 34600, 11, 3862, 11, 29805, 341, 201, 198, 6738, 28686, 1330, 651, 38235, 201, 198, 6738, 302, 1330, 850, 201, 198, 201, 198, 18224, 62, 9127, 796, 657, ...
2.207181
3,036
import random from crypto_commons.generic import long_to_bytes, multiply, factorial from crypto_commons.rsa.rsa_commons import ensure_long, modinv, lcm_multi """ Here are some less popular asymmetric cryptosystems: - Damgard-Jurik - Paillier (same as Damgard Jurik for s = 1) """ def paillier_encrypt(m, g, n, r): """ Encrypt data using Paillier Cryptosystem Actually it's the same as Damgard Jurik with s=1 :param m: plaintext to encrypt, can be either long or bytes :param g: random public integer g :param n: modulus :param r: random r :return: encrypted data as long """ m = ensure_long(m) n2 = n * n return (pow(g, m, n2) * pow(r, n, n2)) % n2 def paillier_encrypt_simple(m, g, n): """ Encrypt data using Paillier Cryptosystem Actually it's the same as Damgard Jurik with s=1 :param m: plaintext to encrypt, can be either long or bytes :param g: random public integer g :param n: modulus :return: encrypted data as long """ n2 = n * n r = random.randint(2, n2) return paillier_encrypt(m, g, n, r) def paillier_decrypt(c, factors, g): """ Decrypt data using Paillier Cryptosystem Actually it's the same as Damgard Jurik with s=1 :param c: ciphertext :param factors: prime factors :param g: random public integer g :return: decrypted data as long """ lbd = lcm_multi([p - 1 for p in factors]) n = multiply(factors) x = L(pow(g, lbd, n * n), n) mi = int(modinv(x, n)) m = L(pow(c, lbd, n * n), n) * pow(mi, 1, n) return m % n def paillier_decrypt_printable(c, factors, g): """ Decrypt data using Paillier Cryptosystem Actually it's the same as Damgard Jurik with s=1 :param c: ciphertext :param factors: prime factors :param g: random public integer g :return: decrypted data as bytes """ return long_to_bytes(paillier_decrypt(c, factors, g)) def damgard_jurik_encrypt(m, n, g, s): """ Encrypt data using Damgard Jurik Cryptosystem :param m: plaintext :param n: modulus :param g: random public integer g :param s: order n^s :return: """ m = ensure_long(m) s1 = s + 1 ns1 = n ** s1 r = random.randint(2, ns1) enc = pow(g, m, ns1) * pow(r, n ** s, ns1) % ns1 return enc def damgard_jurik_decrypt(c, n, s, factors, g): """ Decrypt data using Damgard Jurik Cryptosystem :param c: ciphertext :param n: modulus :param s: order n^s :param factors: modulus prime factors :param g: random public integer g :return: """ d = lcm_multi([p - 1 for p in factors]) ns = pow(n, s) jd = decrypt(g, d, n, s) jd_inv = modinv(jd, ns) jmd = decrypt(c, d, n, s) return (jd_inv * jmd) % ns
[ 11748, 4738, 198, 198, 6738, 21473, 62, 9503, 684, 13, 41357, 1330, 890, 62, 1462, 62, 33661, 11, 29162, 11, 1109, 5132, 198, 6738, 21473, 62, 9503, 684, 13, 3808, 64, 13, 3808, 64, 62, 9503, 684, 1330, 4155, 62, 6511, 11, 953, 16...
2.412987
1,155
mats = [ Mat(**m) for m in [ { "name": "Bronze", "smithing": 1, "forging": 15, "forging_levels": [1], "forging_burial": False, }, { "name": "Iron", "smithing": 2, "forging": 40, "forging_levels": [1, 1], "forging_burial": False, }, { "name": "Steel", "smithing": 3, "forging": 75, "forging_levels": [1, 1], "forging_burial": False, }, { "name": "Mithril", "smithing": 5, "forging": 120, "forging_levels": [1, 1, 2], "forging_burial": False, }, { "name": "Adamant", "smithing": 7, "forging": 170, "forging_levels": [1, 1, 2], "forging_burial": True, }, { "name": "Rune", "smithing": 10, "forging": 240, "forging_levels": [1, 1, 2, 4], "forging_burial": True, }, { "name": "Orikalkum", "smithing": 13, "forging": 350, "forging_levels": [1, 1, 2, 4], "forging_burial": True, }, { "name": "Necronium", "smithing": 17, "forging": 500, "forging_levels": [1, 1, 2, 4, 8], "forging_burial": True, }, { "name": "Bane", "smithing": 21, "forging": 700, "forging_levels": [1, 1, 2, 4, 8], "forging_burial": True, }, { "name": "Elder Rune", "smithing": 26, "forging": 1000, "forging_levels": [1, 1, 2, 4, 8, 16], "forging_burial": True, }, ] ]
[ 76, 1381, 796, 685, 198, 220, 220, 220, 6550, 7, 1174, 76, 8, 198, 220, 220, 220, 329, 285, 287, 685, 198, 220, 220, 220, 220, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 366, 3672, 1298, 3...
1.54339
1,233
from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 11299, 19199, 13, 27530, 1330, 14041, 6030, 198, 198, 6738, 42625...
3.636364
55
from typing import List if __name__ == '__main__': s = Solution() nums1 = [1, 2, 3] nums2 = [2, 3, 4, 5] # nums1 = [0, 0] # nums2 = [0, 0] print(s.findMedianSortedArrays(nums1=nums1, nums2=nums2))
[ 6738, 19720, 1330, 7343, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 264, 796, 28186, 3419, 198, 220, 220, 220, 997, 82, 16, 796, 685, 16, 11, 362, 11, 513, 60, 198, 220, 220, 220, ...
1.898305
118
# -*- coding: utf-8 -*- # @Author : Lyu Kui # @Email : 9428.al@gmail.com # @Created Date : 2021-02-24 13:58:46 # @Last Modified : 2021-03-05 18:14:17 # @Description : import tensorflow as tf from .nets.efficientnet import EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetB3 from .nets.efficientnet import EfficientNetB4, EfficientNetB5, EfficientNetB6, EfficientNetB7 if __name__ == '__main__': model = EasyDet(phi=0) model.summary() import time import numpy as np x = np.random.random_sample((1, 640, 640, 3)) # warm up output = model.predict(x) print('\n[INFO] Test start') time_start = time.time() for i in range(1000): output = model.predict(x) time_end = time.time() print('[INFO] Time used: {:.2f} ms'.format((time_end - time_start)*1000/(i+1)))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 220, 220, 220, 220, 220, 220, 220, 1058, 9334, 84, 509, 9019, 198, 2, 2488, 15333, 220, 220, 220, 220, 220, 220, 220, 220, 1058, 10048, 2078, 13, 282...
2.327027
370
from libs import *
[ 6738, 9195, 82, 1330, 1635, 201 ]
3.166667
6
from PygameFloatObjects.objects import * # circle_example()
[ 6738, 9485, 6057, 43879, 10267, 82, 13, 48205, 1330, 1635, 628, 628, 198, 2, 9197, 62, 20688, 3419, 198 ]
3.368421
19
''' This example demonstrates creating and usind an AdvancedEffectBase. In this case, we use it to efficiently pass the touch coordinates into the shader. ''' from kivy.base import runTouchApp from kivy.properties import ListProperty from kivy.lang import Builder from kivy.uix.effectwidget import EffectWidget, AdvancedEffectBase effect_string = ''' uniform vec2 touch; vec4 effect(vec4 color, sampler2D texture, vec2 tex_coords, vec2 coords) { vec2 distance = 0.025*(coords - touch); float dist_mag = (distance.x*distance.x + distance.y*distance.y); vec3 multiplier = vec3(abs(sin(dist_mag - time))); return vec4(multiplier * color.xyz, 1.0); } ''' root = Builder.load_string(''' TouchWidget: Button: text: 'Some text!' Image: source: 'data/logo/kivy-icon-512.png' allow_stretch: True keep_ratio: False ''') runTouchApp(root)
[ 7061, 6, 198, 1212, 1672, 15687, 4441, 290, 514, 521, 281, 13435, 18610, 14881, 13, 554, 198, 5661, 1339, 11, 356, 779, 340, 284, 18306, 1208, 262, 3638, 22715, 656, 262, 33030, 13, 198, 7061, 6, 198, 198, 6738, 479, 452, 88, 13, ...
2.709091
330
from typing import Union from hypothesis import given from tests.utils import (FractionWithBuiltin, IntWithBuiltin, equivalence) from . import strategies @given(strategies.fractions_with_builtins, strategies.fractions_or_ints_with_builtins)
[ 6738, 19720, 1330, 4479, 198, 198, 6738, 14078, 1330, 1813, 198, 198, 6738, 5254, 13, 26791, 1330, 357, 37, 7861, 3152, 39582, 259, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.396825
126
#################### # Import Libraries #################### import os import sys import cv2 import numpy as np import pandas as pd import pytorch_lightning as pl from pytorch_lightning.metrics import Accuracy from pytorch_lightning import loggers from pytorch_lightning import seed_everything from pytorch_lightning import Trainer from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint import torch from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import StratifiedKFold, KFold import segmentation_models_pytorch as smp from catalyst.contrib.nn.criterion.dice import DiceLoss #from sklearn import model_selection import albumentations as A import timm import glob from omegaconf import OmegaConf from sklearn.metrics import roc_auc_score from tqdm import tqdm from PIL import Image cv2.setNumThreads(0) #################### # Utils #################### #################### # Config #################### conf_dict = {'batch_size': 8,#32, 'epoch': 30, 'image_size': 128,#640, 'image_scale': 2, 'encoder_name': 'timm-efficientnet-b0', 'lr': 0.001, 'fold': 0, 'csv_path': '../input/extract-test/train.csv', 'data_dir': '../input/extract-test/size_2048', 'output_dir': './', 'use_mask_exist': True, 'trainer': {}} conf_base = OmegaConf.create(conf_dict) #################### # Dataset #################### #################### # Data Module #################### # OPTIONAL, called only on 1 GPU/machine(for download or tokenize) # OPTIONAL, called for every GPU/machine #################### # Lightning Module #################### #################### # Train #################### if __name__ == "__main__": main()
[ 14468, 4242, 198, 2, 17267, 46267, 198, 14468, 4242, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 12972, 13165, 354, 62, 2971, ...
2.701881
691
#!/shared/anaconda/bin/python # encoding=utf8 from __future__ import print_function from __future__ import division from __future__ import unicode_literals from builtins import bytes, chr from builtins import str from builtins import dict from builtins import object from builtins import range from builtins import map from builtins import zip from builtins import filter import sys import re import codecs reload(sys) sys.setdefaultencoding('utf8') sys.stdin = codecs.getreader('utf8')(sys.stdin, errors='ignore') session_time = 0 session_count = 0 for line in sys.stdin: count, time = list(map(int, line.split('\t'))) session_count += count session_time += time print(session_count, session_time, sep='\t')
[ 2, 48443, 28710, 14, 272, 330, 13533, 14, 8800, 14, 29412, 198, 2, 21004, 28, 40477, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 28000, 109...
3.114894
235
# Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock
[ 2, 15069, 2177, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330...
3.811321
159
import time from django.test import TestCase from algoliasearch_django import algolia_engine from algoliasearch_django import get_adapter from algoliasearch_django import register from algoliasearch_django import unregister from algoliasearch_django import raw_search from algoliasearch_django import clear_index from algoliasearch_django import update_records from .models import Website
[ 11748, 640, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 198, 6738, 435, 70, 349, 4448, 3679, 62, 28241, 14208, 1330, 435, 70, 22703, 62, 18392, 198, 6738, 435, 70, 349, 4448, 3679, 62, 28241, 14208, 1330, 651, 62, ...
3.275
120
from .grade_metric import GradeMetric import types class NCU(GradeMetric): ''' NCU (Normalised Cumulative Utility) See Sakai. T. and Robertson, S.: Modelling A User Population for Designing Information Retrieval Metrics, EVIA 2008. Args: xrelnum: the number of judged X-rel docs (including 0-rel=judged nonrel). grades: a list of the grade for each relevance level (except level 0). beta: a parameter for blended ratio sp: a stop probability function. There are three functions in our implementation, uniform (p_u), graded-uniform (p_gu), rank-biased (p_rb). ''' def gain(self, idx): ''' Blended ratio ''' rank = self.rank(idx) g = sum([self._grade(i) for i in range(rank)]) ig = sum(self.ideal_grade_ranked_list[:rank]) return (self.relnum + self.beta * g) / (rank + self.beta * ig) def p_u(): ''' Uniform stop probability function where the stop probability is the same for all the relevant documents, i.e. 1/(# relevant documents). ''' return func def p_gu(stops): ''' Graded-uniform stop probability function where the stop probability is defined for each relevance level. Args: stops: a list of the stop probability for each relevance level (except 0 level). ''' return func def p_rb(gamma): ''' Rank-biased stop probability function where the stop probability increases as the number of preceding relevant documents increase. Args: gamma: a parameter that controls the gain of the stop probability when a relevant document is observed. ''' return func class NCUguP(NCU): ''' NCU (Normalised Cumulative Utility) with Pr = Graded-uniform and NU = Precision See Sakai. T. and Robertson, S.: Modelling A User Population for Designing Information Retrieval Metrics, EVIA 2008. Args: xrelnum: the number of judged X-rel docs (including 0-rel=judged nonrel). grades: a list of the grade for each relevance level (except level 0). stops: a list of the stop probability for each relevance level (except 0 level). ''' class NCUguBR(NCU): ''' NCU (Normalised Cumulative Utility) with Pr = Graded-uniform and NU = Blended ratio See Sakai. T. and Robertson, S.: Modelling A User Population for Designing Information Retrieval Metrics, EVIA 2008. Args: xrelnum: the number of judged X-rel docs (including 0-rel=judged nonrel). grades: a list of the grade for each relevance level (except level 0). stops: a list of the stop probability for each relevance level (except 0 level). beta: a parameter for blended ratio ''' class NCUrbP(NCU): ''' NCU (Normalised Cumulative Utility) with Pr = Rank-biased and NU = Precision See Sakai. T. and Robertson, S.: Modelling A User Population for Designing Information Retrieval Metrics, EVIA 2008. Args: xrelnum: the number of judged X-rel docs (including 0-rel=judged nonrel). grades: a list of the grade for each relevance level (except level 0). gamma: a parameter that controls the gain of the stop probability when a relevant document is observed. ''' class NCUrbBR(NCU): ''' NCU (Normalised Cumulative Utility) with Pr = Rank-biased and NU = Blended ratio See Sakai. T. and Robertson, S.: Modelling A User Population for Designing Information Retrieval Metrics, EVIA 2008. Args: xrelnum: the number of judged X-rel docs (including 0-rel=judged nonrel). grades: a list of the grade for each relevance level (except level 0). gamma: a parameter that controls the gain of the stop probability when a relevant document is observed. beta: a parameter for blended ratio '''
[ 6738, 764, 9526, 62, 4164, 1173, 1330, 22653, 9171, 1173, 198, 11748, 3858, 198, 198, 4871, 8823, 52, 7, 42233, 9171, 1173, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 8823, 52, 357, 26447, 1417, 27843, 13628, 34030, 8, ...
2.831633
1,372
""" This automation attempts to remove a tag for a resource, identified as above or below the configured threshold by Hyperglance Rule(s) This automation will operate across accounts, where the appropriate IAM Role exists. """ import logging import processing.automation_utils as utils logger = logging.getLogger() logger.setLevel(logging.DEBUG) def hyperglance_automation(boto_session, resource: dict, automation_params=''): """ Attempts to Tag a resource Parameters ---------- boto_session : object The boto session to use to invoke the automation resource: dict Dict of Resource attributes touse in the automation automation_params : str Automation parameters passed from the Hyperglance UI """ key = automation_params.get('Key') tags = resource['tags'] if not key in tags.keys(): logger.error(tags) logger.error("tag " + key + " is not present - aborting automation") return utils.remove_tag(boto_session, key, resource)
[ 37811, 198, 198, 1212, 22771, 6370, 284, 4781, 257, 7621, 329, 257, 8271, 11, 5174, 355, 2029, 393, 2174, 262, 17839, 11387, 198, 1525, 15079, 4743, 590, 14330, 7, 82, 8, 198, 198, 1212, 22771, 481, 8076, 1973, 5504, 11, 810, 262, 5...
3.160494
324
''' This file contains helper functions ''' from datetime import timedelta def date_range(start_date, end_date): ''' Name: dateRange Input: start date end date Output: list of dates Purpose: generate list of dates between start and end ''' # now return list of dates for date_element in range(int((end_date-start_date).days)): yield start_date+timedelta(date_element) def format_cmd_line(cmdline, day): ''' Name: formatCmdLine Input: raw command line date Output: final command line Purpose: take a cmd line template and substitute in dates according to handful of predefined formats ''' # yyyymmdd only currently supported format cmdline = cmdline.replace("{yyyymmdd}", day.strftime("%Y%m%d")) # more below... # ... sometime return cmdline
[ 7061, 6, 198, 220, 220, 220, 770, 2393, 4909, 31904, 5499, 198, 7061, 6, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 4299, 3128, 62, 9521, 7, 9688, 62, 4475, 11, 886, 62, 4475, 2599, 198, 220, 220, 220, 705, 7061, 198, 22...
2.441799
378
"""File list helper functions.""" import re def generate_glob_and_replacer(search, replace): """ Prepare a wildcard pattern for globbing and replacing. :param search: :param replace: :return: """ replace = generate_replacer(search, replace) glob_pattern = prepare_for_regex(search, task='glob') return glob_pattern, replace def generate_replacer(search, replace): """ Prepare a wildcard pattern to be used a replacement regex. :param search: :param replace: :return: """ search = prepare_for_regex(search) replace = prepare_for_regex(replace, task='replace') search = re.compile(search) return _inner def prepare_for_regex(input_, task='search'): """ Prepare a wildcard pattern for specific use. :param input_: :param task: :return: """ splits = input_.split('{}') process = _prepare_for_regex_get_processor(task) return ( ''.join( process(n, split) for n, split in zip([n for n, _ in enumerate(splits)][1:], splits) ) + splits[-1] )
[ 37811, 8979, 1351, 31904, 5499, 526, 15931, 198, 11748, 302, 628, 198, 4299, 7716, 62, 4743, 672, 62, 392, 62, 35666, 11736, 7, 12947, 11, 6330, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 43426, 257, 4295, 9517, 3912, 329, ...
2.53303
439
from aiogram import types from aiogram.utils.callback_data import CallbackData from money_bot.utils.strings import ADD_TASKS_MENU_TEXT, EARN_MENU_TEXT, MAIN_MENU_BUTTONS_LABELS earn_factory = CallbackData("earn", "skip") add_tasks_factory = CallbackData("add_tasks", "data")
[ 6738, 257, 72, 21857, 1330, 3858, 198, 6738, 257, 72, 21857, 13, 26791, 13, 47423, 62, 7890, 1330, 4889, 1891, 6601, 198, 198, 6738, 1637, 62, 13645, 13, 26791, 13, 37336, 1330, 27841, 62, 51, 1921, 27015, 62, 49275, 52, 62, 32541, ...
2.67619
105
import requests import regex as re import sys import socket import ssl import datetime try: from http.client import HTTPConnection except ImportError: from httplib import HTTPConnection from requests.packages.urllib3.connection import VerifiedHTTPSConnection requests.packages.urllib3.connectionpool.HTTPConnection = MyHTTPConnection requests.packages.urllib3.connectionpool.HTTPConnectionPool.ConnectionCls = MyHTTPConnection # HTTPS requests.packages.urllib3.connectionpool.HTTPSConnection = MyHTTPSConnection requests.packages.urllib3.connectionpool.VerifiedHTTPSConnection = MyHTTPSConnection requests.packages.urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls = MyHTTPSConnection requests.packages.urllib3.disable_warnings() BASE_URL = 'https://{0}.cspace.berkeley.edu/cspace-services/' SERVICE = 'servicegroups/common/items?as=(collectionspace_core:updatedAt >= TIMESTAMP "{0}")' PAGE_OPT = '&pgSz={0}&pgNum={1}' START_DATE = str(datetime.date.today() - datetime.timedelta(days=1)) + "T00:00:00Z" if __name__ == "__main__": args = sys.argv userinfo = args[args.index("-u") + 1].split(":") if (len(userinfo) != 2): print("Please input password in this format: -u username:password") sys.exit(-1) user, pwd = userinfo[0], userinfo[1] # Which mode are we invoking? print(len(args)) print(args[1] == 'delete') if args[1] == 'delete' and len(args) == 6: filepath = args[args.index("-f") + 1] deleteRecords(user, pwd, filepath) elif args[1] == 'fetch' and len(args) == 8: env = args[args.index("-e") + 1] profile = args[args.index("-p") + 1] fetchUris(user, pwd, profile + '-' + env) else: print('Usage: fetch -p \'profile\' -e \'qa/dev\' -u \'username:password\' \ \n OR delete -f filepath -u \'username:password\'') sys.exit(-1)
[ 11748, 7007, 198, 11748, 40364, 355, 302, 198, 11748, 25064, 198, 11748, 17802, 198, 11748, 264, 6649, 198, 11748, 4818, 8079, 198, 198, 28311, 25, 198, 197, 6738, 2638, 13, 16366, 1330, 14626, 32048, 198, 16341, 17267, 12331, 25, 198, ...
2.746627
667
import torch.optim as optim from .adamw import AdamW from .adabound import AdaBound, AdaBoundW from .asam import SAM, ASAM
[ 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 764, 324, 321, 86, 1330, 7244, 54, 198, 6738, 764, 324, 397, 633, 1330, 47395, 49646, 11, 47395, 49646, 54, 198, 6738, 764, 292, 321, 1330, 28844, 11, 7054, 2390, 628 ]
3.179487
39
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', 'user_profile.views.profile', name="user_profile"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 764, 1330, 5009, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 3, 3256, 705, 7220, 62, 13317, 13, 33571, 13, 13317, 3256, 1438, 2...
2.72549
51
from __future__ import division import re from werkzeug.exceptions import BadRequest from flask import current_app from munimap.grid import Grid import logging log = logging.getLogger(__name__) MISSING = object() PRINT_NAME_REGEX = re.compile(r'^[0-9a-zA-Z_\.\-]+$')
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 302, 198, 6738, 266, 9587, 2736, 1018, 13, 1069, 11755, 1330, 7772, 18453, 198, 198, 6738, 42903, 1330, 1459, 62, 1324, 198, 198, 6738, 29856, 320, 499, 13, 25928, 1330, 24846, 198, 198, ...
2.75
100
import os import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * # # PlotsSelfTest # # # PlotsSelfTestWidget # # # PlotsSelfTestLogic # class PlotsSelfTestLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget """ class PlotsSelfTestTest(ScriptedLoadableModuleTest): """ This is the test case for your scripted module. """ def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0) def runTest(self): """Run as few or as many tests as needed here. """ self.setUp() self.test_PlotsSelfTest_FullTest1() # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
[ 11748, 28686, 198, 11748, 555, 715, 395, 198, 11748, 410, 30488, 11, 10662, 83, 11, 269, 30488, 11, 14369, 263, 198, 6738, 14369, 263, 13, 7391, 276, 8912, 540, 26796, 1330, 1635, 198, 198, 2, 198, 2, 1345, 1747, 24704, 14402, 198, ...
4.248366
306