text
stringlengths
0
1.05M
meta
dict
from fov import fov import sys TEST_CASES = (""" ..... ... ....... ... ..... ....... 0 .1. ..2.. ...3... ... ..... ....... ... ....... ..... """, """ .... . ...... .. ...... ....#..... .......#.. #.5..... .....#.... ....... . ...... ...... ..... """, """ ###### # # ###..### #@...# ###### """) def parse_test_case(test_case): lines = [line.rstrip() for line in test_case.splitlines()[1:]] width = max(len(line) for line in lines) if width != min(len(line) for line in lines): lines = [line.ljust(width) for line in lines] cells = [list(line.replace('.', ' ')) for line in lines] return lines, cells def do_fov(cells): width, height = len(cells[0]), len(cells) def visit(x, y): if not (0 <= x < width and 0 <= y < height): raise IndexError('grid position (%d, %d) out of range' % (x, y)) if cells[y][x] == ' ': cells[y][x] = '.' return cells[y][x] == '#' for y, row in enumerate(cells): for x, cell in enumerate(row): if cell.isdigit() or cell == '@': fov(x, y, 1000 if cell == '@' else int(cell), visit) def validate_result(cells, lines): return [''.join(row) for row in cells] == lines def print_fail_message(n, cells, lines): width = len(cells[0]) print 'Failed test case #%d:' % (n) print print ' %s | %s | %s' % ('RESULT'.ljust(width)[:width], 'EXPECTED'.ljust(width)[:width], 'STATUS') for row, line in zip(cells, lines): assert len(row) == width and len(line) == width for x in xrange(width): if row[x] != line[x]: status = 'Column %d differs.' % x break else: status = 'OK.' print ' %s | %s | %s' % (''.join(row), line, status) print def print_summary(failed, passed): if failed: print 'Failed %d test case(s).' % failed if passed: print 'Passed %d test case(s).' % passed def main(): failed = 0 for n, test_case in enumerate(TEST_CASES): lines, cells = parse_test_case(test_case) try: do_fov(cells) except Exception, e: print 'Exception in test case %d: %s' % (n, e) raise e if not validate_result(cells, lines): failed += 1 print_fail_message(n, cells, lines) print_summary(failed, len(TEST_CASES) - failed) return failed if __name__ == '__main__': sys.exit(main())
{ "repo_name": "elemel/python-fov", "path": "src/fov_test.py", "copies": "1", "size": "2634", "license": "mit", "hash": 1284434797091196200, "line_mean": 24.0857142857, "line_max": 68, "alpha_frac": 0.4540622627, "autogenerated": false, "ratio": 3.443137254901961, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4397199517601961, "avg_score": null, "num_lines": null }
from foxy_player_api.models import Album, Artist, Track, Cover from foxy_player.settings import COVERS_DIR from celery import shared_task,current_task import mutagen import hashlib import errno import uuid import sys import os class CoverInfo: def __init__(self, data, is_artist): self.data = data self.md5 = hashlib.md5(data).hexdigest() self.is_artist = is_artist def get(self, artist): cover = Cover.objects.filter(md5=self.md5).first() if not cover: if artist != self.is_artist: return get_default_cover() path = os.path.join(COVERS_DIR, str(uuid.uuid1()) + '.jpg') cover = Cover(md5=self.md5, path=path) cover.save() with open(cover.path, 'wb') as f: f.write(self.data) return cover def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def get_files_count(dir): count = 0 for root, dirs, files in os.walk(dir): for file in files: count += 1 return count def get_artist(tags): for tag in ('TPE1', 'TPE2'): try: return str(tags[tag]) except KeyError: pass return '' def get_album(tags): for tag in ('TALB', ): try: return str(tags[tag]) except KeyError: pass return '' def get_title(tags): for tag in ('TIT2', 'TIT3', 'TIT1'): try: return str(tags[tag]) except KeyError: pass return '' def get_cover(tags): for tag in ('APIC', 'APIC:'): if tag in tags: is_artist = tags[tag].type in (mutagen.id3.PictureType.ARTIST, mutagen.id3.PictureType.BAND, mutagen.id3.PictureType.BAND_LOGOTYPE, mutagen.id3.PictureType.COMPOSER, mutagen.id3.PictureType.LEAD_ARTIST, mutagen.id3.PictureType.PUBLISHER_LOGOTYPE) return CoverInfo(tags[tag].data, is_artist) return None def get_default_cover(): default_cover_path = os.path.join(COVERS_DIR, 'default.png') hash_md5 = hashlib.md5() with open(default_cover_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) default_cover = Cover.objects.filter(md5=hash_md5.hexdigest()).first() if not default_cover: default_cover = Cover(md5=hash_md5.hexdigest(), path=default_cover_path) default_cover.save() return default_cover def process_audio_file(counter, file_type, file_path): artist_s = get_artist(file_type.tags) album_s = get_album(file_type.tags) title_s = get_title(file_type.tags) cover_info = get_cover(file_type.tags) if not title_s: base = os.path.basename(file_path) title_s = os.path.splitext(base)[0] if not artist_s: artist_s = 'Unknown' if not album_s: album_s = 'Unknown' #if not artist_s or not album_s or not title_s: # logger.error('{} ERROR: Unable to read all tags[{}]: {}'.format(counter, (artist_s, album_s, title_s), '; '.join(key for key in file_type.tags))) artist_obj = Artist.objects.filter(name=artist_s).first() if artist_obj is None: artist_obj = Artist(name=artist_s, cover=cover_info.get(True)) artist_obj.save() album_obj = Album.objects.filter(artist=artist_obj, name=album_s).first() if album_obj is None: album_obj = Album(name=album_s, artist=artist_obj, cover=cover_info.get(False)) album_obj.save() track_obj = Track.objects.filter(title=title_s, album=album_obj).first() if track_obj is None: track_obj = Track(title=title_s, album=album_obj, path=file_path, duration=file_type.info.length) track_obj.save() return '{} Added audio file: {} - {} - {}'.format(counter, artist_s, album_s, title_s) else: return '{} Skip audio file (already in database): {} - {} - {}'.format(counter, artist_s, album_s, title_s) @shared_task def scan_music_collection(folder): current = 0 count = get_files_count(folder) log = [] def update_log(data): log.append(data) current_task.update_state(state='PROGRESS', meta={'log': log}) # validate tracks for track in Track.objects.all(): if not os.path.exists(track.path): update_log('Track {} not found. Removing database record...'.format(track.path)) track.delete() for album in Album.objects.all(): if Track.objects.filter(album=album).count() == 0: update_log('Album {} has no tracks. Removing database record...'.format(album.name)) album.delete() for artist in Artist.objects.all(): if Album.objects.filter(artist=artist).count() == 0: update_log('Artist {} has no albums. Removing database record...'.format(artist.name)) artist.delete() for cover in Cover.objects.all(): if not os.path.exists(cover.path): update_log('Cover {} not found. Removing database record...'.format(cover.path)) cover.delete() elif Album.objects.filter(cover=cover).count() == 0 and Artist.objects.filter(cover=cover).count() == 0: update_log('Cover {} has no references. Removing file and database record...'.format(cover.path)) os.remove(cover.path) cover.delete() for root, dirs, files in os.walk(folder): for file in files: file_path = os.path.join(root, file) current += 1 counter = '[{}/{}]'.format(current, count) try: f = mutagen.File(file_path) if f is None: update_log('{} Skipping file: {}'.format(counter, file_path)) continue update_log(process_audio_file(counter, f, file_path)) except mutagen.MutagenError as ex: update_log('{} Error occured on file {}: {}'.format(counter, file_path, ex)) continue return log
{ "repo_name": "TheCheshireFox/foxy-player", "path": "foxy_player/foxy_player_api/tasks.py", "copies": "1", "size": "6129", "license": "apache-2.0", "hash": 514895653605067140, "line_mean": 33.8238636364, "line_max": 258, "alpha_frac": 0.5956926089, "autogenerated": false, "ratio": 3.5022857142857142, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4597978323185714, "avg_score": null, "num_lines": null }
from foxy_player_api.models import Album, Artist, Track, Cover from foxy_player.settings import COVERS_DIR import logging import mutagen import hashlib import errno import uuid import sys import os logger = logging.getLogger('SCAN') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(logging.Formatter('%(levelname)s|%(name)s|%(asctime)s| %(message)s')) logger.addHandler(ch) class CoverInfo: def __init__(self, data, is_artist): self.data = data self.md5 = hashlib.md5(data).hexdigest() self.is_artist = is_artist def get(self, artist): cover = Cover.objects.filter(md5=self.md5).first() if not cover: if artist != self.is_artist: return get_default_cover() path = os.path.join(COVERS_DIR, str(uuid.uuid1()) + '.jpg') cover = Cover(md5=self.md5, path=path) cover.save() with open(cover.path, 'wb') as f: f.write(self.data) return cover def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def get_files_count(dir): count = 0 for root, dirs, files in os.walk(dir): for file in files: count += 1 return count def get_artist(tags): for tag in ('TPE1', 'TPE2'): try: return str(tags[tag]) except KeyError: pass return '' def get_album(tags): for tag in ('TALB', ): try: return str(tags[tag]) except KeyError: pass return '' def get_title(tags): for tag in ('TIT2', 'TIT3', 'TIT1'): try: return str(tags[tag]) except KeyError: pass return '' def get_cover(tags): for tag in ('APIC', 'APIC:'): if tag in tags: is_artist = tags[tag].type in (mutagen.id3.PictureType.ARTIST, mutagen.id3.PictureType.BAND, mutagen.id3.PictureType.BAND_LOGOTYPE, mutagen.id3.PictureType.COMPOSER, mutagen.id3.PictureType.LEAD_ARTIST, mutagen.id3.PictureType.PUBLISHER_LOGOTYPE) return CoverInfo(tags[tag].data, is_artist) return None def get_default_cover(): default_cover_path = os.path.join(COVERS_DIR, 'default.png') hash_md5 = hashlib.md5() with open(default_cover_path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) default_cover = Cover.objects.filter(md5=hash_md5.hexdigest()).first() if not default_cover: default_cover = Cover(md5=hash_md5.hexdigest(), path=default_cover_path) default_cover.save() return default_cover def process_audio_file(counter, file_type, file_path): artist_s = get_artist(file_type.tags) album_s = get_album(file_type.tags) title_s = get_title(file_type.tags) cover_info = get_cover(file_type.tags) if not title_s: base = os.path.basename(file_path) title_s = os.path.splitext(base)[0] if not artist_s: artist_s = 'Unknown' if not album_s: album_s = 'Unknown' if not artist_s or not album_s or not title_s: logger.error('{} ERROR: Unable to read all tags[{}]: {}'.format(counter, (artist_s, album_s, title_s), '; '.join(key for key in file_type.tags))) artist_obj = Artist.objects.filter(name=artist_s).first() if artist_obj is None: artist_obj = Artist(name=artist_s, cover=cover_info.get(True)) artist_obj.save() album_obj = Album.objects.filter(artist=artist_obj, name=album_s).first() if album_obj is None: album_obj = Album(name=album_s, artist=artist_obj, cover=cover_info.get(False)) album_obj.save() track_obj = Track.objects.filter(title=title_s, album=album_obj).first() if track_obj is None: track_obj = Track(title=title_s, album=album_obj, path=file_path, duration=file_type.info.length) track_obj.save() logger.info('{} Added audio file: {} - {} - {}'.format(counter, artist_s, album_s, title_s)) else: logger.info('{} Skip audio file (already in database): {} - {} - {}'.format(counter, artist_s, album_s, title_s)) def scan(folder): current = 0 count = get_files_count(folder) for root, dirs, files in os.walk(folder): for file in files: file_path = os.path.join(root, file) current += 1 counter = '[{}/{}]'.format(current, count) try: f = mutagen.File(file_path) except mutagen.mp3.HeaderNotFoundError as ex: logger.error('{} Error occured on file {}: {}'.format(counter, file_path, ex)) continue if f is None: logger.info('{} Skipping file: {}'.format(counter, file_path)) continue process_audio_file(counter, f, file_path) if __name__ == "__main__": scan(sys.argv[0])
{ "repo_name": "TheCheshireFox/foxy-player", "path": "foxy_player/foxy_player_api/scanner.py", "copies": "1", "size": "5037", "license": "apache-2.0", "hash": 6405423530287085000, "line_mean": 31.2884615385, "line_max": 258, "alpha_frac": 0.5989676395, "autogenerated": false, "ratio": 3.3737441393168117, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9459093740551021, "avg_score": 0.0027236076531580353, "num_lines": 156 }
from foyer.atomtyper import ( Element, NeighborCount, NeighborsAtLeast, NeighborsExactly, Whitelist, Blacklist, check_atom, InWhitelist) from foyer.chemical_groups import benzene, dioxolane13 # -------------- # # House of rules # # -------------- # @Element('O') @NeighborCount(2) @NeighborsExactly('H', 2) @Whitelist(111) def opls_111(atom): """O TIP3P Water """ return True @Element('H') @NeighborCount(1) @NeighborsExactly(111, 1) @Whitelist(112) def opls_112(atom): """H TIP3P Water """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 1) @NeighborsExactly('H', 3) #@NeighborsExactly('Si', 1) @Whitelist(135) def opls_135(atom): """alkane CH3 """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 2) @NeighborsExactly('H', 2) @Whitelist(136) def opls_136(atom): """alkane CH2 """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 3) @NeighborsExactly('H', 1) @Whitelist(137) def opls_137(atom): """alkane CH """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('H', 4) @Whitelist(138) def opls_138(atom): """alkane CH4 """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 4) @Whitelist(139) def opls_139(atom): """alkane C """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(140) def opls_140(atom): """alkane H """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 3) @Whitelist(141) def opls_141(atom): """alkene C (R2-C=) """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly('H', 1) @Whitelist(142) def opls_142(atom): """alkene C (RH-C=) """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 1) @NeighborsExactly('H', 2) @Whitelist(143) def opls_143(atom): """alkene C (H2-C=) """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(144) @Blacklist(140) def opls_144(atom): """alkene H (H-C=) """ # Make sure that the carbon is an alkene carbon. rule_ids = [141, 142, 143] return check_atom(atom.neighbors[0], rule_ids) @Element('C') @NeighborCount(3) @NeighborsAtLeast('C', 2) @Whitelist(145) @Blacklist([141, 142]) def opls_145(atom): """Benzene C - 12 site JACS,112,4768-90. Use #145B for biphenyl """ return benzene(atom) @Element('C') @NeighborCount(3) @NeighborsExactly('C', 3) @NeighborsExactly('145', 3) @Whitelist('145B') @Blacklist([145]) def opls_145B(atom): """Biphenyl C1 """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly(145, 1) @Whitelist(146) @Blacklist([140, 144]) def opls_146(atom): """Benzene H - 12 site. """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 1) @NeighborsExactly(145, 1) @NeighborsExactly('H', 3) @Whitelist(148) @Blacklist(135) def opls_148(atom): """C: CH3, toluene """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 2) @NeighborsExactly(145, 1) @NeighborsExactly('H', 2) @Whitelist(149) @Blacklist(136) def opls_149(atom): """C: CH2, ethyl benzene """ return True @Element('O') @NeighborCount(2) @NeighborsExactly('H', 1) @Whitelist(154) def opls_154(atom): """all-atom O: mono alcohols """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('O', 1) @NeighborsExactly(154, 1) @Whitelist(155) def opls_155(atom): """all-atom H(O): mono alcohols, OP(=O)2 """ return True @Element('O') @NeighborCount(2) @NeighborsExactly('C', 2) @NeighborsExactly(145, 1) @Whitelist(179) @Blacklist(180) def opls_179(atom): """O: anisole """ return True @Element('O') @NeighborCount(2) @NeighborsExactly('C', 2) @Whitelist(180) def opls_180(atom): """O: dialkyl ether """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('H', 3) @NeighborsExactly('O', 1) @Whitelist(181) def opls_181(atom): """C(H3OR): methyl ether """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(185) @Blacklist([140, 144]) def opls_185(atom): """H(COR): alpha H ether """ rule_ids = [181, 182, 183, 184] return check_atom(atom.neighbors[0], rule_ids) @Element('C') @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly(145, 2) @NeighborsExactly('O', 1) @Whitelist(199) @Blacklist(145) def opls_199(atom): """C(O,Me): anisole """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('O', 1) @NeighborsExactly(154, 1) @NeighborsExactly('C', 1) @NeighborsExactly(145, 1) @NeighborsExactly('H', 2) @Whitelist(218) def opls_218(atom): """C in CH2OH - benzyl alcohols """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 3) @NeighborsExactly(218, 1) @NeighborsExactly(145, 2) @Whitelist(221) @Blacklist([145, '145B']) def opls_221(atom): """C(CH2OH) - benzyl alcohols """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 1) @NeighborsExactly(145, 1) @NeighborsExactly('H', 1) @NeighborsExactly('O', 1) @NeighborsExactly(278, 1) @Whitelist(232) def opls_232(atom): """C: C=0 in benzaldehyde, acetophenone (CH) """ return True @Element('C') @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly(145, 1) @NeighborsExactly('O', 1) @NeighborsExactly(278, 1) @Whitelist(233) @Blacklist(145) def opls_233(atom): """C: C=0 in acetophenone (CMe) """ return True @Element('C') @InWhitelist(145) @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly('CL', 1) @Whitelist(263) @Blacklist(145) def opls_263(atom): """C(Cl) chlorobenzene """ return True @Element('CL') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(264) def opls_264(atom): """Cl chlorobenzene """ return benzene(atom.neighbors[0]) @Element('O') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(278) def opls_278(atom): """AA O: aldehyde """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) #@NeighborsExactly(277, 1) @Whitelist(279) @Blacklist(140) def opls_279(atom): """AA H-alpha in aldehyde & formamide """ # TODO: 232 needs to blacklist 277 return check_atom(atom.neighbors[0], [232, 277]) #return True @Element('O') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly(233, 1) @Whitelist(281) @Blacklist(278) def opls_281(atom): """AA O: ketone """ return True @Element('N') @NeighborCount(4) @Whitelist(288) def opls_288(atom): """N (R4N+) JPC,90,2174 (1986) """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('N', 1) @NeighborsExactly('H', 3) @Whitelist(291) def opls_291(atom): """C in CH3NH3+ """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('N', 1) @NeighborsExactly('C', 1) @NeighborsExactly('H', 2) @Whitelist(292) def opls_292(atom): """C in RCH2NH3+ """ return True @Element('P') @NeighborCount(4) @NeighborsExactly('O', 4) @Whitelist(440) def opls_440(atom): """P in Me2PO4-, Me2PO4H """ return True @Element('O') @NeighborCount(1) @NeighborsExactly('P', 1) @Whitelist(441) def opls_441(atom): """O= in Me2PO4-, Me2PO4H """ # TODO: check validity of using this for -CH2-O-P(=O)(-O^-)-O-CH2- return True @Element('O') @NeighborCount(2) @NeighborsExactly('P', 1) @NeighborsExactly('C', 1) @Whitelist(442) def opls_442(atom): """OMe in Me2PO4-, Me2PO4H dimethylphosphate """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('O', 1) @NeighborsExactly(442, 1) @NeighborsAtLeast('H', 2) @Whitelist(443) def opls_443(atom): """C in Me2PO4-, Me2PO4H dimethylphosphate """ # TODO: check validity of using this for -CH2-O-P(=O)(-O^-)-O-CH2- return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly(443, 1) @Whitelist(444) @Blacklist([140, 144]) def opls_444(atom): """H in Me2PO4-, Me2PO4H 6-31+G* CHELPG """ # TODO: check validity of using this for -CH2-O-P(=O)(-O^-)-O-CH2- return True @Element('C') @NeighborCount(3) @NeighborsExactly('O', 2) @NeighborsExactly('C', 1) @Whitelist(465) def opls_465(atom): """AA C: esters - for R on C=O use #280-#282 """ return True @Element('O') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly(465, 1) @Whitelist(466) @Blacklist(278) def opls_466(atom): """AA =O: esters """ return True @Element('O') @NeighborCount(2) @NeighborsExactly('C', 2) @NeighborsAtLeast(465, 1) @Whitelist(467) @Blacklist([179, 180]) def opls_467(atom): """AA -OR: ester """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('H', 3) @NeighborsExactly('O', 1) @NeighborsAtLeast(467, 1) @Whitelist(468) def opls_468(atom): """methoxy C in esters - see also #490-#492 """ return True @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly(490, 1) @Whitelist(469) @Blacklist(140) def opls_469(atom): """methoxy Hs in esters """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 1) @NeighborsExactly('O', 1) @NeighborsExactly(467, 1) @NeighborsExactly('H', 2) @Whitelist(490) def opls_490(atom): """C(H2OS) ethyl ester """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 3) @NeighborsExactly(145, 1) @NeighborsExactly('H', 1) @Whitelist(515) @Blacklist(137) def opls_515(atom): """all-atom C: CH, isopropyl benzene """ return True @Element('C') @InWhitelist('145') @NeighborCount(3) @NeighborsExactly('C', 3) @NeighborsExactly('725', 1) @Whitelist(724) @Blacklist([145, 221]) def opls_724(atom): """C(CF3) trifluoromethylbenzene """ return True @Element('C') @NeighborCount(4) @NeighborsExactly('C', 1) @NeighborsExactly('145', 1) @NeighborsExactly('F', 3) @Whitelist(725) def opls_725(atom): """CF3 trifluoromethylbenzene """ return True @Element('F') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly('725', 1) @Whitelist(726) def opls_726(atom): """F trifluoromethylbenzene """ return True @Element('N') @NeighborCount(3) @NeighborsExactly('O', 2) @NeighborsExactly('C', 1) @Whitelist(760) def opls_760(atom): """N in nitro R-NO2 """ return True @Element('O') @NeighborCount(1) @NeighborsExactly('N', 1) @Whitelist(761) def opls_761(atom): """O in nitro R-NO2 """ return True @Element('C') @InWhitelist('145') @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly('N', 1) @NeighborsExactly('760', 1) @Whitelist(768) @Blacklist(145) def opls_768(atom): """C(NO2) nitrobenzene """ return True @Element('O') @NeighborCount(1) @NeighborsExactly('C', 1) @Whitelist(771) @Blacklist(278) def opls_771(atom): """propylene carbonate O """ if dioxolane13(atom.neighbors[0]): for neighbors_neighbor in atom.neighbors[0].neighbors: if neighbors_neighbor.name != 'O': return False else: return True return False @Element('C') @NeighborCount(3) @NeighborsExactly('O', 3) @Whitelist(772) def opls_772(atom): """propylene carbonate C=O """ return dioxolane13(atom) @Element('O') @NeighborCount(2) @NeighborsExactly('C', 2) @Whitelist(773) @Blacklist([467, 180]) def opls_773(atom): """propylene carbonate OS """ return dioxolane13(atom) @Element('C') @NeighborCount(4) @NeighborsExactly('C', 1) @NeighborsExactly('O', 1) @NeighborsExactly('H', 2) @Whitelist(774) @Blacklist([218, 490]) def opls_774(atom): """propylene carbonate C in CH2 """ return dioxolane13(atom) @Element('H') @NeighborCount(1) @NeighborsExactly('C', 1) @NeighborsExactly('774', 1) @Whitelist(777) @Blacklist(140) def opls_777(atom): """propylene carbonate H in CH2 """ return True @Element('C') @InWhitelist(145) @NeighborCount(3) @NeighborsExactly('C', 2) @NeighborsExactly('N', 1) @Whitelist(916) @Blacklist(145) def opls_916(atom): """C(NH2) aniline """ return True @Element('Si') @NeighborCount(4) @NeighborsExactly('C', 2) @NeighborsExactly('O', 2) @Whitelist(1000) def opls_1000(atom): """OMCTS Si fudged""" return True @Element('O') @NeighborCount(2) @NeighborsExactly('Si', 2) @Whitelist(1001) def opls_1001(atom): """OMCTS O fudged""" return True def get_opls_fn(name): """Get the full path to a file used to validate the OPLS-aa atomtyper. In the mbuild source distribution, these files are in ``opls_validation``. Args: name (str): Name of the file to load. """ import os from pkg_resources import resource_filename fn = resource_filename('mbuild', os.path.join('..', 'opls_validation', name)) if not os.path.exists(fn): raise ValueError('Sorry! {} does not exists. If you just ' 'added it, you\'ll have to re-install'.format(fn)) return fn if __name__ == "__main__": import mbuild as mb from foyer.atomtyper import find_atomtypes from foyer.forcefield import prepare_atoms # m = Methane() # m = Ethane() # m = mb.load(get_opls_fn('isopropane.pdb')) # m = mb.load(get_opls_fn('cyclohexane.pdb')) # m = mb.load(get_opls_fn('neopentane.pdb')) m = mb.load(get_opls_fn('benzene.pdb')) # m = mb.load(get_opls_fn('1-propene.pdb')) # m = mb.load(get_opls_fn('biphenyl.pdb')) traj = m.to_trajectory() prepare_atoms(traj.top) find_atomtypes(traj.top._atoms, forcefield='OPLS-AA') for i, a in enumerate(traj.top._atoms): print("Atom name={}, opls_type={}".format(a.name, a.atomtype))
{ "repo_name": "Jonestj1/foyer", "path": "foyer/oplsaa/rules.py", "copies": "1", "size": "13563", "license": "mit", "hash": 8349115432062241000, "line_mean": 18.1028169014, "line_max": 78, "alpha_frac": 0.6475705965, "autogenerated": false, "ratio": 2.637176745090414, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8782345238339098, "avg_score": 0.00048042065026323514, "num_lines": 710 }
from fparser.Fortran2003 import * from fparser.api import get_reader from nose.tools import assert_equal def assertRaises(exc, cls, s): try: cls(s) raise AssertionError('Expected %s but got nothing' % exc) except exc: pass ############################################################################### ############################### SECTION 2 #################################### ############################################################################### def test_Program(): # R201 cls = Program reader = get_reader('''\ subroutine foo end subroutine foo subroutine bar end ''') a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a), 'SUBROUTINE foo\nEND SUBROUTINE foo\nSUBROUTINE bar\nEND SUBROUTINE bar') reader = get_reader('''\ subroutine foo (*) end subroutine foo ''') a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a), 'SUBROUTINE foo(*)\nEND SUBROUTINE foo') def test_Specification_Part(): # R204 reader = get_reader('''\ integer a''') cls = Specification_Part a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a),'INTEGER :: a') assert_equal(repr(a), "Specification_Part(Type_Declaration_Stmt(Intrinsic_Type_Spec('INTEGER', None), None, Entity_Decl(Name('a'), None, None, None)))") a = cls(get_reader(''' type a end type a type b end type b ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'TYPE :: a\nEND TYPE a\nTYPE :: b\nEND TYPE b') ############################################################################### ############################### SECTION 3 #################################### ############################################################################### def test_Name(): # R304 a = Name('a') assert isinstance(a,Name),`a` a = Name('a2') assert isinstance(a,Name),`a` a = Designator('a') assert isinstance(a,Name),`a` a = Constant('a') assert isinstance(a,Name),`a` a = Expr('a') assert isinstance(a,Name),`a` def test_Literal_Constant(): # R305 cls = Constant a = cls('.false.') assert isinstance(a, Logical_Literal_Constant), `a` assert str(a)=='.FALSE.' def test_Literal_Constant(): # R306 cls = Literal_Constant a = cls('.false.') assert isinstance(a, Logical_Literal_Constant), `a` assert str(a)=='.FALSE.' ############################################################################### ############################### SECTION 4 #################################### ############################################################################### def test_Type_Param_Value(): # 402 cls = Type_Param_Value a = cls('*') assert isinstance(a,cls),`a` assert_equal(str(a),'*') assert_equal(repr(a),"Type_Param_Value('*')") a = cls(':') assert isinstance(a,cls),`a` assert_equal(str(a),':') a = cls('1+2') assert isinstance(a,Level_2_Expr),`a` assert_equal(str(a),'1 + 2') def test_Intrinsic_Type_Spec(): # R403 cls = Intrinsic_Type_Spec a = cls('INTEGER') assert isinstance(a,cls),`a` assert_equal(str(a),'INTEGER') assert_equal(repr(a), "Intrinsic_Type_Spec('INTEGER', None)") a = cls('Integer*2') assert isinstance(a,cls),`a` assert_equal(str(a),'INTEGER*2') a = cls('real*2') assert isinstance(a,cls),`a` assert_equal(str(a),'REAL*2') a = cls('logical*2') assert isinstance(a,cls),`a` assert_equal(str(a),'LOGICAL*2') a = cls('complex*2') assert isinstance(a,cls),`a` assert_equal(str(a),'COMPLEX*2') a = cls('character*2') assert isinstance(a,cls),`a` assert_equal(str(a),'CHARACTER*2') a = cls('double complex') assert isinstance(a,cls),`a` assert_equal(str(a),'DOUBLE COMPLEX') a = cls('double precision') assert isinstance(a,cls),`a` assert_equal(str(a),'DOUBLE PRECISION') def test_Kind_Selector(): # R404 cls = Kind_Selector a = cls('(1)') assert isinstance(a,cls),`a` assert_equal(str(a),'(KIND = 1)') assert_equal(repr(a),"Kind_Selector('(', Int_Literal_Constant('1', None), ')')") a = cls('(kind=1+2)') assert isinstance(a,cls),`a` assert_equal(str(a),'(KIND = 1 + 2)') a = cls('* 1') assert isinstance(a,cls),`a` assert_equal(str(a),'*1') def test_Signed_Int_Literal_Constant(): # R405 cls = Signed_Int_Literal_Constant a = cls('1') assert isinstance(a,cls),`a` assert_equal(str(a),'1') assert_equal(repr(a),"%s('1', None)" % (cls.__name__)) a = cls('+ 21_2') assert isinstance(a,cls),`a` assert_equal(str(a),'+21_2') assert_equal(repr(a),"%s('+21', '2')" % (cls.__name__)) a = cls('-21_SHORT') assert isinstance(a,cls),`a` assert_equal(str(a),'-21_SHORT') a = cls('21_short') assert isinstance(a,cls),`a` assert_equal(str(a),'21_short') a = cls('+1976354279568241_8') assert isinstance(a,cls),`a` assert_equal(str(a),'+1976354279568241_8') def test_Int_Literal_Constant(): # R406 cls = Int_Literal_Constant a = cls('1') assert isinstance(a,cls),`a` assert_equal(str(a),'1') assert_equal(repr(a),"%s('1', None)" % (cls.__name__)) a = cls('21_2') assert isinstance(a,cls),`a` assert_equal(str(a),'21_2') assert_equal(repr(a),"%s('21', '2')" % (cls.__name__)) a = cls('21_SHORT') assert isinstance(a,cls),`a` assert_equal(str(a),'21_SHORT') a = cls('21_short') assert isinstance(a,cls),`a` assert_equal(str(a),'21_short') a = cls('1976354279568241_8') assert isinstance(a,cls),`a` assert_equal(str(a),'1976354279568241_8') def test_Binary_Constant(): # R412 cls = Boz_Literal_Constant bcls = Binary_Constant a = cls('B"01"') assert isinstance(a,bcls),`a` assert_equal(str(a),'B"01"') assert_equal(repr(a),"%s('B\"01\"')" % (bcls.__name__)) def test_Octal_Constant(): # R413 cls = Boz_Literal_Constant ocls = Octal_Constant a = cls('O"017"') assert isinstance(a,ocls),`a` assert_equal(str(a),'O"017"') assert_equal(repr(a),"%s('O\"017\"')" % (ocls.__name__)) def test_Hex_Constant(): # R414 cls = Boz_Literal_Constant zcls = Hex_Constant a = cls('Z"01A"') assert isinstance(a,zcls),`a` assert_equal(str(a),'Z"01A"') assert_equal(repr(a),"%s('Z\"01A\"')" % (zcls.__name__)) def test_Signed_Real_Literal_Constant(): # R416 cls = Signed_Real_Literal_Constant a = cls('12.78') assert isinstance(a,cls),`a` assert_equal(str(a),'12.78') assert_equal(repr(a),"%s('12.78', None)" % (cls.__name__)) a = cls('+12.78_8') assert isinstance(a,cls),`a` assert_equal(str(a),'+12.78_8') assert_equal(repr(a),"%s('+12.78', '8')" % (cls.__name__)) a = cls('- 12.') assert isinstance(a,cls),`a` assert_equal(str(a),'-12.') a = cls('1.6E3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E3') a = cls('+1.6E3_8') assert isinstance(a,cls),`a` assert_equal(str(a),'+1.6E3_8') a = cls('1.6D3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6D3') a = cls('-1.6E-3') assert isinstance(a,cls),`a` assert_equal(str(a),'-1.6E-3') a = cls('1.6E+3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E+3') a = cls('3E4') assert isinstance(a,cls),`a` assert_equal(str(a),'3E4') a = cls('.123') assert isinstance(a,cls),`a` assert_equal(str(a),'.123') a = cls('+1.6E-3') assert isinstance(a,cls),`a` assert_equal(str(a),'+1.6E-3') a = cls('10.9E7_QUAD') assert isinstance(a,cls),`a` assert_equal(str(a),'10.9E7_QUAD') a = cls('-10.9e-17_quad') assert isinstance(a,cls),`a` assert_equal(str(a),'-10.9E-17_quad') def test_Real_Literal_Constant(): # R417 cls = Real_Literal_Constant a = cls('12.78') assert isinstance(a,cls),`a` assert_equal(str(a),'12.78') assert_equal(repr(a),"%s('12.78', None)" % (cls.__name__)) a = cls('12.78_8') assert isinstance(a,cls),`a` assert_equal(str(a),'12.78_8') assert_equal(repr(a),"%s('12.78', '8')" % (cls.__name__)) a = cls('12.') assert isinstance(a,cls),`a` assert_equal(str(a),'12.') a = cls('1.6E3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E3') a = cls('1.6E3_8') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E3_8') a = cls('1.6D3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6D3') a = cls('1.6E-3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E-3') a = cls('1.6E+3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E+3') a = cls('3E4') assert isinstance(a,cls),`a` assert_equal(str(a),'3E4') a = cls('.123') assert isinstance(a,cls),`a` assert_equal(str(a),'.123') a = cls('1.6E-3') assert isinstance(a,cls),`a` assert_equal(str(a),'1.6E-3') a = cls('10.9E7_QUAD') assert isinstance(a,cls),`a` assert_equal(str(a),'10.9E7_QUAD') a = cls('10.9e-17_quad') assert isinstance(a,cls),`a` assert_equal(str(a),'10.9E-17_quad') a = cls('0.0D+0') assert isinstance(a,cls),`a` assert_equal(str(a),'0.0D+0') def test_Char_Selector(): # R424 cls = Char_Selector a = cls('(len=2, kind=8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = 2, KIND = 8)') assert_equal(repr(a),"Char_Selector(Int_Literal_Constant('2', None), Int_Literal_Constant('8', None))") a = cls('(2, kind=8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = 2, KIND = 8)') a = cls('(2, 8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = 2, KIND = 8)') a = cls('(kind=8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(KIND = 8)') a = cls('(kind=8,len=2)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = 2, KIND = 8)') def test_Complex_Literal_Constant(): # R421 cls = Complex_Literal_Constant a = cls('(1.0, -1.0)') assert isinstance(a,cls),`a` assert_equal(str(a),'(1.0, -1.0)') assert_equal(repr(a),"Complex_Literal_Constant(Signed_Real_Literal_Constant('1.0', None), Signed_Real_Literal_Constant('-1.0', None))") a = cls('(3,3.1E6)') assert isinstance(a,cls),`a` assert_equal(str(a),'(3, 3.1E6)') a = cls('(4.0_4, 3.6E7_8)') assert isinstance(a,cls),`a` assert_equal(str(a),'(4.0_4, 3.6E7_8)') a = cls('( 0., PI)') assert isinstance(a,cls),`a` assert_equal(str(a),'(0., PI)') def test_Type_Name(): # C424 cls = Type_Name a = cls('a') assert isinstance(a,cls),`a` assert_equal(str(a),'a') assert_equal(repr(a),"Type_Name('a')") assertRaises(NoMatchError,cls,'integer') assertRaises(NoMatchError,cls,'doubleprecision') def test_Length_Selector(): # R425 cls = Length_Selector a = cls('( len = *)') assert isinstance(a,cls),`a` assert_equal(str(a),'(LEN = *)') assert_equal(repr(a),"Length_Selector('(', Type_Param_Value('*'), ')')") a = cls('*2,') assert isinstance(a,cls),`a` assert_equal(str(a),'*2') def test_Char_Length(): # R426 cls = Char_Length a = cls('(1)') assert isinstance(a,cls),`a` assert_equal(str(a),'(1)') assert_equal(repr(a),"Char_Length('(', Int_Literal_Constant('1', None), ')')") a = cls('1') assert isinstance(a,Int_Literal_Constant),`a` assert_equal(str(a),'1') a = cls('(*)') assert isinstance(a,cls),`a` assert_equal(str(a),'(*)') a = cls('(:)') assert isinstance(a,cls),`a` assert_equal(str(a),'(:)') def test_Char_Literal_Constant(): # R427 cls = Char_Literal_Constant a = cls('NIH_"DO"') assert isinstance(a,cls),`a` assert_equal(str(a),'NIH_"DO"') assert_equal(repr(a),'Char_Literal_Constant(\'"DO"\', \'NIH\')') a = cls("'DO'") assert isinstance(a,cls),`a` assert_equal(str(a),"'DO'") assert_equal(repr(a),'Char_Literal_Constant("\'DO\'", None)') a = cls("'DON''T'") assert isinstance(a,cls),`a` assert_equal(str(a),"'DON''T'") a = cls('"DON\'T"') assert isinstance(a,cls),`a` assert_equal(str(a),'"DON\'T"') a = cls('""') assert isinstance(a,cls),`a` assert_equal(str(a),'""') a = cls("''") assert isinstance(a,cls),`a` assert_equal(str(a),"''") a = cls('"hey ha(ada)\t"') assert isinstance(a,cls),`a` assert_equal(str(a),'"hey ha(ada)\t"') def test_Logical_Literal_Constant(): # R428 cls = Logical_Literal_Constant a = cls('.TRUE.') assert isinstance(a,cls),`a` assert_equal(str(a),'.TRUE.') assert_equal(repr(a),"%s('.TRUE.', None)" % (cls.__name__)) a = cls('.True.') assert isinstance(a,cls),`a` assert_equal(str(a),'.TRUE.') a = cls('.FALSE.') assert isinstance(a,cls),`a` assert_equal(str(a),'.FALSE.') a = cls('.false.') assert isinstance(a,cls),`a` assert_equal(str(a),'.FALSE.') a = cls('.TRUE._HA') assert isinstance(a,cls),`a` assert_equal(str(a),'.TRUE._HA') def test_Derived_Type_Stmt(): # R430 cls = Derived_Type_Stmt a = cls('type a') assert isinstance(a, cls),`a` assert_equal(str(a),'TYPE :: a') assert_equal(repr(a),"Derived_Type_Stmt(None, Type_Name('a'), None)") a = cls('type ::a(b,c)') assert isinstance(a, cls),`a` assert_equal(str(a),'TYPE :: a(b, c)') a = cls('type, private, abstract::a(b,c)') assert isinstance(a, cls),`a` assert_equal(str(a),'TYPE, PRIVATE, ABSTRACT :: a(b, c)') def test_Type_Name(): # C423 cls = Type_Name a = cls('a') assert isinstance(a, cls),`a` assert_equal(str(a),'a') assert_equal(repr(a),"Type_Name('a')") def test_Type_Attr_Spec(): # R431 cls = Type_Attr_Spec a = cls('abstract') assert isinstance(a, cls),`a` assert_equal(str(a),'ABSTRACT') assert_equal(repr(a),"Type_Attr_Spec('ABSTRACT', None)") a = cls('bind (c )') assert isinstance(a, cls),`a` assert_equal(str(a),'BIND(C)') a = cls('extends(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'EXTENDS(a)') a = cls('private') assert isinstance(a, Access_Spec),`a` assert_equal(str(a),'PRIVATE') def test_End_Type_Stmt(): # R433 cls = End_Type_Stmt a = cls('end type') assert isinstance(a, cls),`a` assert_equal(str(a),'END TYPE') assert_equal(repr(a),"End_Type_Stmt('TYPE', None)") a = cls('end type a') assert isinstance(a, cls),`a` assert_equal(str(a),'END TYPE a') def test_Sequence_Stmt(): # R434 cls = Sequence_Stmt a = cls('sequence') assert isinstance(a, cls),`a` assert_equal(str(a),'SEQUENCE') assert_equal(repr(a),"Sequence_Stmt('SEQUENCE')") def test_Type_Param_Def_Stmt(): # R435 cls = Type_Param_Def_Stmt a = cls('integer ,kind :: a') assert isinstance(a, cls),`a` assert_equal(str(a),'INTEGER, KIND :: a') assert_equal(repr(a),"Type_Param_Def_Stmt(None, Type_Param_Attr_Spec('KIND'), Name('a'))") a = cls('integer*2 ,len :: a=3, b=2+c') assert isinstance(a, cls),`a` assert_equal(str(a),'INTEGER*2, LEN :: a = 3, b = 2 + c') def test_Type_Param_Decl(): # R436 cls = Type_Param_Decl a = cls('a=2') assert isinstance(a, cls),`a` assert_equal(str(a),'a = 2') assert_equal(repr(a),"Type_Param_Decl(Name('a'), '=', Int_Literal_Constant('2', None))") a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') def test_Type_Param_Attr_Spec(): # R437 cls = Type_Param_Attr_Spec a = cls('kind') assert isinstance(a, cls),`a` assert_equal(str(a),'KIND') assert_equal(repr(a),"Type_Param_Attr_Spec('KIND')") a = cls('len') assert isinstance(a, cls),`a` assert_equal(str(a),'LEN') def test_Component_Attr_Spec(): # R441 cls = Component_Attr_Spec a = cls('pointer') assert isinstance(a, cls),`a` assert_equal(str(a),'POINTER') assert_equal(repr(a),"Component_Attr_Spec('POINTER')") a = cls('allocatable') assert isinstance(a, cls),`a` assert_equal(str(a),'ALLOCATABLE') a = cls('dimension(a)') assert isinstance(a, Dimension_Component_Attr_Spec),`a` assert_equal(str(a),'DIMENSION(a)') a = cls('private') assert isinstance(a, Access_Spec),`a` assert_equal(str(a),'PRIVATE') def test_Component_Decl(): # R442 cls = Component_Decl a = cls('a(1)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)') assert_equal(repr(a),"Component_Decl(Name('a'), Explicit_Shape_Spec(None, Int_Literal_Constant('1', None)), None, None)") a = cls('a(1)*(3)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)*(3)') a = cls('a(1)*(3) = 2') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)*(3) = 2') a = cls('a(1) => NULL') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1) => NULL') def test_Proc_Component_Def_Stmt(): # R445 cls = Proc_Component_Def_Stmt a = cls('procedure(), pointer :: a') assert isinstance(a, cls),`a` assert_equal(str(a),'PROCEDURE(), POINTER :: a') a = cls('procedure(real*8), pointer, pass(n) :: a, b') assert isinstance(a, cls),`a` assert_equal(str(a),'PROCEDURE(REAL*8), POINTER, PASS(n) :: a, b') def test_Type_Bound_Procedure_Part(): # R448 cls = Type_Bound_Procedure_Part a = cls(get_reader(''' contains procedure, pass :: length => point_length ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'CONTAINS\nPROCEDURE, PASS :: length => point_length') def test_Proc_Binding_Stmt(): # R450 cls = Proc_Binding_Stmt a = cls('procedure, pass :: length => point_length') assert isinstance(a, Specific_Binding),`a` assert_equal(str(a),'PROCEDURE, PASS :: length => point_length') def test_Specific_Binding(): # R451 cls = Specific_Binding a = cls('procedure, pass :: length => point_length') assert isinstance(a, cls),`a` assert_equal(str(a),'PROCEDURE, PASS :: length => point_length') def test_Generic_Binding(): # R452 cls = Generic_Binding a = cls('generic :: a => b') assert isinstance(a, cls),`a` assert_equal(str(a),'GENERIC :: a => b') a = cls('generic, private :: read(formatted) => b,c') assert isinstance(a, cls),`a` assert_equal(str(a),'GENERIC, PRIVATE :: READ(FORMATTED) => b, c') def test_Final_Binding(): # R454 cls = Final_Binding a = cls('final a, b') assert isinstance(a,cls),`a` assert_equal(str(a),'FINAL :: a, b') assert_equal(repr(a),"Final_Binding('FINAL', Final_Subroutine_Name_List(',', (Name('a'), Name('b'))))") a = cls('final::a') assert isinstance(a,cls),`a` assert_equal(str(a),'FINAL :: a') def test_Derived_Type_Spec(): # R455 cls = Derived_Type_Spec a = cls('a(b)') assert isinstance(a,cls),`a` assert_equal(str(a),'a(b)') assert_equal(repr(a),"Derived_Type_Spec(Type_Name('a'), Name('b'))") a = cls('a(b,c,g=1)') assert isinstance(a,cls),`a` assert_equal(str(a),'a(b, c, g = 1)') a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') a = cls('a()') assert isinstance(a,cls),`a` assert_equal(str(a),'a()') def test_Type_Param_Spec(): # R456 cls = Type_Param_Spec a = cls('a=1') assert isinstance(a,cls),`a` assert_equal(str(a),'a = 1') assert_equal(repr(a),"Type_Param_Spec(Name('a'), Int_Literal_Constant('1', None))") a = cls('k=a') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a') a = cls('k=:') assert isinstance(a,cls),`a` assert_equal(str(a),'k = :') def test_Type_Param_Spec_List(): # R456-list cls = Type_Param_Spec_List a = cls('a,b') assert isinstance(a,cls),`a` assert_equal(str(a),'a, b') assert_equal(repr(a),"Type_Param_Spec_List(',', (Name('a'), Name('b')))") a = cls('a') assert isinstance(a,Name),`a` a = cls('k=a,c,g=1') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a, c, g = 1') def test_Structure_Constructor_2(): # R457.b cls = Structure_Constructor_2 a = cls('k=a') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a') assert_equal(repr(a),"Structure_Constructor_2(Name('k'), Name('a'))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Structure_Constructor(): # R457 cls = Structure_Constructor a = cls('t()') assert isinstance(a,cls),`a` assert_equal(str(a),'t()') assert_equal(repr(a),"Structure_Constructor(Type_Name('t'), None)") a = cls('t(s=1, a)') assert isinstance(a,cls),`a` assert_equal(str(a),'t(s = 1, a)') a = cls('a=k') assert isinstance(a,Structure_Constructor_2),`a` assert_equal(str(a),'a = k') assert_equal(repr(a),"Structure_Constructor_2(Name('a'), Name('k'))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Component_Spec(): # R458 cls = Component_Spec a = cls('k=a') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a') assert_equal(repr(a),"Component_Spec(Name('k'), Name('a'))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') a = cls('a % b') assert isinstance(a, Proc_Component_Ref),`a` assert_equal(str(a),'a % b') a = cls('s =a % b') assert isinstance(a, Component_Spec),`a` assert_equal(str(a),'s = a % b') def test_Component_Spec_List(): # R458-list cls = Component_Spec_List a = cls('k=a, b') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a, b') assert_equal(repr(a),"Component_Spec_List(',', (Component_Spec(Name('k'), Name('a')), Name('b')))") a = cls('k=a, c') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a, c') def test_Enum_Def(): # R460 cls = Enum_Def a = cls(get_reader(''' enum, bind(c) enumerator :: red = 4, blue = 9 enumerator yellow end enum ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'ENUM, BIND(C)\n ENUMERATOR :: red = 4, blue = 9\n ENUMERATOR :: yellow\nEND ENUM') def test_Enum_Def_Stmt(): # R461 cls = Enum_Def_Stmt a = cls('enum, bind(c)') assert isinstance(a,cls),`a` assert_equal(str(a),'ENUM, BIND(C)') def test_Array_Constructor(): # R465 cls = Array_Constructor a = cls('(/a/)') assert isinstance(a,cls),`a` assert_equal(str(a),'(/a/)') assert_equal(repr(a),"Array_Constructor('(/', Name('a'), '/)')") a = cls('[a]') assert isinstance(a,cls),`a` assert_equal(str(a),'[a]') assert_equal(repr(a),"Array_Constructor('[', Name('a'), ']')") a = cls('[integer::a]') assert isinstance(a,cls),`a` assert_equal(str(a),'[INTEGER :: a]') a = cls('[integer::a,b]') assert isinstance(a,cls),`a` assert_equal(str(a),'[INTEGER :: a, b]') def test_Ac_Spec(): # R466 cls = Ac_Spec a = cls('integer ::') assert isinstance(a,cls),`a` assert_equal(str(a),'INTEGER ::') assert_equal(repr(a),"Ac_Spec(Intrinsic_Type_Spec('INTEGER', None), None)") a = cls('integer :: a,b') assert isinstance(a,cls),`a` assert_equal(str(a),'INTEGER :: a, b') a = cls('a,b') assert isinstance(a,Ac_Value_List),`a` assert_equal(str(a),'a, b') a = cls('integer :: a, (a, b, n = 1, 5)') assert isinstance(a,cls),`a` assert_equal(str(a),'INTEGER :: a, (a, b, n = 1, 5)') def test_Ac_Value_List(): # R469-list cls = Ac_Value_List a = cls('a, b') assert isinstance(a,cls),`a` assert_equal(str(a),'a, b') assert_equal(repr(a),"Ac_Value_List(',', (Name('a'), Name('b')))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Ac_Implied_Do(): # R470 cls = Ac_Implied_Do a = cls('( a, b, n = 1, 5 )') assert isinstance(a,cls),`a` assert_equal(str(a),'(a, b, n = 1, 5)') assert_equal(repr(a),"Ac_Implied_Do(Ac_Value_List(',', (Name('a'), Name('b'))), Ac_Implied_Do_Control(Name('n'), [Int_Literal_Constant('1', None), Int_Literal_Constant('5', None)]))") def test_Ac_Implied_Do_Control(): # R471 cls = Ac_Implied_Do_Control a = cls('n = 3, 5') assert isinstance(a,cls),`a` assert_equal(str(a),'n = 3, 5') assert_equal(repr(a),"Ac_Implied_Do_Control(Name('n'), [Int_Literal_Constant('3', None), Int_Literal_Constant('5', None)])") a = cls('n = 3+1, 5, 1') assert isinstance(a,cls),`a` assert_equal(str(a),'n = 3 + 1, 5, 1') ############################################################################### ############################### SECTION 5 #################################### ############################################################################### def test_Type_Declaration_Stmt(): # R501 cls = Type_Declaration_Stmt a = cls('integer a') assert isinstance(a, cls),`a` assert_equal(str(a), 'INTEGER :: a') assert_equal(repr(a), "Type_Declaration_Stmt(Intrinsic_Type_Spec('INTEGER', None), None, Entity_Decl(Name('a'), None, None, None))") a = cls('integer ,dimension(2):: a*3') assert isinstance(a, cls),`a` assert_equal(str(a), 'INTEGER, DIMENSION(2) :: a*3') a = cls('real a') assert isinstance(a, cls),`a` assert_equal(str(a), 'REAL :: a') assert_equal(repr(a), "Type_Declaration_Stmt(Intrinsic_Type_Spec('REAL', None), None, Entity_Decl(Name('a'), None, None, None))") a = cls('REAL A( LDA, * ), B( LDB, * )') assert isinstance(a, cls),`a` assert_equal(str(a), 'REAL :: A(LDA, *), B(LDB, *)') a = cls('DOUBLE PRECISION ALPHA, BETA') assert isinstance(a, cls),`a` assert_equal(str(a), 'DOUBLE PRECISION :: ALPHA, BETA') a = cls('logical,parameter:: T=.true.') assert isinstance(a, cls),`a` assert_equal(str(a), 'LOGICAL, PARAMETER :: T = .TRUE.') a = cls('character(n),private:: x(n)') assert isinstance(a, cls),`a` assert_equal(str(a), 'CHARACTER(LEN = n), PRIVATE :: x(n)') a = cls('character(lenmax),private:: x(n)') assert isinstance(a, cls),`a` assert_equal(str(a), 'CHARACTER(LEN = lenmax), PRIVATE :: x(n)') def test_Declaration_Type_Spec(): # R502 cls = Declaration_Type_Spec a = cls('Integer*2') assert isinstance(a, Intrinsic_Type_Spec),`a` assert_equal(str(a), 'INTEGER*2') a = cls('type(foo)') assert isinstance(a, cls),`a` assert_equal(str(a), 'TYPE(foo)') assert_equal(repr(a), "Declaration_Type_Spec('TYPE', Type_Name('foo'))") def test_Attr_Spec(): # R503 cls = Attr_Spec a = cls('allocatable') assert isinstance(a, cls),`a` assert_equal(str(a), 'ALLOCATABLE') a = cls('dimension(a)') assert isinstance(a, Dimension_Attr_Spec),`a` assert_equal(str(a),'DIMENSION(a)') def test_Dimension_Attr_Spec(): # R503.d cls = Dimension_Attr_Spec a = cls('dimension(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'DIMENSION(a)') assert_equal(repr(a),"Dimension_Attr_Spec('DIMENSION', Explicit_Shape_Spec(None, Name('a')))") def test_Intent_Attr_Spec(): # R503.f cls = Intent_Attr_Spec a = cls('intent(in)') assert isinstance(a, cls),`a` assert_equal(str(a),'INTENT(IN)') assert_equal(repr(a),"Intent_Attr_Spec('INTENT', Intent_Spec('IN'))") def test_Entity_Decl(): # 504 cls = Entity_Decl a = cls('a(1)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)') assert_equal(repr(a),"Entity_Decl(Name('a'), Explicit_Shape_Spec(None, Int_Literal_Constant('1', None)), None, None)") a = cls('a(1)*(3)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)*(3)') a = cls('a(1)*(3) = 2') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)*(3) = 2') a = cls('a = 2') assert isinstance(a, cls),`a` assert_equal(str(a),'a = 2') a = cls('a=2') assert isinstance(a, cls),`a` assert_equal(str(a),'a = 2') a = cls('a = "abc "') assert isinstance(a, cls),`a` assert_equal(str(a),'a = "abc "') a = cls('a = .true.') assert isinstance(a, cls),`a` assert_equal(str(a),'a = .TRUE.') def test_Target_Entity_Decl(): cls = Target_Entity_Decl a = cls('a(1)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(1)') assert_equal(repr(a),"Target_Entity_Decl(Name('a'), Explicit_Shape_Spec(None, Int_Literal_Constant('1', None)), None, None)") def test_Access_Spec(): # R508 cls = Access_Spec a = cls('private') assert isinstance(a, cls),`a` assert_equal(str(a),'PRIVATE') assert_equal(repr(a),"Access_Spec('PRIVATE')") a = cls('public') assert isinstance(a, cls),`a` assert_equal(str(a),'PUBLIC') def test_Language_Binding_Spec(): # R509 cls = Language_Binding_Spec a = cls('bind(c)') assert isinstance(a, cls),`a` assert_equal(str(a),'BIND(C)') assert_equal(repr(a),'Language_Binding_Spec(None)') a = cls('bind(c, name="hey")') assert isinstance(a, cls),`a` assert_equal(str(a),'BIND(C, NAME = "hey")') def test_Explicit_Shape_Spec(): # R511 cls = Explicit_Shape_Spec a = cls('a:b') assert isinstance(a, cls),`a` assert_equal(str(a),'a : b') assert_equal(repr(a),"Explicit_Shape_Spec(Name('a'), Name('b'))") a = cls('a') assert isinstance(a, cls),`a` assert_equal(str(a),'a') def test_Upper_Bound(): # R513 cls = Upper_Bound a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') assertRaises(NoMatchError,cls,'*') def test_Assumed_Shape_Spec(): # R514 cls = Assumed_Shape_Spec a = cls(':') assert isinstance(a, cls),`a` assert_equal(str(a),':') assert_equal(repr(a),'Assumed_Shape_Spec(None, None)') a = cls('a :') assert isinstance(a, cls),`a` assert_equal(str(a),'a :') def test_Deferred_Shape_Spec(): # R515 cls = Deferred_Shape_Spec a = cls(':') assert isinstance(a, cls),`a` assert_equal(str(a),':') assert_equal(repr(a),'Deferred_Shape_Spec(None, None)') def test_Assumed_Size_Spec(): # R516 cls = Assumed_Size_Spec a = cls('*') assert isinstance(a, cls),`a` assert_equal(str(a),'*') assert_equal(repr(a),'Assumed_Size_Spec(None, None)') a = cls('1:*') assert isinstance(a, cls),`a` assert_equal(str(a),'1 : *') a = cls('a,1:*') assert isinstance(a, cls),`a` assert_equal(str(a),'a, 1 : *') a = cls('a:b,1:*') assert isinstance(a, cls),`a` assert_equal(str(a),'a : b, 1 : *') def test_Access_Stmt(): # R518 cls = Access_Stmt a = cls('private') assert isinstance(a, cls),`a` assert_equal(str(a),'PRIVATE') assert_equal(repr(a),"Access_Stmt('PRIVATE', None)") a = cls('public a,b') assert isinstance(a, cls),`a` assert_equal(str(a),'PUBLIC :: a, b') a = cls('public ::a') assert isinstance(a, cls),`a` assert_equal(str(a),'PUBLIC :: a') def test_Data_Stmt(): #R524 cls = Data_Stmt a = cls('DATA YOURNAME % AGE, YOURNAME % NAME / 35, "FRED BROWN" /') assert isinstance(a, cls),`a` assert_equal(str(a),'DATA YOURNAME % AGE, YOURNAME % NAME / 35, "FRED BROWN" /') a = cls('DATA NAME / "JOHN DOE" / MILES / 10 * 0 /') assert isinstance(a, cls),`a` assert_equal(str(a),'DATA NAME / "JOHN DOE" /, MILES / 10 * 0 /') a = cls('DATA MYNAME / PERSON (21, \'JOHN SMITH\') /') assert isinstance(a, cls),`a` assert_equal(str(a),'DATA MYNAME / PERSON(21, \'JOHN SMITH\') /') def test_Data_Stmt_Set(): #R525 cls = Data_Stmt_Set a = cls('MILES / 10 * "2/3" /') assert isinstance(a, cls),`a` assert_equal(str(a),'MILES / 10 * "2/3" /') def test_Data_Implied_Do(): # R527 cls = Data_Implied_Do a = cls('((SKEW (K, J), J = 1, K), K = 1, 100)') assert isinstance(a, cls),`a` assert_equal(str(a),'((SKEW(K, J), J = 1, K), K = 1, 100)') # R531-R534 are trivial def test_Dimension_Stmt(): # R535 cls = Dimension_Stmt a = cls('dimension :: a(5)') assert isinstance(a, cls),`a` assert_equal(str(a),'DIMENSION :: a(5)') assert_equal(repr(a),"Dimension_Stmt([(Name('a'), Explicit_Shape_Spec(None, Int_Literal_Constant('5', None)))])") a = cls('dimension a(n,m), b(:), c(2:n), d(*), e(n, 2:*)') assert isinstance(a, cls),`a` assert_equal(str(a),'DIMENSION :: a(n, m), b(:), c(2 : n), d(*), e(n, 2 : *)') def test_Intent_Stmt(): # R536 cls = Intent_Stmt a = cls('intent(in) :: a') assert isinstance(a, cls),`a` assert_equal(str(a),'INTENT(IN) :: a') assert_equal(repr(a),"Intent_Stmt(Intent_Spec('IN'), Name('a'))") a = cls('intent(out) a, b') assert isinstance(a, cls),`a` assert_equal(str(a),'INTENT(OUT) :: a, b') assert_equal(repr(a),"Intent_Stmt(Intent_Spec('OUT'), Dummy_Arg_Name_List(',', (Name('a'), Name('b'))))") def test_Optional_Stmt(): # R537 cls = Optional_Stmt a = cls('optional :: a') assert isinstance(a, cls),`a` assert_equal(str(a),'OPTIONAL :: a') assert_equal(repr(a),"Optional_Stmt('OPTIONAL', Name('a'))") a = cls('optional :: a, b, c') assert isinstance(a, cls),`a` assert_equal(str(a),'OPTIONAL :: a, b, c') assert_equal(repr(a),"Optional_Stmt('OPTIONAL', Dummy_Arg_Name_List(',', (Name('a'), Name('b'), Name('c'))))") def test_Parameter_Stmt(): # R538 cls = Parameter_Stmt a = cls('parameter(a=1)') assert isinstance(a, cls),`a` assert_equal(str(a),'PARAMETER(a = 1)') assert_equal(repr(a),"Parameter_Stmt('PARAMETER', Named_Constant_Def(Name('a'), Int_Literal_Constant('1', None)))") a = cls('parameter(a=1, b=a+2)') assert isinstance(a, cls),`a` assert_equal(str(a),'PARAMETER(a = 1, b = a + 2)') a = cls('PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 )') assert isinstance(a, cls),`a` assert_equal(str(a),'PARAMETER(ONE = 1.0D+0, ZERO = 0.0D+0)') def test_Named_Constant_Def(): # R539 cls = Named_Constant_Def a = cls('a=1') assert isinstance(a, cls),`a` assert_equal(str(a),'a = 1') assert_equal(repr(a),"Named_Constant_Def(Name('a'), Int_Literal_Constant('1', None))") def test_Pointer_Stmt(): # R540 cls = Pointer_Stmt a = cls('pointer a(:), b') assert isinstance(a, cls),`a` assert_equal(str(a),'POINTER :: a(:), b') assert_equal(repr(a),"Pointer_Stmt('POINTER', Pointer_Decl_List(',', (Pointer_Decl(Name('a'), Deferred_Shape_Spec(None, None)), Name('b'))))") def test_Pointer_Decl(): # R541 cls = Pointer_Decl a = cls('a(:)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(:)') assert_equal(repr(a),"Pointer_Decl(Name('a'), Deferred_Shape_Spec(None, None))") a = cls('a(:,:)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(:, :)') def test_Protected_Stmt(): # R542 cls = Protected_Stmt a = cls('protected a,b') assert isinstance(a, cls),`a` assert_equal(str(a),'PROTECTED :: a, b') assert_equal(repr(a),"Protected_Stmt('PROTECTED', Entity_Name_List(',', (Name('a'), Name('b'))))") a = cls('protected ::a') assert isinstance(a, cls),`a` assert_equal(str(a),'PROTECTED :: a') assert_equal(repr(a),"Protected_Stmt('PROTECTED', Name('a'))") def test_Save_Stmt(): # R543 cls = Save_Stmt a = cls('save') assert isinstance(a, cls),`a` assert_equal(str(a),'SAVE') assert_equal(repr(a),"Save_Stmt('SAVE', None)") a = cls('save a, b') assert isinstance(a, cls),`a` assert_equal(str(a),'SAVE :: a, b') assert_equal(repr(a),"Save_Stmt('SAVE', Saved_Entity_List(',', (Name('a'), Name('b'))))") a = cls('save :: /a/ , b') assert isinstance(a, cls),`a` assert_equal(str(a),'SAVE :: /a/, b') assert_equal(repr(a),"Save_Stmt('SAVE', Saved_Entity_List(',', (Saved_Entity('/', Name('a'), '/'), Name('b'))))") def test_Saved_Entity(): # R544 cls = Saved_Entity a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') assert_equal(repr(a),"Name('a')") a = cls('/a/') assert isinstance(a, cls),`a` assert_equal(str(a),'/a/') assert_equal(repr(a),"Saved_Entity('/', Name('a'), '/')") # R545 is trivial def test_Target_Stmt(): # R546 cls = Target_Stmt a = cls('target a, b(1000, 1000)') assert isinstance(a, cls),`a` assert_equal(str(a),'TARGET :: a, b(1000, 1000)') a = cls('target :: a, c') assert isinstance(a, cls),`a` assert_equal(str(a),'TARGET :: a, c') def test_Value_Stmt(): # R547 cls = Value_Stmt a = cls('value a') assert isinstance(a, cls),`a` assert_equal(str(a),'VALUE :: a') a = cls('value:: a, c') assert isinstance(a, cls),`a` assert_equal(str(a),'VALUE :: a, c') def test_Volatile_Stmt(): # R548 cls = Volatile_Stmt a = cls('volatile a') assert isinstance(a, cls),`a` assert_equal(str(a),'VOLATILE :: a') a = cls('volatile :: a, c') assert isinstance(a, cls),`a` assert_equal(str(a),'VOLATILE :: a, c') def test_Implicit_Stmt(): # R549 cls = Implicit_Stmt a = cls('implicitnone') assert isinstance(a, cls),`a` assert_equal(str(a),'IMPLICIT NONE') assert_equal(repr(a),"Implicit_Stmt('NONE')") a = cls('implicit real(a-d), double precision(r-t,x), type(a) (y-z)') assert isinstance(a, cls),`a` assert_equal(str(a),'IMPLICIT REAL(A - D), DOUBLE PRECISION(R - T, X), TYPE(a)(Y - Z)') def test_Implicit_Spec(): # R550 cls = Implicit_Spec a = cls('integer (a-z)') assert isinstance(a, cls),`a` assert_equal(str(a),'INTEGER(A - Z)') assert_equal(repr(a),"Implicit_Spec(Intrinsic_Type_Spec('INTEGER', None), Letter_Spec('A', 'Z'))") a = cls('double complex (r,d-g)') assert isinstance(a, cls),`a` assert_equal(str(a),'DOUBLE COMPLEX(R, D - G)') def test_Letter_Spec(): # R551 cls = Letter_Spec a = cls('a-z') assert isinstance(a, cls),`a` assert_equal(str(a),'A - Z') assert_equal(repr(a),"Letter_Spec('A', 'Z')") a = cls('d') assert isinstance(a, cls),`a` assert_equal(str(a),'D') def test_Namelist_Stmt(): # R552 cls = Namelist_Stmt a = cls('namelist / nlist / a') assert isinstance(a, cls),`a` assert_equal(str(a),'NAMELIST /nlist/ a') a = cls('namelist / nlist / a, /mlist/ b,c /klist/ d,e') assert_equal(str(a),'NAMELIST /nlist/ a, /mlist/ b, c, /klist/ d, e') def test_Equivalence_Stmt(): # R554 cls = Equivalence_Stmt a = cls('equivalence (a, b ,z)') assert isinstance(a, cls),`a` assert_equal(str(a),'EQUIVALENCE(a, b, z)') assert_equal(repr(a),"Equivalence_Stmt('EQUIVALENCE', Equivalence_Set(Name('a'), Equivalence_Object_List(',', (Name('b'), Name('z')))))") a = cls('equivalence (a, b ,z),(b,l)') assert isinstance(a, cls),`a` assert_equal(str(a),'EQUIVALENCE(a, b, z), (b, l)') def test_Common_Stmt(): # R557 cls = Common_Stmt a = cls('common a') assert isinstance(a, cls),`a` assert_equal(str(a),'COMMON // a') assert_equal(repr(a),"Common_Stmt([(None, Name('a'))])") a = cls('common // a,b') assert isinstance(a, cls),`a` assert_equal(str(a),'COMMON // a, b') a = cls('common /name/ a,b') assert isinstance(a, cls),`a` assert_equal(str(a),'COMMON /name/ a, b') a = cls('common /name/ a,b(4,5) // c, /ljuks/ g(2)') assert isinstance(a, cls),`a` assert_equal(str(a),'COMMON /name/ a, b(4, 5) // c /ljuks/ g(2)') def test_Common_Block_Object(): # R558 cls = Common_Block_Object a = cls('a(2)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(2)') assert_equal(repr(a),"Common_Block_Object(Name('a'), Explicit_Shape_Spec(None, Int_Literal_Constant('2', None)))") a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') ############################################################################### ############################### SECTION 6 #################################### ############################################################################### def test_Substring(): # R609 cls = Substring a = cls('a(:)') assert isinstance(a, cls),`a` assert_equal(str(a),'a(:)') assert_equal(repr(a),"Substring(Name('a'), Substring_Range(None, None))") a = cls('a(1:2)') assert isinstance(a,cls),`a` assert_equal(str(a),'a(1 : 2)') assert_equal(repr(a),"Substring(Name('a'), Substring_Range(Int_Literal_Constant('1', None), Int_Literal_Constant('2', None)))") def test_Substring_Range(): # R611 cls = Substring_Range a = cls(':') assert isinstance(a, cls),`a` assert_equal(str(a),':') assert_equal(repr(a),"Substring_Range(None, None)") a = cls('a+1:') assert isinstance(a, cls),`a` assert_equal(str(a),'a + 1 :') a = cls('a+1: c/foo(g)') assert isinstance(a, cls),`a` assert_equal(str(a),'a + 1 : c / foo(g)') a = cls('a:b') assert isinstance(a,cls),`a` assert_equal(str(a),'a : b') assert_equal(repr(a),"Substring_Range(Name('a'), Name('b'))") a = cls('a:') assert isinstance(a,cls),`a` assert_equal(str(a),'a :') a = cls(':b') assert isinstance(a,cls),`a` assert_equal(str(a),': b') def test_Data_Ref(): # R612 cls = Data_Ref a = cls('a%b') assert isinstance(a,cls),`a` assert_equal(str(a),'a % b') assert_equal(repr(a),"Data_Ref('%', (Name('a'), Name('b')))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Part_Ref(): # R613 cls = Part_Ref a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') def test_Type_Param_Inquiry(): # R615 cls = Type_Param_Inquiry a = cls('a % b') assert isinstance(a,cls),`a` assert_equal(str(a),'a % b') assert_equal(repr(a),"Type_Param_Inquiry(Name('a'), '%', Name('b'))") def test_Array_Section(): # R617 cls = Array_Section a = cls('a(:)') assert isinstance(a,cls),`a` assert_equal(str(a),'a(:)') assert_equal(repr(a),"Array_Section(Name('a'), Substring_Range(None, None))") a = cls('a(2:)') assert isinstance(a,cls),`a` assert_equal(str(a),'a(2 :)') def test_Section_Subscript(): # R619 cls = Section_Subscript a = cls('1:2') assert isinstance(a, Subscript_Triplet),`a` assert_equal(str(a),'1 : 2') a = cls('zzz') assert isinstance(a, Name),`a` assert_equal(str(a),'zzz') def test_Section_Subscript_List(): # R619-list cls = Section_Subscript_List a = cls('a,2') assert isinstance(a,cls),`a` assert_equal(str(a),'a, 2') assert_equal(repr(a),"Section_Subscript_List(',', (Name('a'), Int_Literal_Constant('2', None)))") a = cls('::1') assert isinstance(a,Subscript_Triplet),`a` assert_equal(str(a),': : 1') a = cls('::1, 3') assert isinstance(a,cls),`a` assert_equal(str(a),': : 1, 3') def test_Subscript_Triplet(): # R620 cls = Subscript_Triplet a = cls('a:b') assert isinstance(a,cls),`a` assert_equal(str(a),'a : b') assert_equal(repr(a),"Subscript_Triplet(Name('a'), Name('b'), None)") a = cls('a:b:1') assert isinstance(a,cls),`a` assert_equal(str(a),'a : b : 1') a = cls(':') assert isinstance(a,cls),`a` assert_equal(str(a),':') a = cls('::5') assert isinstance(a,cls),`a` assert_equal(str(a),': : 5') a = cls(':5') assert isinstance(a,cls),`a` assert_equal(str(a),': 5') a = cls('a+1 :') assert isinstance(a,cls),`a` assert_equal(str(a),'a + 1 :') def test_Allocate_Stmt(): # R623 cls = Allocate_Stmt a = cls('allocate(a,b)') assert isinstance(a,cls),`a` assert_equal(str(a),'ALLOCATE(a, b)') a = cls('allocate(real::a)') assert_equal(str(a),'ALLOCATE(REAL::a)') a = cls('allocate(real(kind=8)::a, stat=b, source=c//d)') assert_equal(str(a),'ALLOCATE(REAL(KIND = 8)::a, STAT = b, SOURCE = c // d)') def test_Alloc_Opt(): # R624 cls = Alloc_Opt a = cls('stat=a') assert isinstance(a, cls),`a` assert_equal(str(a),'STAT = a') assert_equal(repr(a),"Alloc_Opt('STAT', Name('a'))") def test_Nullify_Stmt(): # R633 cls = Nullify_Stmt a = cls('nullify (a)') assert isinstance(a, cls),`a` assert_equal(str(a),'NULLIFY(a)') assert_equal(repr(a),"Nullify_Stmt('NULLIFY', Name('a'))") a = cls('nullify (a,c)') assert isinstance(a, cls),`a` assert_equal(str(a),'NULLIFY(a, c)') def test_Deallocate_Stmt(): # R635 cls = Deallocate_Stmt a = cls('deallocate (a)') assert isinstance(a, cls),`a` assert_equal(str(a),'DEALLOCATE(a)') a = cls('deallocate (a,stat=b)') assert isinstance(a, cls),`a` assert_equal(str(a),'DEALLOCATE(a, STAT = b)') a = cls('deallocate (a,c,stat=b,errmsg=d)') assert_equal(str(a),'DEALLOCATE(a, c, STAT = b, ERRMSG = d)') ############################################################################### ############################### SECTION 7 #################################### ############################################################################### def test_Primary(): # R701 cls = Primary a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') a = cls('(a)') assert isinstance(a,Parenthesis),`a` assert_equal(str(a),'(a)') a = cls('1') assert isinstance(a,Int_Literal_Constant),`a` assert_equal(str(a),'1') a = cls('1.') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'1.') a = cls('(1, n)') assert isinstance(a,Complex_Literal_Constant),`a` assert_equal(str(a),'(1, n)') a = cls('.true.') assert isinstance(a,Logical_Literal_Constant),`a` assert_equal(str(a),'.TRUE.') a = cls('"hey a()c"') assert isinstance(a,Char_Literal_Constant),`a` assert_equal(str(a),'"hey a()c"') a = cls('b"0101"') assert isinstance(a,Binary_Constant),`a` assert_equal(str(a),'B"0101"') a = cls('o"0107"') assert isinstance(a,Octal_Constant),`a` assert_equal(str(a),'O"0107"') a = cls('z"a107"') assert isinstance(a,Hex_Constant),`a` assert_equal(str(a),'Z"A107"') a = cls('a % b') assert isinstance(a,Data_Ref),`a` assert_equal(str(a),'a % b') a = cls('a(:)') assert isinstance(a,Array_Section),`a` assert_equal(str(a),'a(:)') a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') def test_Parenthesis(): # R701.h cls = Parenthesis a = cls('(a)') assert isinstance(a,cls),`a` assert_equal(str(a),'(a)') assert_equal(repr(a),"Parenthesis('(', Name('a'), ')')") a = cls('(a+1)') assert isinstance(a,cls),`a` assert_equal(str(a),'(a + 1)') a = cls('((a))') assert isinstance(a,cls),`a` assert_equal(str(a),'((a))') a = cls('(a+(a+c))') assert isinstance(a,cls),`a` assert_equal(str(a),'(a + (a + c))') def test_Level_1_Expr(): # R702 cls = Level_1_Expr a = cls('.hey. a') assert isinstance(a,cls),`a` assert_equal(str(a),'.HEY. a') assert_equal(repr(a),"Level_1_Expr('.HEY.', Name('a'))") #assertRaises(NoMatchError,cls,'.not. a') a = cls('.false.') assert isinstance(a,Logical_Literal_Constant),`a` def test_Mult_Operand(): # R704 cls = Mult_Operand a = cls('a**b') assert isinstance(a,cls),`a` assert_equal(str(a),'a ** b') assert_equal(repr(a),"Mult_Operand(Name('a'), '**', Name('b'))") a = cls('a**2') assert isinstance(a,cls),`a` assert_equal(str(a),'a ** 2') a = cls('(a+b)**2') assert isinstance(a,cls),`a` assert_equal(str(a),'(a + b) ** 2') a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') def test_Add_Operand(): # R705 cls = Add_Operand a = cls('a*b') assert isinstance(a,cls),`a` assert_equal(str(a),'a * b') assert_equal(repr(a),"Add_Operand(Name('a'), '*', Name('b'))") a = cls('a/b') assert isinstance(a,cls),`a` assert_equal(str(a),'a / b') a = cls('a**b') assert isinstance(a,Mult_Operand),`a` assert_equal(str(a),'a ** b') a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') def test_Level_2_Expr(): # R706 cls = Level_2_Expr a = cls('a+b') assert isinstance(a,cls),`a` assert_equal(str(a),'a + b') assert_equal(repr(a),"Level_2_Expr(Name('a'), '+', Name('b'))") a = cls('a-b') assert isinstance(a,cls),`a` assert_equal(str(a),'a - b') a = cls('a+b+c') assert isinstance(a,cls),`a` assert_equal(str(a),'a + b + c') a = cls('+a') assert isinstance(a,Level_2_Unary_Expr),`a` assert_equal(str(a),'+ a') a = cls('+1') assert isinstance(a,Level_2_Unary_Expr),`a` assert_equal(str(a),'+ 1') a = cls('+a+b') assert isinstance(a,cls),`a` assert_equal(str(a),'+ a + b') a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') def test_Level_2_Unary_Expr(): cls = Level_2_Unary_Expr a = cls('+a') assert isinstance(a,cls),`a` assert_equal(str(a),'+ a') assert_equal(repr(a),"Level_2_Unary_Expr('+', Name('a'))") a = cls('-a') assert isinstance(a,cls),`a` assert_equal(str(a),'- a') a = cls('+1') assert isinstance(a,cls),`a` assert_equal(str(a),'+ 1') a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') def test_Level_3_Expr(): # R710 cls = Level_3_Expr a = cls('a//b') assert isinstance(a,cls),`a` assert_equal(str(a),'a // b') assert_equal(repr(a),"Level_3_Expr(Name('a'), '//', Name('b'))") a = cls('"a"//"b"') assert isinstance(a,cls),`a` assert_equal(str(a),'"a" // "b"') def test_Level_4_Expr(): # R712 cls = Level_4_Expr a = cls('a.eq.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .EQ. b') assert_equal(repr(a),"Level_4_Expr(Name('a'), '.EQ.', Name('b'))") a = cls('a.ne.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .NE. b') a = cls('a.lt.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .LT. b') a = cls('a.gt.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .GT. b') a = cls('a.ge.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .GE. b') a = cls('a==b') assert isinstance(a,cls),`a` assert_equal(str(a),'a == b') a = cls('a/=b') assert isinstance(a,cls),`a` assert_equal(str(a),'a /= b') a = cls('a<b') assert isinstance(a,cls),`a` assert_equal(str(a),'a < b') a = cls('a<=b') assert isinstance(a,cls),`a` assert_equal(str(a),'a <= b') a = cls('a>=b') assert isinstance(a,cls),`a` assert_equal(str(a),'a >= b') a = cls('a>b') assert isinstance(a,cls),`a` assert_equal(str(a),'a > b') def test_And_Operand(): # R714 cls = And_Operand a = cls('.not.a') assert isinstance(a,cls),`a` assert_equal(str(a),'.NOT. a') assert_equal(repr(a),"And_Operand('.NOT.', Name('a'))") def test_Or_Operand(): # R715 cls = Or_Operand a = cls('a.and.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .AND. b') assert_equal(repr(a),"Or_Operand(Name('a'), '.AND.', Name('b'))") def test_Equiv_Operand(): # R716 cls = Equiv_Operand a = cls('a.or.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .OR. b') assert_equal(repr(a),"Equiv_Operand(Name('a'), '.OR.', Name('b'))") def test_Level_5_Expr(): # R717 cls = Level_5_Expr a = cls('a.eqv.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .EQV. b') assert_equal(repr(a),"Level_5_Expr(Name('a'), '.EQV.', Name('b'))") a = cls('a.neqv.b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .NEQV. b') a = cls('a.eq.b') assert isinstance(a,Level_4_Expr),`a` assert_equal(str(a),'a .EQ. b') def test_Expr(): # R722 cls = Expr a = cls('a .op. b') assert isinstance(a,cls),`a` assert_equal(str(a),'a .OP. b') assert_equal(repr(a),"Expr(Name('a'), '.OP.', Name('b'))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') a = cls('3.e2') assert isinstance(a,Real_Literal_Constant),`a` a = cls('0.0E-1') assert isinstance(a,Real_Literal_Constant),`a` assert_equal(str(a),'0.0E-1') a = cls('123') assert isinstance(a,Int_Literal_Constant),`a` assert_equal(str(a),'123') a = cls('.false.') assert isinstance(a,Logical_Literal_Constant),`a` assert_equal(str(a),'.FALSE.') assertRaises(NoMatchError,Scalar_Int_Expr,'a,b') def test_Logical_Expr(): # R724 cls = Logical_Expr a = cls('(f0 .lt. f1) .and. abs(x1-x0) .gt. abs(x2) .or. .not. root') assert isinstance(a,Equiv_Operand),`a` assert_equal(str(a),'(f0 .LT. f1) .AND. abs(x1 - x0) .GT. abs(x2) .OR. .NOT. root') def test_Logical_Initialization_Expr(): # R733 cls = Logical_Initialization_Expr a = cls('.false.') assert isinstance(a, Logical_Literal_Constant), `a` assert str(a)=='.FALSE.' def test_Assignment_Stmt(): # R734 cls = Assignment_Stmt a = cls('a = b') assert isinstance(a, cls),`a` assert_equal(str(a),'a = b') assert_equal(repr(a),"Assignment_Stmt(Name('a'), '=', Name('b'))") a = cls('a(3:4) = b+c') assert isinstance(a, cls),`a` assert_equal(str(a),'a(3 : 4) = b + c') a = cls('a%c = b+c') assert isinstance(a, cls),`a` assert_equal(str(a),'a % c = b + c') a = cls('a = .FALSE.') assert isinstance(a, cls),`a` assert_equal(repr(a),"Assignment_Stmt(Name('a'), '=', Logical_Literal_Constant('.FALSE.', None))") a = cls('a(n)(k:m) = 5') assert isinstance(a, cls),`a` assert_equal(str(a),'a(n)(k : m) = 5') a = cls('b = a + 1 d - 8') assert isinstance(a, cls),`a` assert_equal(str(a),'b = a + 1D-8') a = cls('b = a + 1 d - 8 + 1.1e+3') assert isinstance(a, cls),`a` assert_equal(str(a),'b = a + 1D-8 + 1.1E+3') def test_Pointer_Assignment_Stmt(): # R735 cls = Pointer_Assignment_Stmt a = cls('new_node % left => current_node') assert isinstance(a, cls),`a` assert_equal(str(a),'new_node % left => current_node') a = cls('simple_name => target_structure % substruct % component') assert isinstance(a, cls),`a` assert_equal(str(a),'simple_name => target_structure % substruct % component') for stmt in '''\ PTR => NULL() ROW => MAT2D(N, :) WINDOW => MAT2D(I - 1 : I + 1, J - 1 : J + 1) POINTER_OBJECT => POINTER_FUNCTION(ARG_1, ARG_2) EVERY_OTHER => VECTOR(1 : N : 2) WINDOW2(0 :, 0 :) => MAT2D(ML : MU, NL : NU) P => BESSEL STRUCT % COMPONENT => BESSEL'''.split('\n'): a = cls(stmt) assert isinstance(a, cls),`a` assert_equal(str(a), stmt) def test_Proc_Component_Ref(): # R741 cls = Proc_Component_Ref a = cls('a % b') assert isinstance(a,cls),`a` assert_equal(str(a),'a % b') assert_equal(repr(a),"Proc_Component_Ref(Name('a'), '%', Name('b'))") def test_Where_Stmt(): # R743 cls = Where_Stmt a = cls('where (a) c=2') assert isinstance(a,cls),`a` assert_equal(str(a),'WHERE (a) c = 2') assert_equal(repr(a),"Where_Stmt(Name('a'), Assignment_Stmt(Name('c'), '=', Int_Literal_Constant('2', None)))") def test_Where_Construct(): # R745 cls = Where_Construct a = cls(get_reader(''' where (pressure <= 1.0) pressure = pressure + inc_pressure temp = temp - 5.0 elsewhere raining = .true. end where ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'WHERE (pressure <= 1.0)\n pressure = pressure + inc_pressure\n temp = temp - 5.0\nELSEWHERE\n raining = .TRUE.\nEND WHERE') a = cls(get_reader(''' where (cond1) elsewhere (cond2) end where ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'WHERE (cond1)\nELSEWHERE(cond2)\nEND WHERE') a = cls(get_reader(''' n:where (cond1) elsewhere (cond2) n elsewhere n end where n ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'n:WHERE (cond1)\nELSEWHERE(cond2) n\nELSEWHERE n\nEND WHERE n') def test_Where_Construct_Stmt(): # R745 cls = Where_Construct_Stmt a = cls('where (a)') assert isinstance(a,cls),`a` assert_equal(str(a),'WHERE (a)') assert_equal(repr(a),"Where_Construct_Stmt(Name('a'))") def test_Forall_Construct(): # R752 cls = Forall_Construct a = cls(get_reader(''' forall (i = 1:10, j = 1:10, b(i, j) /= 0.0) a(i, j) = real (i + j - 2) b(i, j) = a(i, j) + b(i, j) * real (i * j) end forall ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'FORALL(i = 1 : 10, j = 1 : 10, b(i, j) /= 0.0)\n a(i, j) = real(i + j - 2)\n b(i, j) = a(i, j) + b(i, j) * real(i * j)\nEND FORALL') a = cls(get_reader(''' n: forall (x = 1:5:2, j = 1:4) a(x, j) = j end forall n ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'n:FORALL(x = 1 : 5 : 2, j = 1 : 4)\n a(x, j) = j\nEND FORALL n') def test_Forall_Header(): # R754 cls = Forall_Header a = cls('(n=1:2, a+1)') assert isinstance(a,cls),`a` assert_equal(str(a),'(n = 1 : 2, a + 1)') a = cls('(n=1:2, m=1:x-1:z(a))') assert isinstance(a,cls),`a` assert_equal(str(a),'(n = 1 : 2, m = 1 : x - 1 : z(a))') def test_Forall_Triplet_Spec(): # R755 cls = Forall_Triplet_Spec a = cls('n = 1: 2') assert isinstance(a,cls),`a` assert_equal(str(a),'n = 1 : 2') a = cls('n = f(x): 2-b:a+1') assert isinstance(a,cls),`a` assert_equal(str(a),'n = f(x) : 2 - b : a + 1') ############################################################################### ############################### SECTION 8 #################################### ############################################################################### def test_If_Construct(): # R802 cls = If_Construct a = cls(get_reader(''' if (expr) then a = 1 end if ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'IF (expr) THEN\n a = 1\nEND IF') a = cls(get_reader(''' name: if (expr) then a = 1 end if name ''')) assert_equal(str(a),'name:IF (expr) THEN\n a = 1\nEND IF name') a = cls(get_reader(''' if (expr) then a = 1 if (expr2) then a = 2 endif a = 3 end if ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'IF (expr) THEN\n a = 1\n IF (expr2) THEN\n a = 2\n END IF\n a = 3\nEND IF') a = cls(get_reader(''' if (expr) then a = 1 else if (expr2) then a = 2 end if ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'IF (expr) THEN\n a = 1\nELSE IF (expr2) THEN\n a = 2\nEND IF') a = cls(get_reader(''' if (expr) then a = 1 else a = 2 end if ''')) assert_equal(str(a),'IF (expr) THEN\n a = 1\nELSE\n a = 2\nEND IF') a = cls(get_reader(''' if (expr) then a = 1 else if (expr2) then a = 2 else a = 3 end if ''')) assert_equal(str(a),'IF (expr) THEN\n a = 1\nELSE IF (expr2) THEN\n a = 2\nELSE\n a = 3\nEND IF') a = cls(get_reader(''' named: if (expr) then a = 1 else named a = 2 end if named ''')) assert_equal(str(a),'named:IF (expr) THEN\n a = 1\nELSE named\n a = 2\nEND IF named') a = cls(get_reader(''' named: if (expr) then a = 1 named2: if (expr2) then a = 2 end if named2 end if named ''')) assert_equal(str(a),'named:IF (expr) THEN\n a = 1\n named2:IF (expr2) THEN\n a = 2\n END IF named2\nEND IF named') a = cls(get_reader(''' if (expr) then a = 1 else if (expr2) then a = 2 else if (expr3) then a = 3 end if ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'IF (expr) THEN\n a = 1\nELSE IF (expr2) THEN\n a = 2\nELSE IF (expr3) THEN\n a = 3\nEND IF') a = cls(get_reader(''' if (dxmx .gt. 0d0) then diff = 0 do 80 k = 1, n 80 diff = max(diff,abs(xnew(k)-xin(k))) if (diff .gt. dxmx) then betx = dxmx/diff call awrit3(' broyj: max shift = %1;3g'// . ' is larger than dxmx = %1;3g. Scale by %1;3g', . ' ',80,i1mach(2),diff,dxmx,dxmx/diff) do 82 k = 1, n 82 xnew(k) = xin(k) + betx*(xnew(k)-xin(k)) endif endif ''')) def test_if_nonblock_do(): cls = If_Construct a = cls(get_reader(''' if (expr) then do 20 i = 1, 3 a = 1 do 20 j = 1, 3 a = 2 do 20 k = 1, 3 a = 3 20 rotm(i,j) = r2(j,i) endif ''')) assert isinstance(a,cls),`a` assert len(a.content)==3,`a` a = a.content[1] assert isinstance(a, Action_Term_Do_Construct),`a` assert_equal(str(a),'DO 20 , i = 1, 3\n a = 1\n DO 20 , j = 1, 3\n a = 2\n DO 20 , k = 1, 3\n a = 3\n20 rotm(i, j) = r2(j, i)') a = cls(get_reader(''' if (expr) then do 50 i = n, m, -1 50 call foo(a) endif''')) assert isinstance(a,cls),`a` assert len(a.content)==3,`a` a = a.content[1] assert isinstance(a, Action_Term_Do_Construct),`a` def test_Case_Construct(): # R808 cls = Case_Construct a = cls(get_reader(''' select case (n) case (:-1) signum = -1 case (0) signum = 0 case (1:) signum = 1 end select ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'SELECT CASE (n)\nCASE (: - 1)\n signum = - 1\nCASE (0)\n signum = 0\nCASE (1 :)\n signum = 1\nEND SELECT') def test_Case_Selector(): # R813 cls = Case_Selector a = cls('default') assert isinstance(a,cls),`a` assert_equal(str(a),'DEFAULT') a = cls('(2)') assert isinstance(a,cls),`a` assert_equal(str(a),'(2)') a = cls('(2:3, c+2:, :-a)') assert isinstance(a,cls),`a` assert_equal(str(a),'(2 : 3, c + 2 :, : - a)') def test_Associate_Construct(): # R816 cls = Associate_Construct a = cls(get_reader(''' ASSOCIATE ( Z => EXP(-(X**2+Y**2)) * COS(THETA) ) PRINT *, A+Z, A-Z END ASSOCIATE ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'ASSOCIATE(Z => EXP(- (X ** 2 + Y ** 2)) * COS(THETA))\n PRINT *, A + Z, A - Z\nEND ASSOCIATE') a = cls(get_reader(''' name:ASSOCIATE ( XC => AX%B(I,J)%C ) XC%DV = XC%DV + PRODUCT(XC%EV(1:N)) END ASSOCIATE name ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'name:ASSOCIATE(XC => AX % B(I, J) % C)\n XC % DV = XC % DV + PRODUCT(XC % EV(1 : N))\nEND ASSOCIATE name') a = cls(get_reader(''' ASSOCIATE ( W => RESULT(I,J)%W, ZX => AX%B(I,J)%D, ZY => AY%B(I,J)%D ) W = ZX*X + ZY*Y END ASSOCIATE ''')) assert_equal(str(a),'ASSOCIATE(W => RESULT(I, J) % W, ZX => AX % B(I, J) % D, ZY => AY % B(I, J) % D)\n W = ZX * X + ZY * Y\nEND ASSOCIATE') def test_Select_Type_Construct(): # R821 cls = Select_Type_Construct a = cls(get_reader(''' n:SELECT TYPE ( A => P_OR_C ) CLASS IS ( POINT ) PRINT *, A%X, A%Y ! This block gets executed TYPE IS ( POINT_3D ) PRINT *, A%X, A%Y, A%Z END SELECT n ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'n:SELECT TYPE(A=>P_OR_C)\n CLASS IS (POINT)\n PRINT *, A % X, A % Y\n TYPE IS (POINT_3D)\n PRINT *, A % X, A % Y, A % Z\nEND SELECT n') def test_Select_Type_Stmt(): # R822 cls = Select_Type_Stmt a = cls('select type(a=>b)') assert isinstance(a,cls),`a` assert_equal(str(a),'SELECT TYPE(a=>b)') a = cls('select type(a)') assert isinstance(a,cls),`a` assert_equal(str(a),'SELECT TYPE(a)') def test_Type_Guard_Stmt(): # R823 cls = Type_Guard_Stmt a = cls('type is (real*8)') assert isinstance(a,cls),`a` assert_equal(str(a),'TYPE IS (REAL*8)') a = cls('class is (mytype) name') assert isinstance(a,cls),`a` assert_equal(str(a),'CLASS IS (mytype) name') a = cls('classdefault') assert isinstance(a,cls),`a` assert_equal(str(a),'CLASS DEFAULT') def test_Block_Label_Do_Construct(): # R826_1 cls = Block_Label_Do_Construct a = cls(get_reader(''' do 12 a = 1 12 continue ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'DO 12\n a = 1\n12 CONTINUE') a = cls(get_reader(''' do 12 do 13 a = 1 13 continue 12 continue ''')) assert_equal(str(a),'DO 12\n DO 13\n a = 1\n13 CONTINUE\n12 CONTINUE') assert len(a.content)==3,`len(a.content)` assert_equal(str(a.content[1]), 'DO 13\n a = 1\n13 CONTINUE') def test_Block_Nonlabel_Do_Construct(): # # R826_2 cls = Block_Nonlabel_Do_Construct a = cls(get_reader(''' do i=1,10 a = 1 end do ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'DO , i = 1, 10\n a = 1\nEND DO') a = cls(get_reader(''' foo:do i=1,10 a = 1 end do foo ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'foo:DO , i = 1, 10\n a = 1\nEND DO foo') a = cls(get_reader(''' do j=1,2 foo:do i=1,10 a = 1 end do foo end do ''')) assert isinstance(a,cls),`a` assert_equal(str(a),'DO , j = 1, 2\n foo:DO , i = 1, 10\n a = 1\n END DO foo\nEND DO') def test_Label_Do_Stmt(): # R828 cls = Label_Do_Stmt a = cls('do 12') assert isinstance(a,cls),`a` assert_equal(str(a),'DO 12') assert_equal(repr(a),"Label_Do_Stmt(None, Label('12'), None)") def test_Nonblock_Do_Construct(): # R835 cls = Nonblock_Do_Construct a = cls(get_reader(''' do 20 i = 1, 3 20 rotm(i,j) = r2(j,i) ''')) assert isinstance(a,Action_Term_Do_Construct),`a` assert_equal(str(a),'DO 20 , i = 1, 3\n20 rotm(i, j) = r2(j, i)') a = cls(get_reader(''' do 20 i = 1, 3 k = 3 do 20 j = 1, 3 l = 3 20 rotm(i,j) = r2(j,i) ''')) assert isinstance(a,Action_Term_Do_Construct),`a` assert_equal(str(a),'DO 20 , i = 1, 3\n k = 3\n DO 20 , j = 1, 3\n l = 3\n20 rotm(i, j) = r2(j, i)') a = cls(get_reader(''' do 20 i = 1, 3 20 rotm(i,j) = r2(j,i) ''')) assert isinstance(a,Action_Term_Do_Construct),`a` assert_equal(str(a),'DO 20 , i = 1, 3\n20 rotm(i, j) = r2(j, i)') a = cls(get_reader(''' do 50 i = n, m, -1 50 call foo(a) ''')) assert isinstance(a,Action_Term_Do_Construct),`a` assert_equal(str(a),'DO 50 , i = n, m, - 1\n50 CALL foo(a)') def test_Continue_Stmt(): # R848 cls = Continue_Stmt a = cls('continue') assert isinstance(a, cls),`a` assert_equal(str(a),'CONTINUE') assert_equal(repr(a),"Continue_Stmt('CONTINUE')") def test_Stop_Stmt(): # R849 cls = Stop_Stmt a = cls('stop') assert isinstance(a, cls),`a` assert_equal(str(a),'STOP') a = cls('stop 123') assert isinstance(a, cls),`a` assert_equal(str(a),'STOP 123') a = cls('stop \'hey you\'') assert isinstance(a, cls),`a` assert_equal(str(a),"STOP 'hey you'") ############################################################################### ############################### SECTION 9 #################################### ############################################################################### def test_Io_Unit(): # R901 cls = Io_Unit a = cls('*') assert isinstance(a, cls),`a` assert_equal(str(a),'*') a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') def test_Read_Stmt(): # R910 cls = Read_Stmt a = cls('read(123)') assert isinstance(a, cls),`a` assert_equal(str(a), 'READ(UNIT = 123)') a = cls('read(123) a') assert_equal(str(a), 'READ(UNIT = 123) a') a = cls('read(123) a( 2)') assert_equal(str(a), 'READ(UNIT = 123) a(2)') a = cls('read*, a( 2), b') assert_equal(str(a), 'READ *, a(2), b') def test_Write_Stmt(): # R911 cls = Write_Stmt a = cls('write (123)"hey"') assert isinstance(a, cls),`a` assert_equal(str(a),'WRITE(UNIT = 123) "hey"') assert_equal(repr(a),'Write_Stmt(Io_Control_Spec_List(\',\', (Io_Control_Spec(\'UNIT\', Int_Literal_Constant(\'123\', None)),)), Char_Literal_Constant(\'"hey"\', None))') def test_Print_Stmt(): # R912 cls = Print_Stmt a = cls('print 123') assert isinstance(a, cls),`a` assert_equal(str(a),'PRINT 123') assert_equal(repr(a),"Print_Stmt(Label('123'), None)") a = cls('print *,"a=",a') assert isinstance(a, cls),`a` assert_equal(str(a),'PRINT *, "a=", a') def test_Io_Control_Spec(): # R913 cls = Io_Control_Spec a = cls('end=123') assert isinstance(a, cls),`a` assert_equal(str(a),'END = 123') assert_equal(repr(a),"Io_Control_Spec('END', Label('123'))") def test_Io_Control_Spec_List(): # R913-list cls = Io_Control_Spec_List a = cls('end=123') assert isinstance(a, cls),`a` assert_equal(str(a),'END = 123') assert_equal(repr(a),"Io_Control_Spec_List(',', (Io_Control_Spec('END', Label('123')),))") a = cls('123') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123') a = cls('123,*') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123, FMT = *') a = cls('123,fmt=a') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123, FMT = a') if 0: # see todo note in Io_Control_Spec_List a = cls('123,a') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123, NML = a') def test_Format(): # R914 cls = Format a = cls('*') assert isinstance(a, cls),`a` assert_equal(str(a),'*') assert_equal(repr(a),"Format('*')") a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') a = cls('123') assert isinstance(a, Label),`a` assert_equal(str(a),'123') def test_Io_Implied_Do(): # R917 cls = Io_Implied_Do a = cls('(a, i=1,2)') assert isinstance(a, cls),`a` assert_equal(str(a),'(a, i = 1, 2)') a = cls('((i+j,j=3,4,1), i=1,2)') assert isinstance(a, cls),`a` assert_equal(str(a),'((i + j, j = 3, 4, 1), i = 1, 2)') def test_Io_Implied_Do_Control(): # R919 cls = Io_Implied_Do_Control a = cls('i=1,2') assert isinstance(a, cls),`a` assert_equal(str(a),'i = 1, 2') a = cls('i=f(2),2-1,a+2') assert isinstance(a, cls),`a` assert_equal(str(a),'i = f(2), 2 - 1, a + 2') def test_Wait_Stmt(): # R921 cls = Wait_Stmt a = cls('wait (123)') assert isinstance(a, cls),`a` assert_equal(str(a),'WAIT(UNIT = 123)') def test_Wait_Spec(): # R922 cls = Wait_Spec a = cls('123') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 123') assert_equal(repr(a),"Wait_Spec('UNIT', Int_Literal_Constant('123', None))") a = cls('err=1') assert isinstance(a, cls),`a` assert_equal(str(a),'ERR = 1') def test_Backspace_Stmt(): # R923 cls = Backspace_Stmt a = cls('backspace 1') assert isinstance(a, cls),`a` assert_equal(str(a),'BACKSPACE 1') a = cls('backspace (unit=1,err=2)') assert_equal(str(a),'BACKSPACE(UNIT = 1, ERR = 2)') def test_Endfile_Stmt(): # R924 cls = Endfile_Stmt a = cls('endfile 1') assert isinstance(a, cls),`a` assert_equal(str(a),'ENDFILE 1') a = cls('endfile (unit=1,err=2)') assert_equal(str(a),'ENDFILE(UNIT = 1, ERR = 2)') def test_Rewind_Stmt(): # R925 cls = Rewind_Stmt a = cls('rewind 1') assert isinstance(a, cls),`a` assert_equal(str(a),'REWIND 1') a = cls('rewind (unit=1,err=2)') assert_equal(str(a),'REWIND(UNIT = 1, ERR = 2)') def test_Position_Spec(): # R926 cls = Position_Spec a = cls('1') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 1') a = cls('unit=1') assert_equal(str(a),'UNIT = 1') a = cls('err=2') assert_equal(str(a),'ERR = 2') a = cls('iomsg=a') assert_equal(str(a),'IOMSG = a') a = cls('iostat=a') assert_equal(str(a),'IOSTAT = a') def test_Flush_Stmt(): # R927 cls = Flush_Stmt a = cls('flush 1') assert isinstance(a, cls),`a` assert_equal(str(a),'FLUSH 1') a = cls('flush (unit=1,err=2)') assert_equal(str(a),'FLUSH(UNIT = 1, ERR = 2)') def test_Flush_Spec(): # R928 cls = Flush_Spec a = cls('1') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 1') a = cls('unit=1') assert_equal(str(a),'UNIT = 1') a = cls('err=2') assert_equal(str(a),'ERR = 2') a = cls('iomsg=a') assert_equal(str(a),'IOMSG = a') a = cls('iostat=a') assert_equal(str(a),'IOSTAT = a') def test_Inquire_Stmt(): # R929 cls = Inquire_Stmt a = cls('inquire(1,file=a)') assert isinstance(a, cls),`a` assert_equal(str(a),'INQUIRE(UNIT = 1, FILE = a)') a = cls('inquire(iolength=n) a, b') assert_equal(str(a),'INQUIRE(IOLENGTH=n) a, b') def test_Inquire_Spec(): # R930 cls = Inquire_Spec a = cls('1') assert isinstance(a, cls),`a` assert_equal(str(a),'UNIT = 1') a = cls('file=fn') assert isinstance(a, cls),`a` assert_equal(str(a),'FILE = fn') a = cls('access=a') assert isinstance(a, cls),`a` assert_equal(str(a),'ACCESS = a') ############################################################################### ############################### SECTION 10 #################################### ############################################################################### def test_Format_Stmt(): # R1001 cls = Format_Stmt a = cls('format (3f9.4)') assert isinstance(a, cls),`type(a)` assert_equal(str(a),'FORMAT(3F9.4)') a = cls("format (' ',3f9.4)") assert isinstance(a, cls),`type(a)` assert_equal(str(a),"FORMAT(' ', 3F9.4)") a = cls('format(i6,f12.6,2x,f12.6)') assert isinstance(a, cls),`type(a)` assert_equal(str(a),'FORMAT(I6, F12.6, 2X, F12.6)') a = cls("format(' Enter smth',$)") assert isinstance(a, cls),`type(a)` assert_equal(str(a),"FORMAT(' Enter smth', $)") a = cls("format(/'a' /'b')") assert isinstance(a, cls),`type(a)` assert_equal(str(a),"FORMAT(/, 'a', /, 'b')") a = cls("format('a:':' b')") assert isinstance(a, cls),`type(a)` assert_equal(str(a),"FORMAT('a:', :, ' b')") return a = cls("format('text=',' '") assert_equal(str(a),'') def test_Format_Specification(): # R1002 cls = Format_Specification a = cls('(3f9.4, 2f8.1)') assert isinstance(a, cls),`type(a)` assert_equal(str(a),'(3F9.4, 2F8.1)') a = cls("(' ', 2f8.1)") assert isinstance(a, cls),`type(a)` assert_equal(str(a),"(' ', 2F8.1)") def test_Format_Item(): # R1003 cls = Format_Item a = cls('3f9.4') assert isinstance(a, cls),`type(a)` assert_equal(str(a),'3F9.4') a = cls("' '") assert isinstance(a, Char_Literal_Constant),`type(a)` assert_equal(str(a),"' '") a = cls('i4/') assert isinstance(a, Format_Item_C1002),`type(a)` assert_equal(str(a),'I4, /') a = cls('3f12.6/') assert_equal(str(a),'3F12.6, /') a = cls("/' '") assert_equal(str(a),"/, ' '") a = cls("' '/") assert_equal(str(a),"' ', /") a = cls("' '/' '") assert_equal(str(a),"' ', /, ' '") def test_Format_Item_List(): cls = Format_Item_List a = cls('3f9.4') assert isinstance(a, Format_Item),`type(a)` assert_equal(str(a),'3F9.4') a = cls('3f9.4, 2f8.1') assert isinstance(a, Format_Item_List),`type(a)` assert_equal(str(a),'3F9.4, 2F8.1') a = cls("' ', 2f8.1") assert isinstance(a, Format_Item_List),`type(a)` assert_equal(str(a),"' ', 2F8.1") a = cls("' ', ' '") assert_equal(str(a),"' ', ' '") ############################################################################### ############################### SECTION 11 #################################### ############################################################################### def test_Main_Program(): # R1101 cls = Main_Program a = cls(get_reader(''' program a end ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'PROGRAM a\nEND PROGRAM a') a = cls(get_reader(''' program a real b b = 1 contains subroutine foo end end ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'PROGRAM a\n REAL :: b\n b = 1\n CONTAINS\n SUBROUTINE foo\n END SUBROUTINE foo\nEND PROGRAM a') a = Main_Program0(get_reader(''' end ''')) assert isinstance(a, Main_Program0),`a` assert_equal(str(a),'END PROGRAM') a = Main_Program0(get_reader(''' contains function foo() end end ''')) assert isinstance(a, Main_Program0),`a` assert_equal(str(a),'CONTAINS\nFUNCTION foo()\nEND FUNCTION\nEND PROGRAM') def test_Module(): # R1104 cls = Module a = cls(get_reader(''' module m end ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'MODULE m\nEND MODULE m') a = cls(get_reader(''' module m type a end type type b end type b end ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'MODULE m\n TYPE :: a\n END TYPE a\n TYPE :: b\n END TYPE b\nEND MODULE m') def test_Module_Subprogram_Part(): # R1107 cls = Module_Subprogram_Part a = cls(get_reader(''' contains subroutine foo(a) real a a = 1.0 end ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'CONTAINS\nSUBROUTINE foo(a)\n REAL :: a\n a = 1.0\nEND SUBROUTINE foo') def test_Use_Stmt(): # R1109 cls = Use_Stmt a = cls('use a') assert isinstance(a, cls),`a` assert_equal(str(a),'USE :: a') assert_equal(repr(a),"Use_Stmt(None, Name('a'), '', None)") a = cls('use :: a, c=>d') assert isinstance(a, cls),`a` assert_equal(str(a),'USE :: a, c => d') a = cls('use :: a, operator(.hey.)=>operator(.hoo.)') assert isinstance(a, cls),`a` assert_equal(str(a),'USE :: a, OPERATOR(.HEY.) => OPERATOR(.HOO.)') a = cls('use, intrinsic :: a, operator(.hey.)=>operator(.hoo.), c=>g') assert isinstance(a, cls),`a` assert_equal(str(a),'USE, INTRINSIC :: a, OPERATOR(.HEY.) => OPERATOR(.HOO.), c => g') def test_Module_Nature(): # R1110 cls = Module_Nature a = cls('intrinsic') assert isinstance(a, cls),`a` assert_equal(str(a),'INTRINSIC') assert_equal(repr(a),"Module_Nature('INTRINSIC')") a = cls('non_intrinsic') assert isinstance(a, cls),`a` assert_equal(str(a),'NON_INTRINSIC') def test_Rename(): # R1111 cls = Rename a = cls('a=>b') assert isinstance(a, cls),`a` assert_equal(str(a),'a => b') a = cls('operator(.foo.)=>operator(.bar.)') assert isinstance(a, cls),`a` assert_equal(str(a),'OPERATOR(.FOO.) => OPERATOR(.BAR.)') def test_Block_Data(): # R1116 cls = Block_Data a = cls(get_reader(''' block data a real b end block data ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'BLOCK DATA a\n REAL :: b\nEND BLOCK DATA a') ############################################################################### ############################### SECTION 12 #################################### ############################################################################### def test_Interface_Block(): # R1201 cls = Interface_Block a = cls(get_reader('''\ interface end interface''')) assert isinstance(a, cls),`a` assert_equal(str(a),'INTERFACE\nEND INTERFACE') a = cls(get_reader('''\ abstract interface procedure a module procedure b,c end interface ''')) assert isinstance(a, cls),`a` assert_equal(str(a),'ABSTRACT INTERFACE\n MODULE PROCEDURE a\n MODULE PROCEDURE b, c\nEND INTERFACE') def test_Interface_Specification(): # R1202 cls = Interface_Specification a = cls(get_reader(''' function foo() end ''')) assert isinstance(a, Function_Body),`a` assert_equal(str(a),'FUNCTION foo()\nEND FUNCTION') def test_Interface_Stmt(): # R1203 cls = Interface_Stmt a = cls('interface') assert isinstance(a, cls),`a` assert_equal(str(a),'INTERFACE') a = cls('interface assignment(=)') assert isinstance(a, cls),`a` assert_equal(str(a),'INTERFACE ASSIGNMENT(=)') a = cls('abstract interface') assert isinstance(a, cls),`a` assert_equal(str(a),'ABSTRACT INTERFACE') def test_End_Interface_Stmt(): # R1204 cls = End_Interface_Stmt a = cls('end interface') assert isinstance(a, cls),`a` assert_equal(str(a),'END INTERFACE') a = cls('end interface read(formatted)') assert isinstance(a, cls),`a` assert_equal(str(a),'END INTERFACE READ(FORMATTED)') a = cls('end interface assignment(=)') assert isinstance(a, cls),`a` assert_equal(str(a),'END INTERFACE ASSIGNMENT(=)') def test_Interface_Body(): # R1205 cls = Interface_Body a = cls(get_reader('''\ subroutine foo end subroutine foo ''')) assert isinstance(a, Subroutine_Body),`a` assert_equal(str(a),'SUBROUTINE foo\nEND SUBROUTINE foo') a = cls(get_reader('''\ function foo(a) result(c) real a, c end ''')) assert isinstance(a, Function_Body),`a` assert_equal(str(a),'FUNCTION foo(a) RESULT(c)\n REAL :: a, c\nEND FUNCTION') def test_Subroutine_Body(): pass def test_Function_Body(): pass def test_Procedure_Stmt(): # R1206 cls = Procedure_Stmt a = cls('module procedure a') assert isinstance(a, cls),`a` assert_equal(str(a),'MODULE PROCEDURE a') a = cls('procedure a, b') assert isinstance(a, cls),`a` assert_equal(str(a),'MODULE PROCEDURE a, b') def test_Generic_Spec(): # R1207 cls = Generic_Spec a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a), 'a') a = cls('read(formatted)') assert isinstance(a, Dtio_Generic_Spec),`a` assert_equal(str(a), 'READ(FORMATTED)') a = cls('assignment ( = )') assert isinstance(a, cls),`a` assert_equal(str(a), 'ASSIGNMENT(=)') return # TODO a = cls('operator(.foo.)') assert isinstance(a, cls),`a` assert_equal(str(a), 'OPERATOR(.foo.)') def test_Dtio_Generic_Spec(): # R1208 cls = Dtio_Generic_Spec a = cls('read ( formatted )') assert isinstance(a, cls),`a` assert_equal(str(a), 'READ(FORMATTED)') a = cls('write ( formatted )') assert_equal(str(a), 'WRITE(FORMATTED)') a = cls('read ( unformatted )') assert_equal(str(a), 'READ(UNFORMATTED)') a = cls('write ( unformatted )') assert_equal(str(a), 'WRITE(UNFORMATTED)') def test_Import_Stmt(): # R1209 cls = Import_Stmt a = cls('import :: a, b') assert isinstance(a, cls),`a` assert_equal(str(a), 'IMPORT :: a, b') a = cls('import a') assert isinstance(a, cls),`a` assert_equal(str(a), 'IMPORT :: a') def test_External_Stmt(): # R1210 cls = External_Stmt a = cls('external :: a, b') assert isinstance(a, cls),`a` assert_equal(str(a), 'EXTERNAL :: a, b') a = cls('external a') assert isinstance(a, cls),`a` assert_equal(str(a), 'EXTERNAL :: a') def test_Procedure_Declaration_Stmt(): # R1211 cls = Procedure_Declaration_Stmt a = cls('procedure () a') assert isinstance(a, cls),`a` assert_equal(str(a), 'PROCEDURE() a') a = cls('procedure (n) a') assert_equal(str(a), 'PROCEDURE(n) a') a = cls('procedure (real*8) a') assert_equal(str(a), 'PROCEDURE(REAL*8) a') a = cls('procedure (real(kind=8)) a') assert_equal(str(a), 'PROCEDURE(REAL(KIND = 8)) a') a = cls('procedure (real*8) :: a') assert_equal(str(a), 'PROCEDURE(REAL*8) a') a = cls('procedure (real*8), intent(in), bind(c) :: a, b') assert_equal(str(a), 'PROCEDURE(REAL*8), INTENT(IN), BIND(C) :: a, b') def test_Proc_Attr_Spec(): # R1213 cls = Proc_Attr_Spec a = cls('intent(in)') assert isinstance(a, cls) assert_equal(str(a),'INTENT(IN)') a = cls('optional') assert isinstance(a, cls) assert_equal(str(a),'OPTIONAL') a = cls('save') assert isinstance(a, cls) assert_equal(str(a),'SAVE') a = cls('private') assert isinstance(a, Access_Spec),`type(a)` assert_equal(str(a),'PRIVATE') a = cls('bind(c)') assert isinstance(a, Language_Binding_Spec),`a` assert_equal(str(a),'BIND(C)') def test_Proc_Decl(): # R1214 cls = Proc_Decl a = cls('a => NULL') assert isinstance(a, cls) assert_equal(str(a),'a => NULL') a = cls('a') assert isinstance(a, Name),`type(a)` assert_equal(str(a),'a') def test_Intrinsic_Stmt(): # R1216 cls = Intrinsic_Stmt a = cls('intrinsic :: a, b') assert isinstance(a,cls),`a` assert_equal(str(a),'INTRINSIC :: a, b') a = cls('intrinsic a, b') assert_equal(str(a),'INTRINSIC :: a, b') a = cls('intrinsic a') assert_equal(str(a),'INTRINSIC :: a') def test_Function_Reference(): # R1217 cls = Function_Reference a = cls('f()') assert isinstance(a,cls),`a` assert_equal(str(a),'f()') assert_equal(repr(a),"Function_Reference(Name('f'), None)") a = cls('f(2,k=1,a)') assert isinstance(a,cls),`a` assert_equal(str(a),'f(2, k = 1, a)') def test_Call_Stmt(): # R1218 cls = Call_Stmt a = cls('call a') assert isinstance(a, cls) assert_equal(str(a), 'CALL a') a = cls('call a()') assert_equal(str(a), 'CALL a') a = cls('call a(b,c)') assert_equal(str(a), 'CALL a(b, c)') def test_Procedure_Designator(): # R1219 cls = Procedure_Designator a = cls('a%b') assert isinstance(a,cls),`a` assert_equal(str(a),'a % b') assert_equal(repr(a),"Procedure_Designator(Name('a'), '%', Name('b'))") def test_Actual_Arg_Spec(): # R1220 cls = Actual_Arg_Spec a = cls('k=a') assert isinstance(a,cls),`a` assert_equal(str(a),'k = a') assert_equal(repr(a),"Actual_Arg_Spec(Name('k'), Name('a'))") a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Actual_Arg_Spec_List(): cls = Actual_Arg_Spec_List a = cls('a,b') assert isinstance(a,cls),`a` assert_equal(str(a),'a, b') assert_equal(repr(a),"Actual_Arg_Spec_List(',', (Name('a'), Name('b')))") a = cls('a = k') assert isinstance(a,Actual_Arg_Spec),`a` assert_equal(str(a),'a = k') a = cls('a = k,b') assert isinstance(a,Actual_Arg_Spec_List),`a` assert_equal(str(a),'a = k, b') a = cls('a') assert isinstance(a,Name),`a` assert_equal(str(a),'a') def test_Alt_Return_Spec(): # R1222 cls = Alt_Return_Spec a = cls('* 123') assert isinstance(a,cls),`a` assert_equal(str(a),'*123') assert_equal(repr(a),"Alt_Return_Spec(Label('123'))") def test_Function_Subprogram(): # R1223 reader = get_reader('''\ function foo() end function foo''') cls = Function_Subprogram a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a),'FUNCTION foo()\nEND FUNCTION foo') assert_equal(repr(a),"Function_Subprogram(Function_Stmt(None, Name('foo'), None, None), End_Function_Stmt('FUNCTION', Name('foo')))") reader = get_reader('''\ pure real function foo(a) result(b) bind(c) integer a end function foo''') cls = Function_Subprogram a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a),'PURE REAL FUNCTION foo(a) RESULT(b) BIND(C)\n INTEGER :: a\nEND FUNCTION foo') def test_Function_Stmt(): # R1224 cls = Function_Stmt a = cls('function foo()') assert isinstance(a, cls),`a` assert_equal(str(a),'FUNCTION foo()') assert_equal(repr(a),"Function_Stmt(None, Name('foo'), None, None)") a = cls('function foo(a,b)') assert isinstance(a, cls),`a` assert_equal(str(a),'FUNCTION foo(a, b)') assert_equal(repr(a),"Function_Stmt(None, Name('foo'), Dummy_Arg_List(',', (Name('a'), Name('b'))), None)") a = cls('function foo(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'FUNCTION foo(a)') a = cls('real function foo(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'REAL FUNCTION foo(a)') a = cls('real recursive function foo(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'REAL RECURSIVE FUNCTION foo(a)') a = cls('real function foo(a) bind(c)') assert isinstance(a, cls),`a` assert_equal(str(a),'REAL FUNCTION foo(a) BIND(C)') a = cls('real function foo(a) result (b)') assert isinstance(a, cls),`a` assert_equal(str(a),'REAL FUNCTION foo(a) RESULT(b)') a = cls('real function foo(a) bind(c) result(b)') assert isinstance(a, cls),`a` assert_equal(str(a),'REAL FUNCTION foo(a) RESULT(b) BIND(C)') def test_Dummy_Arg_Name(): # R1226 cls = Dummy_Arg_Name a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') def test_Prefix(): # R1227 cls = Prefix a = cls('pure recursive') assert isinstance(a, cls),`a` assert_equal(str(a),'PURE RECURSIVE') assert_equal(repr(a), "Prefix(' ', (Prefix_Spec('PURE'), Prefix_Spec('RECURSIVE')))") a = cls('integer * 2 pure') assert isinstance(a, cls),`a` assert_equal(str(a),'INTEGER*2 PURE') def test_Prefix_Spec(): # R1228 cls = Prefix_Spec a = cls('pure') assert isinstance(a, cls),`a` assert_equal(str(a),'PURE') assert_equal(repr(a),"Prefix_Spec('PURE')") a = cls('elemental') assert isinstance(a, cls),`a` assert_equal(str(a),'ELEMENTAL') a = cls('recursive') assert isinstance(a, cls),`a` assert_equal(str(a),'RECURSIVE') a = cls('integer * 2') assert isinstance(a, Intrinsic_Type_Spec),`a` assert_equal(str(a),'INTEGER*2') def test_Suffix(): # R1229 cls = Suffix a = cls('bind(c)') assert isinstance(a, Language_Binding_Spec),`a` assert_equal(str(a),'BIND(C)') assert_equal(repr(a),"Language_Binding_Spec(None)") a = cls('result(a)') assert isinstance(a, Suffix),`a` assert_equal(str(a),'RESULT(a)') a = cls('bind(c) result(a)') assert isinstance(a, Suffix),`a` assert_equal(str(a),'RESULT(a) BIND(C)') a = cls('result(a) bind(c)') assert isinstance(a, Suffix),`a` assert_equal(str(a),'RESULT(a) BIND(C)') def test_End_Function_Stmt(): # R1230 cls = End_Function_Stmt a = cls('end') assert isinstance(a, cls),`a` assert_equal(str(a), 'END FUNCTION') a = cls('endfunction') assert_equal(str(a), 'END FUNCTION') a = cls('endfunction foo') assert_equal(str(a), 'END FUNCTION foo') def test_Subroutine_Subprogram(): # R1231 reader = get_reader('''\ subroutine foo end subroutine foo''') cls = Subroutine_Subprogram a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo\nEND SUBROUTINE foo') assert_equal(repr(a),"Subroutine_Subprogram(Subroutine_Stmt(None, Name('foo'), None, None), End_Subroutine_Stmt('SUBROUTINE', Name('foo')))") reader = get_reader('''\ subroutine foo integer a end subroutine foo''') cls = Subroutine_Subprogram a = cls(reader) assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo\n INTEGER :: a\nEND SUBROUTINE foo') def test_Subroutine_Stmt(): # R1232 cls = Subroutine_Stmt a = cls('subroutine foo') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo') assert_equal(repr(a),"Subroutine_Stmt(None, Name('foo'), None, None)") a = cls('pure subroutine foo') assert isinstance(a, cls),`a` assert_equal(str(a),'PURE SUBROUTINE foo') a = cls('pure subroutine foo(a,b)') assert isinstance(a, cls),`a` assert_equal(str(a),'PURE SUBROUTINE foo(a, b)') a = cls('subroutine foo() bind(c)') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo BIND(C)') a = cls('subroutine foo(a)') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo(a)') a = cls('subroutine foo(a, b)') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo(a, b)') a = cls('subroutine foo(a,*)') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo(a, *)') a = cls('subroutine foo(*)') assert isinstance(a, cls),`a` assert_equal(str(a),'SUBROUTINE foo(*)') def test_Dummy_Arg(): # R1233 cls = Dummy_Arg a = cls('a') assert isinstance(a, Name),`a` assert_equal(str(a),'a') a = cls('*') assert isinstance(a, cls),`a` assert_equal(str(a),'*') def test_End_Subroutine_Stmt(): # R1234 cls = End_Subroutine_Stmt a = cls('end subroutine foo') assert isinstance(a, cls),`a` assert_equal(str(a),'END SUBROUTINE foo') assert_equal(repr(a),"End_Subroutine_Stmt('SUBROUTINE', Name('foo'))") a = cls('end') assert isinstance(a, cls),`a` assert_equal(str(a),'END SUBROUTINE') a = cls('endsubroutine') assert isinstance(a, cls),`a` assert_equal(str(a),'END SUBROUTINE') def test_Entry_Stmt(): # R1235 cls = Entry_Stmt a = cls('entry a') assert isinstance(a, cls),`a` assert_equal(str(a), 'ENTRY a()') a = cls('entry a()') assert_equal(str(a), 'ENTRY a()') a = cls('entry a(b, c)') assert_equal(str(a), 'ENTRY a(b, c)') a = cls('entry a(b, c) bind(c)') assert_equal(str(a), 'ENTRY a(b, c) BIND(C)') def test_Return_Stmt(): # R1236 cls = Return_Stmt a = cls('return') assert isinstance(a, cls),`a` assert_equal(str(a), 'RETURN') assert_equal(repr(a), 'Return_Stmt(None)') def test_Contains(): # R1237 cls = Contains_Stmt a = cls('Contains') assert isinstance(a, cls),`a` assert_equal(str(a),'CONTAINS') assert_equal(repr(a),"Contains_Stmt('CONTAINS')") if 1: nof_needed_tests = 0 nof_needed_match = 0 total_needs = 0 total_classes = 0 for name in dir(): obj = eval(name) if not isinstance(obj, ClassType): continue if not issubclass(obj, Base): continue clsname = obj.__name__ if clsname.endswith('Base'): continue total_classes += 1 subclass_names = obj.__dict__.get('subclass_names',None) use_names = obj.__dict__.get('use_names',None) if not use_names: continue match = obj.__dict__.get('match',None) try: test_cls = eval('test_%s' % (clsname)) except NameError: test_cls = None total_needs += 1 if match is None: if test_cls is None: print 'Needs tests:', clsname print 'Needs match implementation:', clsname nof_needed_tests += 1 nof_needed_match += 1 else: print 'Needs match implementation:', clsname nof_needed_match += 1 else: if test_cls is None: print 'Needs tests:', clsname nof_needed_tests += 1 continue print '-----' print 'Nof match implementation needs:',nof_needed_match,'out of',total_needs print 'Nof tests needs:',nof_needed_tests,'out of',total_needs print 'Total number of classes:',total_classes print '-----'
{ "repo_name": "pemryan/f2py", "path": "fparser/tests/test_Fortran2003.py", "copies": "2", "size": "100189", "license": "bsd-3-clause", "hash": 4358014117541049300, "line_mean": 28.2950292398, "line_max": 191, "alpha_frac": 0.5257762828, "autogenerated": false, "ratio": 3.0171956875263506, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45429719703263505, "avg_score": null, "num_lines": null }
from fparser import api def test_reproduce_issue(): source_str = '''\ subroutine bl(a, &b, &c) integer a, b, c a = b + c end subroutine bl subroutine blc(a, c here's an annoying comment line &b, &c, c another annoying comment &d, c a third annoying comment &e) a = b + c + d + e end subroutine blc ''' tree = api.parse(source_str, isfree=False, isstrict=True, analyze=False) print tree assert str(tree).strip().split('\n')[1:] == ''' ! BEGINSOURCE <cStringIO.StringI object at 0x3723710> mode=f77 SUBROUTINE bl(a, b, c) INTEGER a, b, c a = b + c END SUBROUTINE bl SUBROUTINE blc(a, b, c, d, e) a = b + c + d + e END SUBROUTINE blc '''.strip().split('\n')[1:] # def test_reproduce_issue(): # source_str = '''\ # subroutine foo # do 10 # 10 continue # end subroutine # ''' # tree = api.parse(source_str, isfree=False, isstrict=False, # ignore_comments=False) # assert str(tree).strip().split('\n')[1:]==''' # ! BEGINSOURCE <cStringIO.StringI object at 0x1733ea0> mode=fix90 # SUBROUTINE foo() # DO 10 # 10 CONTINUE # END SUBROUTINE foo # '''.strip().split('\n')[1:]
{ "repo_name": "dagss/f2py-g3", "path": "fparser/tests/test_blank_lines.py", "copies": "3", "size": "1354", "license": "bsd-3-clause", "hash": -6812056673824198000, "line_mean": 21.5666666667, "line_max": 77, "alpha_frac": 0.5214180207, "autogenerated": false, "ratio": 3.278450363196126, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5299868383896126, "avg_score": null, "num_lines": null }
from .fpbench import fpcparser from .arithmetic import ieee754, optimistic, np, evalctx from .titanic import sinking from .arithmetic import core2math from .titanic import wolfmath fpc_minimal = fpcparser.compile( """(FPCore (a b) (- (+ a b) a)) """)[0] fpc_example = fpcparser.compile( """(FPCore (a b c) :name "NMSE p42, positive" :cite (hamming-1987 herbie-2015) :fpbench-domain textbook :pre (and (>= (* b b) (* 4 (* a c))) (!= a 0)) (/ (+ (- b) (sqrt (- (* b b) (* 4 (* a c))))) (* 2 a))) """)[0] fpc_fmod2pi = fpcparser.compile( """(FPCore () (- (* 2 (+ (+ (* 4 7.8539812564849853515625e-01) (* 4 3.7748947079307981766760e-08)) (* 4 2.6951514290790594840552e-15))) (* 2 3.14159)) ) """)[0] fpc_sinpow = fpcparser.compile( """(FPCore (x) (sin (pow 2 x))) """)[0] floatctx = evalctx.EvalCtx(props={'precision':'binary32'}) doublectx = evalctx.EvalCtx(props={'precision':'binary64'}) bigctx = evalctx.EvalCtx(w = 20, p = 16360) repl = wolfmath.MathRepl() def compare(core, *inputs, ctx=None): result_ieee = ieee754.interpret(core, inputs, ctx).collapse() result_sink = optimistic.interpret(core, inputs, ctx) result_np = np.interpret(core, inputs, ctx) print(result_ieee, result_sink, result_np) print(repr(result_sink)) print(result_ieee == sinking.Sink(result_np)) math_args, math_expr = core2math.compile(core) math_inputs = [] for arg, name in zip(inputs, math_args): # TODO always uses double, hmmm value = sinking.Sink(arg) math_inputs.append([name, value.to_math()]) core_expr = 'With[{{{}}}, {}]'.format(', '.join((name + ' = ' + value for name, value in math_inputs)), math_expr) # TODO also always double result_exact = repl.evaluate_to_sink(core_expr) print(result_exact) print('') import numpy def floats_near(s, n): f = sinking.Sink(numpy.float32(s)) nearby = [] for i in range(n): nearby.append(f) f = f.away() return nearby def get_vertices(f): result_ieee = sinking.Sink(np.interpret(fpc_sinpow, [f.to_float(numpy.float32)], floatctx)) result_double = ieee754.interpret(fpc_sinpow, [f], doublectx) result_sink = optimistic.interpret(fpc_sinpow, [f], floatctx) print(result_ieee, result_double, result_sink) narrowed = result_sink.narrow(n=result_sink.n - 1) return ['Point[{{{}, {}}}, VertexColors -> {{{}}}]'.format(f.to_math(), y.to_math(), color) for y, color in [[result_ieee, 'Black'], [narrowed.above(), 'Red'], [narrowed.below(), 'Red']]] def make_plot(s, n): fs = floats_near(s, n) points = [] for f in fs: points += get_vertices(f) plot_cmd = 'Export["test.pdf", Plot[Sin[2^x], {{x, {}, {}}}, PlotLabel -> "sin(2^x)", Epilog -> {{PointSize[0.02], {}}}], ImageResolution -> 1200]'.format( fs[0].to_math(), fs[-1].to_math(), ', '.join(p for p in points)) print(plot_cmd) print(repl.run(plot_cmd))
{ "repo_name": "billzorn/fpunreal", "path": "titanfp/demo.py", "copies": "1", "size": "2962", "license": "mit", "hash": 1014998696301748200, "line_mean": 30.1789473684, "line_max": 159, "alpha_frac": 0.6107359892, "autogenerated": false, "ratio": 2.786453433678269, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38971894228782694, "avg_score": null, "num_lines": null }
from .fpbench import fpcparser from .arithmetic import ieee754, sinking quadratic = fpcparser.compile1( """(FPCore (a b c) :name "NMSE p42, positive" :cite (hamming-1987 herbie-2015) :fpbench-domain textbook :pre (and (>= (* b b) (* 4 (* a c))) (!= a 0)) (/ (+ (- b) (sqrt (- (* b b) (* 4 (* a c))))) (* 2 a))) """) quadratic_herbified = fpcparser.compile1( """(FPCore (a b c) :herbie-status success :herbie-time 118637.2451171875 :herbie-bits-used 3392 :herbie-error-input ((256 28.609971950677362) (8000 33.90307227594979)) :herbie-error-output ((256 5.078369297841056) (8000 6.594164753178634)) :name "NMSE p42, positive" :pre (and (>= (* b b) (* 4 (* a c))) (!= a 0)) (if (<= b -3.2964251401560902e+93) (- (/ b a)) (if (<= b -9.121837495335558e-234) (/ 1 (/ (* a 2) (- (sqrt (- (* b b) (* c (* a 4)))) b))) (if (<= b 4.358108025323294e+96) (/ 1 (* (+ (sqrt (- (* b b) (* c (* a 4)))) b) (/ 2 (/ (- 4) (/ 1 c))))) (/ (- c) b))))) """) quadratic_regime = fpcparser.compile1( """(FPCore (a b c) (/ 1 (* (+ (sqrt (- (* b b) (* c (* a 4)))) b) (/ -1 (* 2 c))))) """) arguments = [ ('0.1', '2', '3'), ('0.001', '2', '3'), ('1e-9', '2', '3'), ('1e-15', '2', '3'), ('1e-16', '2', '3'), ('1e-17', '2', '3'), ] if __name__ == '__main__': for args in arguments: ieee754_answer = ieee754.Interpreter.interpret(quadratic, args, ctx=ieee754.ieee_ctx(w=11, p=53)) sinking_answer = sinking.Interpreter.interpret(quadratic, args, ctx=ieee754.ieee_ctx(w=11, p=53)) print(*args, str(ieee754_answer), str(sinking_answer)) print() for args in arguments: ieee754_answer = ieee754.Interpreter.interpret(quadratic_regime, args, ctx=ieee754.ieee_ctx(w=11, p=53)) sinking_answer = sinking.Interpreter.interpret(quadratic_regime, args, ctx=ieee754.ieee_ctx(w=11, p=53)) print(*args, str(ieee754_answer), str(sinking_answer))
{ "repo_name": "billzorn/fpunreal", "path": "titanfp/techcon_examples.py", "copies": "1", "size": "1961", "license": "mit", "hash": 520844143474523970, "line_mean": 34.0178571429, "line_max": 112, "alpha_frac": 0.5517593065, "autogenerated": false, "ratio": 2.476010101010101, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3527769407510102, "avg_score": null, "num_lines": null }
from fpdf import FPDF, HTMLMixin from .. import models import actions import flockappsecret as secret import datetime class MyFPDF(FPDF, HTMLMixin): pass def generate_report(trk,usr): html = """ <h3 align="center">Expense Report</h3> <h3>Employee Expense Report</h3> <table border="0" width="90%" align="center"> <thead> <tr><th width="30%">Name</th><th width="10%">Division</th><th width="10%">Depatment</th><th width="30%">Location</th><th width="20%">Travelling allowance</th></tr> </thead> <tbody> <tr> <td>"""+usr.name+"""</td> <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> </tr> </tbody> </table> <p><strong>Business Pupose Visit:</strong></p> <p>Insert the purpose of the visit</p> <table border="0" width="90%" align="center"> <thead> <tr><th width="20%">employee</th><th width="30%">pupose</th><th width="10%">time</th><th width="20%">date</th><th width="10%">cost</th></tr> </thead> <tbody>""" cur_qs = models.Currency.objects.all() total_dic = {} for cur in cur_qs: ex_qs = models.Expense.objects.filter(track = trk,currency=cur) sum = 0.0 for ex in ex_qs: tm = ex.timestamp.time() sum = sum + ex.amount html = html +"""<tr><td>"""+ex.paidby.name+"""</td><td>"""+ex.purpose+"""</td><td>"""+str(tm.hour)+':'+str(tm.minute)+"""</td><td>"""+str(ex.timestamp.date())+"""</td><td>"""+ex.currency.abbr+' '+str(ex.amount)+"""</td></tr>""" if(sum!=0): total_dic[cur.name] = str(sum) for curr,val in total_dic.iteritems(): html = html +"""<tr><td></td><td></td><td></td><td><b>Total cost</b></td><td>"""+curr+' '+str(val)+"""</td></tr>""" html = html + """ </tbody> </table> <hr> <p>I hereby certify, to the best of my knowledge and belief, that (1) all information contained on this report is correct and (2) all expenses claimed on this report are based on actual costs incurred and are consistent with Company/Operations/Division procedures and the instructions on the reverse side of this form.</p> <p>Employee signature:___________________</p>s """ pdf=MyFPDF() pdf.add_page() pdf.write_html(html) pdf.output('media/'+usr.userId+'.pdf','F') actions.bot_sendMessage(usr.userId,'<a>'+secret.get_url()+'/media/'+usr.userId+'.pdf'+'</a>') return def generate_report_2(chattrackId,chatId,userId): user = models.User.objects.get(userId=str(userId)) if(str(chatId)[0]=='g'): group_members = actions.getMembers(chatId,user) print(group_members) Chat = models.Chat.objects.get(chatId=str(chatId)) Chattrack = models.Chattrack.objects.get(id=chattrackId,user = Chat) html = """ <h4 align="center">Expense Report</h4> <h4>Employee Expense Report:"""+Chattrack.name+""" </h4> <table border="0" width="90%" align="center"> <thead> <tr> <th width="50%">Name</th> <th width="50%">Claim</th> </thead> <tbody> """ cur_qs = models.Currency.objects.all() total_dic = {} if(str(chatId)[0]=='g'): ###################################list of employees in group per currency for member in group_members: for cur in cur_qs: ex_qs = models.ChatExpense.objects.filter(track = Chattrack,currency=cur,paidbywhom=member['firstName']+' '+member['lastName']) sum = 0.0 for ex in ex_qs: sum = sum + ex.amount if(sum!=0): html = html+"""<tr><td>"""+member['firstName']+' '+member['lastName']+"""</td><td>"""+cur.abbr+' '+str(sum)+"""</td></tr>""" else: for cur in cur_qs: ex_qs = models.ChatExpense.objects.filter(track = Chattrack,currency=cur) sum = 0.0 for ex in ex_qs: sum = sum + ex.amount if(sum!=0): html = html+"""<tr><td>"""+user.name+"""</td><td>"""+cur.abbr+' '+str(sum)+"""</td></tr>""" html = html+ """ </tbody> </table> <p><strong>Business Visit:</strong></p> <p>Purpose: """+Chattrack.purpose+"""</p> <p>Date: """+str(Chattrack.start_date)+"""</p> <table border="0" width="90%" align="center"> <thead> <tr><th width="20%">Paidby</th><th width="30%">pupose</th><th width="10%">time</th><th width="20%">date</th><th width="10%">cost</th></tr> </thead> <tbody>""" cur_qs = models.Currency.objects.all() total_dic = {} for cur in cur_qs: ex_qs = models.ChatExpense.objects.filter(track = Chattrack,currency=cur) sum = 0.0 for ex in ex_qs: tm = ex.timestamp.time() sum = sum + ex.amount html = html +"""<tr><td>"""+ex.paidbywhom+"""</td><td>"""+ex.purpose+"""</td><td>"""+str(tm.hour)+':'+str(tm.minute)+"""</td><td>"""+str(ex.timestamp.date())+"""</td><td>"""+ex.currency.abbr+' '+str(ex.amount)+"""</td></tr>""" if(sum!=0): total_dic[cur.name] = str(sum) for curr,val in total_dic.iteritems(): html = html +"""<tr><td></td><td></td><td></td><td><b>Total cost</b></td><td>"""+curr+' '+str(val)+"""</td></tr>""" html = html + """ </tbody> </table> <hr> <p>I hereby certify, to the best of my knowledge and belief, that (1) all information contained on this report is correct and (2) all expenses claimed on this report are based on actual costs incurred and are consistent with Company/Operations/Division procedures and the instructions on the reverse side of this form.</p> <p>Employee signature:___________________</p> """ pdf=MyFPDF() pdf.add_page() pdf.write_html(html) bills = models.Bills.objects.filter(track=Chattrack) for b in bills: pdf.add_page() html = """<br/><br/><center><A HREF="http://www.mousevspython.com"><img src='"""+b.image.url[1:]+"""' width="400" height="400"></A></center>""" pdf.write_html(html) tim = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M") pdf.output('media/'+Chattrack.name+str(tim)+'.pdf','F') return secret.get_url()+'/media/'+Chattrack.name+str(tim)+'.pdf'
{ "repo_name": "akhilraj95/xpense", "path": "xpense/flockapp/flockapplib/exports.py", "copies": "1", "size": "6240", "license": "mit", "hash": 9192891040462992000, "line_mean": 40.3245033113, "line_max": 326, "alpha_frac": 0.5551282051, "autogenerated": false, "ratio": 3.1278195488721803, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41829477539721804, "avg_score": null, "num_lines": null }
from fpdf import FPDF import re import sys import os import subprocess from AdaptivePELE.analysis import plotAdaptive import argparse CONTACTS = "contacts" BE = "bindingEnergy" SASA = "sasa" kind_Print, colModifier, traj_range = "PRINT_BE_RMSD", 4, None def arg_parse(): parser = argparse.ArgumentParser(description='Build a summary pdf file of the simulation') parser.add_argument('control_file', type=str, help='adaptive control file') parser.add_argument('--traj', type=str, help='Trajectory file name i.e. run_traj_', default='trajectory_') parser.add_argument('--report', type=str, help='Report file name i.e run_report_', default='report_') args = parser.parse_args() return args def retrieve_metrics(control_file): metrics_names = ["rmsd", "com_distance", "distanceToPoint", BE, SASA] discard = ["random", "constrainAtomToPosition", "sphericalBox", "toThisOtherAtom", "constrainThisAtom", "springConstant", "equilibriumDistance", ] try: with open(control_file, "r") as f: metrics = [line for line in f if "type" in (line.strip()) and not any(x in line for x in discard)] except IOError: raise IOError("Pele control file {} not found. Check the path inside Adaptive control file".format(control_file)) pattern = r'"([A-Za-z0-9_\./\\-]*)"' metrics = re.findall(pattern, "".join(metrics)) metrics = [metric for metric in metrics if metric in metrics_names] return metrics def write_report(metrics, resname, initial_column=4, traj="trajectory_", report="report_"): OUTPUT = 'adaptive_report.pdf' pdf = FPDF() pdf.add_page() # Title pdf.set_font('Arial', 'B', 15) pdf.cell(80) pdf.cell(30, 10, 'Simulation Report', align='C') # Plot Binding SASA plot(1+metrics.index(BE)+initial_column, 1+metrics.index(SASA)+initial_column, ".", "BE.png", "BindingE", "sasa", report=report) pdf.cell(-100) pdf.set_font('Arial', 'B', 11) pdf.cell(10, 49, 'Interaction Energy vs Sasa' +34*"\t" + "Total Energy vs Interaction Energy") pdf.image("BE.png", 10, 40, 83) # Plot Total Biding plot(initial_column, 1+metrics.index(BE)+initial_column, ".", "total.png", "totalE", "BindingE", report=report) pdf.cell(0) pdf.set_font('Arial', 'B', 11) pdf.image("total.png", 100, 40, 83) # Contacts create_contact_plot(".") pdf.cell(0) pdf.set_font('Arial', 'B', 11) pdf.image("{}_threshold.png".format(CONTACTS), 10, 110, 83) pdf.image("{}_hist.png".format(CONTACTS), 100, 110, 83) pdf.add_page() #Plot other metrics agains binding images_per_page = 1 images_per_row = 0 #metrics = ["rmsd", "com_distance", "distanceToPoint", "clusters"] metrics_names = ["rmsd", "com_distance", "distanceToPoint"] for user_metric in metrics_names: if images_per_page > 4: pdf.add_page() images_per_page = 1 if user_metric in metrics or user_metric == "clusters": pdf, images_per_page, images_per_row = write_metric( pdf, user_metric, BE, metrics, images_per_page, images_per_row, resname, traj=traj, report=report) #Output report pdf.output(OUTPUT, 'F') def plot_clusters(metric1, metric2, metrics, resname, traj, report): command = "python -m AdaptivePELE.analysis.clusterAdaptiveRun 200 {} {} {} --report {} --traj {} --png".format( get_column(metric1, metrics), get_column(metric2, metrics), resname, report, traj) os.system(command) def get_column(metric, metrics, initial_pos=4): return 1+metrics.index(metric)+initial_pos def write_metric(pdf, metric1, metric2, metrics, images_per_page, images_per_row, resname=None, initial_pos=4, traj="trajectory_", report="report_"): #Create Image if metric1 == "clusters": image_name = "Cluster_analisis/ClusterMap.png".format(metric1) plot_clusters("bindingEnergy", "sasa", metrics, resname, report) else: image_name = "{}.png".format(metric1) plot(1+metrics.index(metric1)+initial_pos, 1+metrics.index(metric2)+initial_pos, ".", image_name, metric1, metric2, zcol=initial_pos + 1+ metrics.index("sasa"), report=report) #Move over pdf pdf.image(image_name, pdf.get_x(), pdf.get_y(), 83) images_per_row += 1 if images_per_row == 1: pdf.cell(80, 0, "", 0, 0) else: pdf.set_xy(10, 100) pdf.cell(80, 0, "", 0, 2); images_per_row = 0 images_per_page += 1 #Update cursor return pdf, images_per_page, images_per_row def plot(Xcol, Ycol, path, name, xcol_name, ycol_name, zcol=5, report="report_"): try: plot_line = plotAdaptive.generatePrintString(8, Xcol, Ycol, report, "PRINT_BE_RMSD", zcol, None).strip("\n") except TypeError: raise TypeError("Report not found use the flag --report. i.e --report run_report_ ") command = '''gnuplot -e "set terminal png; set output '{}'; set xlabel '{}'; set ylabel '{}'; {}"'''.format( name, xcol_name, ycol_name, plot_line) os.system(command) def create_contact_plot(path, filenames=CONTACTS): command = "python -m AdaptivePELE.analysis.numberOfClusters -f contacts" os.system(command) def retrieve_fields(control_file): with open(control_file, "r") as f: content = f.readlines() control_file_line = [line for line in content if line.strip().startswith('"controlFile"')][0] ligand_res_line = [line for line in content if line.strip().startswith('"ligandResname"')][0] pele, resname = control_file_line.split(":")[1].strip().strip(",").strip('"'), ligand_res_line.split(":")[1].strip().strip(",").strip('"') if not os.path.isfile(pele): path = os.path.dirname(os.path.abspath(control_file)) pele = os.path.join(path, pele) return pele, resname def main(control_file, traj, report): print("Search pele control file") pele_conf, resname = retrieve_fields(control_file) print("Retrieve metrics") metrics = retrieve_metrics(pele_conf) print("Build report") write_report(metrics, resname, 4, traj, report) print("Analysis finished succesfully") if __name__ == "__main__": args = arg_parse() main(args.control_file, args.traj, args.report)
{ "repo_name": "AdaptivePELE/AdaptivePELE", "path": "AdaptivePELE/analysis/reportSimulation.py", "copies": "1", "size": "6288", "license": "mit", "hash": -7933567651086778000, "line_mean": 38.0559006211, "line_max": 150, "alpha_frac": 0.6442430025, "autogenerated": false, "ratio": 3.256343863283273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4400586865783273, "avg_score": null, "num_lines": null }
from fpdf import FPDF class Style(FPDF): """ A simple static class to set default style content """ def feature(self, text): """ :param self: PDF self. to set style :param text: text to be molded :return: """ self.set_font('Times', '', 10) self.set_fill_color(r=231, g=216, b=213) return self.cell(w=0, h=8, txt=text, border=0, ln=1, align='L', fill=True, link='') def value_proposition(self, text): """ :param self: PDF self. to set style :param text: text to be molded :return: """ self.set_font('Times', '', 10) return self.cell(w=0, h=8, txt=text, border=0, ln=1, align='L', fill=False, link='') def scenario(self, text): """ :param self.: PDF self. to set style :param text: text to be molded :return: """ self.set_font('Times', '', 12) self.set_fill_color(r=67, g=67, b=68) self.set_text_color(r=247, g=247, b=247) return self.cell(w=0, h=6, txt=text, border=0, ln=1, align='L', fill=True, link='') def step(self, text): """ :param self.: PDF self. to set style :param text: text to be molded :return: """ self.set_font('Times', '', 10) self.set_text_color(r=0, g=0, b=0) return self.cell(w=0, h=6, txt=text, border=0, ln=1, align='L', fill=False, link='') def break_line(self): """ :return: """ return self.cell(w=0, h=6, txt='', border=0, ln=1, align='L', fill=False, link='')
{ "repo_name": "yurireeis/bddocs", "path": "bddocs/src/pdf/style.py", "copies": "1", "size": "1748", "license": "mit", "hash": 2240590846411681500, "line_mean": 26.746031746, "line_max": 60, "alpha_frac": 0.4771167048, "autogenerated": false, "ratio": 3.420743639921722, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43978603447217224, "avg_score": null, "num_lines": null }
from fpga_sdrlib import config errorcode_shift = 1 errorcode_mod = pow(2, config.msg_errorcode_width) modulecode_shift = errorcode_shift * errorcode_mod modulecode_mod = pow(2, config.msg_modulecode_width) formatcode_shift = modulecode_shift * modulecode_mod formatcode_mod = pow(2, config.msg_formatcode_width) length_shift = formatcode_shift * formatcode_mod length_mod = pow(2, config.msg_length_width) header_shift = length_shift * length_mod def parse_packet(packet): header = packet[0] is_header = header//header_shift length = (header//length_shift) % length_mod formatcode = (header//formatcode_shift) % formatcode_mod modulecode = (header//modulecode_shift) % modulecode_mod errorcode = (header//errorcode_shift) % errorcode_mod length = (header//length_shift) % length_mod if not is_header: raise StandardError("Header of packet thinks it's not a header.") if len(packet) != length+1: raise StandardError("Packet is of length {0} but thinks it is of length {1}.".format(len(packet), length+1)) if modulecode not in packet_codes: raise StandardError("The module code {0} is unknown.".format(module_code)) if errorcode not in packet_codes[modulecode]: raise StandardError("The error code {0} is unknown for module {1}".format(errorcode, modulecode)) return packet_codes[modulecode][errorcode](packet) def nothing_test_packet(packet): if len(packet) != 2: raise StandardError("Packet of type 0, 0 should have length 2") return "nothing: received {0}".format(packet[1]) packet_codes = { 0: { 0: nothing_test_packet, } }
{ "repo_name": "benreynwar/fpga-sdrlib", "path": "python/fpga_sdrlib/message/msg_codes.py", "copies": "1", "size": "1654", "license": "mit", "hash": -1243110355134682400, "line_mean": 40.35, "line_max": 116, "alpha_frac": 0.6964933495, "autogenerated": false, "ratio": 3.5417558886509637, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47382492381509633, "avg_score": null, "num_lines": null }
from fpl_reader.pseudo_object import PseudoObject from fpl_reader.cool_io import CoolIO from fpl_reader.windows_time import get_time_from_ticks class Playlist: def __init__(self, tracks): self.tracks = tracks def __repr__(self): return ( 'Playlist([\n' + ',\n\n'.join(repr(track) for track in self.tracks) + '\n])') class Track(PseudoObject): def __init__(self): super(Track, self).__init__() self.flags = None self.subsong_index = None self.file_name = None self.file_size = None self.file_time = None self.duration = None self.rpg_album = None self.rpg_track = None self.rpk_album = None self.rpk_track = None self.primary_keys = {} self.secondary_keys = {} def read_track(meta_io, index_io): track = Track() track.flags = index_io.read_s32_le() file_name_offset = index_io.read_u32_le() track.file_name = meta_io.seek(file_name_offset).read_to_zero() track.subsong_index = index_io.read_u32_le() if track.flags & 1 == 0: # e.g. stream that was never played, so it has no meta return track track.file_size = index_io.read_s64_le() track.file_time = get_time_from_ticks(index_io.read_u64_le()) track.duration = index_io.read_f64() track.rpg_album = index_io.read_f32() track.rpg_track = index_io.read_f32() track.rpk_album = index_io.read_f32() track.rpk_track = index_io.read_f32() entry_count = index_io.read_u32_le() entries = [index_io.read_u32_le() for _ in range(entry_count)] primary_key_count = entries.pop(0) secondary_key_count = entries.pop(0) secondary_keys_offset = entries.pop(0) primary_key_name_offsets = {} for _ in range(primary_key_count): key_name_id = entries.pop(0) key_name_offset = entries.pop(0) primary_key_name_offsets[key_name_id] = key_name_offset entries.pop(0) # unk0 primary_key_value_offsets = [ entries.pop(0) for _ in range(primary_key_count) ] track.primary_keys = {} last_key_offset = None for i in range(primary_key_count): # foobar2000's properties window duplicates and concatenates the value # when discontiguous keys are detected; we do not. last_key_offset = primary_key_name_offsets.get(i, last_key_offset) value_offset = primary_key_value_offsets[i] if last_key_offset is None: raise RuntimeError('Missing first primary key, now what?') key = meta_io.seek(last_key_offset).read_to_zero() value = meta_io.seek(value_offset).read_to_zero() track.primary_keys[key] = value assert primary_key_count * 3 + 1 <= secondary_keys_offset for _ in range(secondary_keys_offset - (primary_key_count * 3 + 1)): entries.pop(0) track.secondary_keys = {} for _ in range(secondary_key_count): key_offset = entries.pop(0) value_offset = entries.pop(0) key = meta_io.seek(key_offset).read_to_zero() value = meta_io.seek(value_offset).read_to_zero() track.secondary_keys[key] = value if track.flags & 0x04: _padding = index_io.read(64) return track def read_playlist(data): magic = b'\xE1\xA0\x9C\x91\xF8\x3C\x77\x42\x85\x2C\x3B\xCC\x14\x01\xD3\xF2' tracks = [] with CoolIO(data) as handle: if handle.read(len(magic)) != magic: raise RuntimeError('Not a FPL file') meta_size = handle.read_u32_le() meta = handle.read(meta_size) track_count = handle.read_u32_le() with CoolIO(meta) as meta_io, CoolIO(handle.read_to_eof()) as index_io: for track_no in range(track_count): track = read_track(meta_io, index_io) tracks.append(track) return Playlist(tracks)
{ "repo_name": "rr-/fpl_reader", "path": "fpl_reader/playlist_reader.py", "copies": "1", "size": "3898", "license": "mit", "hash": -8171546773321731000, "line_mean": 32.0338983051, "line_max": 79, "alpha_frac": 0.6092868138, "autogenerated": false, "ratio": 3.1924651924651926, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43017520062651926, "avg_score": null, "num_lines": null }
from fp.monads.monad import Monad, MonadPlus class Maybe(Monad, MonadPlus): """ A Maybe monad. The Maybe monad is helpful when dealing with sequences of functions that could return None. For instance, when fetching a key from a dictionary that may not be there: >>> from fp.monads.maybe import Maybe, Just, Nothing >>> data = {"foo": {"bar": {"baz": "bing"}}} >>> data['foo']['bong']['baz'] Traceback (most recent call last): ... KeyError: 'bong' This is a very common problem when processing JSON. Often, with JSON, a missing key is the same as null but in Python a missing key raises an error. `dict.get` is often the solution for missing keys but is still not enough: >>> data.get("foo").get("bong").get("baz") Traceback (most recent call last): ... AttributeError: 'NoneType' object has no attribute 'get' To final solution to this ends up being ugly: >>> data.get("foo", {}).get("bong", {}).get("baz") is None True It is even more complex when dealing with mixed types; for instance if "bong" ends up being a list instead of a dict. The :class:`Maybe` monad lets us express errors such as these as either something or nothing. This is much like :func:`dict.get` returning None, but we can chain Maybe actions so that they fail with :class:`Nothing`, if any of the functions in the chain returns :class:`Nothing`. Normally getitem will raise an error if the key or index is invalid, :func:`Maybe.catch` causes :class:`Nothing` to be returned if any exception occurs. >>> from operator import getitem >>> from fp import p >>> lookup = p(Maybe.catch, getitem) >>> lookup({"foo": "bar"}, "foo") Just('bar') >>> lookup({"foo": "bar"}, "bong") Nothing Now lookup returns :class:`Just(x)` if the key is found or :class:`Nothing` if the key is not found. To extract the value out of the :class:`Just()` class, we can call :class:`Maybe.default()`: >>> lookup({'foo': 'bar'}, 'foo').default('') 'bar' >>> lookup({'foo': 'bar'}, 'bong').default('') '' To chain the lookups, we simply need to partially apply the lookup function: >>> from fp import pp >>> lookup(data, "foo").bind(pp(lookup, "bar")).bind(pp(lookup, "baz")) Just('bing') >>> lookup(data, "foo").bind(pp(lookup, "bong")).bind(pp(lookup, "baz")) Nothing This is still not as pretty as it could be so we provide a `get_nested` function in the `fp.collections` module: >>> from fp.collections import get_nested >>> get_nested(Maybe, data, "foo", "bar", "baz") Just('bing') >>> get_nested(Maybe, data, "foo", "bong", "baz") Nothing In addition, functions that return None become Nothing automatically: >>> Maybe.ret(None) Nothing >>> Maybe.ret({}.get('foo')) Nothing This feature allows you to easily integrate the Maybe monad with existing functions that return None. """ ##===================================================================== ## Maybe methods ##===================================================================== def __init__(self, value): self.__value = value def __eq__(self, other): return self.__value == other.__value def __repr__(self): if self.is_just: return "Just({0!r})".format(self.__value) else: return "Nothing" @property def is_just(self): """ Tests if the Maybe is just a value >>> Just(1).is_just True >>> Nothing.is_just False """ return self.__value is not None @property def is_nothing(self): """ Tests if the Maybe is Nothing >>> Nothing.is_nothing True >>> Just(1).is_nothing False """ return not self.is_just @property def from_just(self): """ Extracts the just value from the Maybe; raises a ValueError if the value is None >>> Just(1).from_just 1 >>> Nothing.from_just Traceback (most recent call last): ... ValueError: Maybe.from_just called on Nothing """ if self.is_just: return self.__value else: raise ValueError("Maybe.from_just called on Nothing") def default(self, default_value): """ Returns the just value or the default value if Nothing >>> Just(1).default(-1) 1 >>> Nothing.default(-1) -1 """ if self.is_just: return self.__value else: return default_value @classmethod def cat_maybes(cls, maybes): """ Returns an iterator of the Just values >>> list(Maybe.cat_maybes([ ... Just(1), Nothing, Just(2) ... ])) [1, 2] """ for maybe in maybes: if maybe.is_just: yield maybe.__value @classmethod def map_maybes(cls, f, xs): """ maps a list over a Maybe arrow >>> def maybe_even(x): ... if x % 2 == 0: ... return Just(x) ... else: ... return Nothing >>> list(Maybe.map_maybes(maybe_even, [1,2,3,4])) [2, 4] """ for x in xs: maybe = f(x) if maybe.is_just: yield maybe.__value ##===================================================================== ## Monad methods ##===================================================================== @classmethod def ret(cls, value): return cls(value) def bind(self, f): """ The Maybe's bind function. `f` is called only if `self` is a Just. >>> Just(1).bind(lambda x: Maybe(x)) Just(1) >>> def crashy(x): ... assert False, "bind will not call me" >>> Nothing.bind(crashy) Nothing """ if self.is_just: return f(self.__value) else: return self @classmethod def fail(cls, err): """ >>> Maybe.fail("some error") Nothing """ return Nothing ##===================================================================== ## MonadPlus methods ##===================================================================== def mplus(self, y): """ An associative operation. >>> Just(1).mplus(Maybe.mzero) Just(1) >>> Nothing.mplus(Maybe(2)) Just(2) >>> Just(1).mplus(Just(2)) Just(1) """ if self.is_just: return self else: return y Just = Maybe Nothing = Maybe(None) Maybe.mzero = Nothing
{ "repo_name": "ericmoritz/fp", "path": "fp/monads/maybe.py", "copies": "1", "size": "6907", "license": "bsd-2-clause", "hash": -5438758310285660000, "line_mean": 24.6765799257, "line_max": 76, "alpha_frac": 0.5073114232, "autogenerated": false, "ratio": 4.206455542021924, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5213766965221924, "avg_score": null, "num_lines": null }
from FPPbrowser import app from flask import render_template, request, jsonify, flash from matplotlib import pyplot as plt from bokeh import plotting as bkplt from bokeh.embed import file_html, components from bokeh.resources import CDN import numpy as np import os, os.path # import vespa import json import mpld3 # starpop = vespa.MultipleStarPopulation(1) data_options = [] # for each_key in starpop.stars.keys(): # if np.isfinite(getattr(starpop.stars,each_key)).any(): # data_options.append(each_key) # Create empty pyplot figure fig = bkplt.figure() KOI_files = [] curdir = os.path.dirname(__file__) KOI_filepath = os.path.join(curdir,'static','fpp') for each_file in os.listdir(KOI_filepath): if each_file[0] != '.': KOI_files.append(each_file) @app.route('/') def index(): # jsonfig = json.dumps(mpld3.fig_to_dict(fig)) # return render_template('index.html', data_options=data_options, jsonfig=jsonfig) script, div = components(fig, CDN) return render_template('index.html', data_options=data_options, script=script, div=div, KOI_files=KOI_files) @app.route('/loadKOIData', methods=['POST']) def load_KOIdata(): KOI_filename = request.form['KOIinput'] return render_template('index.html', KOI_filename=KOI_filename, KOI_files=KOI_files) @app.route('/_plot_data', methods=['POST']) def plot_data(): data = request.form['KOIinput'] return render_template('index.html', data=data, KOI_files=KOI_files) # all_picks = request.args.getlist('checkbox_data') # x_pick = 'H_mag'#str(all_picks[0]) # y_pick = 'H_mag'#str(all_picks[1]) # x = starpop[x_pick] # y = starpop[y_pick] # fig.xaxis.axis_label = x_pick # fig.yaxis.axis_label = y_pick # # Plot data and convert to JSON # script, div = components(fig, CDN) # # jsonfig = jsonify(mpld3.fig_to_dict(fig)) # # return render_template('index.html', data_options=data_options, jsonfig=jsonfig) # return div
{ "repo_name": "timothydmorton/vespa-visualization", "path": "FPPbrowser/FPPbrowser/views.py", "copies": "1", "size": "1895", "license": "mit", "hash": 1856541644909099300, "line_mean": 29.0793650794, "line_max": 109, "alpha_frac": 0.7124010554, "autogenerated": false, "ratio": 2.778592375366569, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3990993430766569, "avg_score": null, "num_lines": null }
from fq.curator.models import Item from fq.collage.models import Spread class ContentIndex(object): """ Content Index """ index_name = "content" doc_types = ["item", "spread"] active_field = "published" item_mapping = { # Item Mapping "title": {"type": "string", "store": "yes", "analyzer": "fq", "boost": "8.0"}, "url": {"type": "string", "store": "yes", "index": "no"}, "item_type": {"type": "integer", "store": "yes"}, "category": {"type": "string", "store": "yes", "analyzer": "fq", "boost": "10.0"}, "categoryid": {"type": "integer", "store": "yes"}, "store": {"type": "string", "store": "yes", "analyzer": "fq", "boost": "2.0"}, "storeid": {"type": "integer", "store": "yes"}, "brand": {"type": "string", "store": "yes", "analyzer": "fq", "boost": "5.0"}, "brandid": {"type": "integer", "store": "yes"}, "price_currency": {"type": "string", "store": "yes", "index": "no"}, "price": {"type": "float", "store": "yes"}, } spread_mapping = { # Spread Mapping "title": {"type": "string", "store": "yes", "analyzer": "fq"}, "user": {"type": "string", "store": "yes", "analyzer": "fq"}, "url": {"type": "string", "store": "yes", "index": "no"}, "tags": {"type": "string", "store": "yes", "analyzer": "fq"}, } settings = { "settings": { "number_of_shards": 1, "number_of_replicas": 1, "analysis": { "analyzer": { "fq": { "tokenizer": "standard", "filter": ["standard", "lowercase", "stop", "porter_stem"] } } } }, "mappings": { "item": { "properties": item_mapping }, "spread": { "properties": spread_mapping } } } def item_queryset(self, start_date, end_date): item = Item.objects.filter(published=True) if start_date and end_date: return item.filter(modified_date__range=(start_date, end_date)) else: return item def spread_queryset(self, start_date, end_date): if start_date and end_date: return Spread.objects.filter(modified_date__range=(start_date, end_date)) else: return Spread.objects.all()
{ "repo_name": "codespresso/djes", "path": "djes/indexes.py", "copies": "1", "size": "2467", "license": "mit", "hash": -193499701843153730, "line_mean": 33.2638888889, "line_max": 90, "alpha_frac": 0.4698013782, "autogenerated": false, "ratio": 3.665676077265973, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4635477455465973, "avg_score": null, "num_lines": null }
from fqn_decorators import get_fqn from influxdb.influxdb08.client import InfluxDBClientError from tests.conftest import Dummy, go from tests.test_base_backend import TestBaseBackend from time_execution import settings from time_execution.backends.influxdb import InfluxBackend class TestTimeExecution(TestBaseBackend): def setUp(self): super(TestTimeExecution, self).setUp() self.database = 'unittest' self.backend = InfluxBackend( host='influx', database=self.database, use_udp=False ) try: self.backend.client.create_database(self.database) except InfluxDBClientError: # Something blew up so ignore it pass settings.configure(backends=[self.backend]) def tearDown(self): self.backend.client.delete_database(self.database) def _query_backend(self, name): query = 'select * from {}'.format(name) metrics = self.backend.client.query(query)[0] for metric in metrics['points']: yield dict(zip(metrics['columns'], metric)) def test_time_execution(self): count = 4 for i in range(count): go() metrics = list(self._query_backend(go.fqn)) self.assertEqual(len(metrics), count) for metric in metrics: self.assertTrue('value' in metric) def test_duration_field(self): with settings(duration_field='my_duration'): go() for metric in self._query_backend(go.fqn): self.assertTrue('my_duration' in metric) def test_with_arguments(self): go('hello', world='world') Dummy().go('hello', world='world') metrics = list(self._query_backend(get_fqn(go))) self.assertEqual(len(metrics), 1) metrics = list(self._query_backend(get_fqn(Dummy().go))) self.assertEqual(len(metrics), 1) def test_hook(self): def test_args(**kwargs): self.assertIn('response', kwargs) self.assertIn('exception', kwargs) self.assertIn('metric', kwargs) return dict() def test_metadata(*args, **kwargs): return dict(test_key='test value') with settings(hooks=[test_args, test_metadata]): go() for metric in self._query_backend(go.fqn): self.assertEqual(metric['test_key'], 'test value')
{ "repo_name": "snelis/timeexecution", "path": "tests/test_influxdb.py", "copies": "1", "size": "2447", "license": "apache-2.0", "hash": 7270559573298978000, "line_mean": 28.8414634146, "line_max": 66, "alpha_frac": 0.6072742133, "autogenerated": false, "ratio": 4.154499151103566, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 82 }
from fractal import Fractal from geometry import Point, midpoint, distance import math def from_degrees(angle): return math.pi* 2 * angle / 360 def rotated_about(p, center, theta): radius = distance(p, center) angle = math.atan2(p.y - center.y, p.x - center.x) angle += theta dx = radius * math.cos(angle) dy = radius * math.sin(angle) return center + Point(dx, dy) class Koch(Fractal): def __init__(self): self.zoom_change = 3 self.left = Point(0,0) self.right = Point(1,0) self.foci = [Point(0.5, 1)] def draw(self, im_draw, bbox): def koch(start, end, depth): if depth == 1: im_draw.line(start.tuple() + end.tuple(), fill="black") else: #transform the line into a collection of four line segments. #Resembling this: _/\_ a = start e = end b = midpoint(a,e, 1/3.0) d = midpoint(a,e, 2/3.0) #b,c, and d form an equilateral triangle, #so we only need to rotate d about b by 30 degrees to get c. c = rotated_about(d, b, from_degrees(60)) points = [a,b,c,d,e] for start, end in zip(points, points[1:]): koch(start, end, depth-1) start, end = self.rebased(self.left, bbox), self.rebased(self.right, bbox) a, b, c = [self.rebased(p, bbox) for p in (self.left, self.foci[0], self.right)] koch(a, b, 6) koch(b, c, 6)
{ "repo_name": "kms70847/Animation", "path": "src/Zooming_Fractals/koch.py", "copies": "1", "size": "1558", "license": "mit", "hash": 5374191854181327000, "line_mean": 35.2558139535, "line_max": 88, "alpha_frac": 0.5295250321, "autogenerated": false, "ratio": 3.2662473794549265, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4295772411554926, "avg_score": null, "num_lines": null }
from fractal import Fractal from geometry import Point, midpoint import math class Sierpinsky(Fractal): def __init__(self): self.zoom_change = 2 #use this height for the largest isoceles triangle that can fit in the bounding box. #height = 1 #use this height for an equilateral triangle. height = math.sqrt(3)/2 self.foci = [Point(0.5, math.sqrt(3)/2), Point(0,0), Point(1, 0)] def draw(self, im_draw, bbox): def sier(depth, a, b, c): def tri(a,b,c): def line(start, end): im_draw.line([start.tuple(), end.tuple()], fill="black") line(a,b); line(b,c); line(c,a) if depth == 1: tri(a,b,c) else: sier(depth-1, a, midpoint(a,b), midpoint(c,a)) sier(depth-1, b, midpoint(b,c), midpoint(a,b)) sier(depth-1, c, midpoint(c,a), midpoint(b,c)) a = self.rebased(self.foci[0], bbox) b = self.rebased(self.foci[1], bbox) c = self.rebased(self.foci[2], bbox) sier(8, a, b, c)
{ "repo_name": "kms70847/Animation", "path": "src/Zooming_Fractals/sierpinsky.py", "copies": "1", "size": "1112", "license": "mit", "hash": -1454253894178546700, "line_mean": 38.7142857143, "line_max": 92, "alpha_frac": 0.529676259, "autogenerated": false, "ratio": 3.0718232044198897, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.410149946341989, "avg_score": null, "num_lines": null }
from fractal import Fractal from geometry import Point from boundingbox import BoundingBox def product(max): """cartesian product of range(max) and range(max)""" for i in range(max): for j in range(max): yield (i,j) class GridFractal(Fractal): def __init__(self, grid): """ initializes the GridFractal object. `grid` is a 3x3 list of boolean values indicating which cells of the grid will be filled. """ self.grid = grid self.foci = [] for i, j in product(3): if self.grid[j][i]: self.foci.append(Point(i/2.0, j/2.0)) #we'll make the center foci the first one, if it exists if self.grid[1][1]: self.foci.remove(Point(1/2.0, 1/2.0)) self.foci.insert(0, Point(1/2.0, 1/2.0)) self.zoom_change = 3 def draw(self, im_draw, bbox): def draw_grid(depth, bbox): if depth == 1: im_draw.rectangle(bbox.tuple(), fill="black") else: width = bbox.width/3.0 height = bbox.height/3.0 for i, j in product(3): if not self.grid[j][i]: continue left = bbox.left + width*i top = bbox.top + height*j child_bbox = BoundingBox(left, top, left+width, top+height) draw_grid(depth-1, child_bbox) draw_grid(6, bbox)
{ "repo_name": "kms70847/Animation", "path": "src/Zooming_Fractals/gridFractal.py", "copies": "1", "size": "1471", "license": "mit", "hash": 6424392615919623000, "line_mean": 34.0476190476, "line_max": 101, "alpha_frac": 0.5227736234, "autogenerated": false, "ratio": 3.5878048780487806, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46105785014487805, "avg_score": null, "num_lines": null }
from fractions import Fraction as F from itertools import count, islice, repeat, chain, starmap import math try: from itertools import izip as zip from itertools import imap as map except ImportError: # will be 3.x series pass pstestlimit = 5 def memoizedGenerator( gen ): _iter = gen() _cache = [] def _gen(): for n in count(): if n < len(_cache): yield _cache[n] else: term = next(_iter) _cache.append(term) yield term return _gen def num_to_str( term ): if isinstance(term, float): return "\t% .3e" % term else: return "\t"+str(term) class PowerSeries(object): def __init__(self, g=None): self.__g = g def __eq__(self, entry): print("Warning: comparing powerseries!") return Equal( self, entry ) def __iter__( self ): return self.__g() if self.__g else repeat(0) def __str__(self): return self.getstr() def getstr(self, nums=[], term_to_str=num_to_str): def gen_str(): if isinstance(nums, int): n = nums r = nums else: n = nums[0] if nums else pstestlimit r = nums[1:] if nums else [] is_pps = isinstance(self.zero, PowerSeries) for term in islice(self, n): if is_pps: yield term.getstr(r) + "\n" else: yield term_to_str(term) + ", " return "".join(gen_str()) + "..." def __getitem__(self, key): """ Access items of power series with an index or a slice. Warning: Access by slice just returns a slice and not a list or tuple. Use list(P[:10]) to get a list of the first 10 coefficients. """ if isinstance(key, slice): return islice(self, key.start, key.stop, key.step) else: return next(islice(self, key, None)) def deep_map( self, func, n=1 ): """ Helper function, which maps a function to the power series at nestedness level n. Deep_maps is essentially an iterated map function used to handle the multivariate power series. """ if n == 0: return func(self) if n == 1: @memoizedGenerator def _deep_map(): return map( func, self ) return PowerSeries( _deep_map ) else: return self.deep_map( lambda x: x.deep_map(func, n-1) ) @property def ord2exp(self): """ Converts an ordinary generating function to an exponential generating function. Example: >>> Equal((1/(1-X)).ord2exp, exp(X)) True """ def _ord2exp(f=1): for n,term in enumerate(self): yield F(term, f) f*= n+1 return PowerSeries(_ord2exp) @property def exp2ord(self): """ Converts an exponential generating function to an ordinary generating function. Example: >>> Equal(exp(X).exp2ord, 1/(1-X)) True """ def _exp2ord(f=1): for n,term in enumerate(self): yield term * f f*= n+1 return PowerSeries(_exp2ord) @property def zero(self): """ Returns the constant term of the power series. """ for term in self: return term @property def tail(self): """ Returns everything except the constant term as a new power series. """ def _tail(): return islice(self, 1, None) return PowerSeries(_tail) @property def xmul(self): """ Shifts the coefficients of the power series P by one term such that P.xmul has 0 as constant term. """ def _xmul(): return chain( ( self.zero*0,), self ) return PowerSeries(_xmul) def __add__(self, entry): """ Implements power series addition. """ if is_powerseries(entry): @memoizedGenerator def _add(): return starmap( lambda a,b: a+b, zip( self, entry ) ) else: def _add(): return chain( map( lambda a: a+entry, islice(self, 0, 1) ), islice(self, 1, None) ) return PowerSeries(_add) __radd__ = __add__ def __sub__(self, entry): return self + (-entry) def __rsub__(self, entry): return entry + (-self) def __neg__(self): return self.deep_map( lambda x: -x ) def __mul__(self, entry): """ Implements multiplication of power series. Only minor modifications were necessary in P. Donis original code to handle multivariate power series. Example: >>> Equal((exp(X-Z)/(1-X)) * (exp(Y+Z)/(1-Y)), exp(X+Y)/(1-X-Y+X*Y)) True """ if not is_powerseries(entry): if entry == 1: return self elif entry == 0: if is_powerseries(self.zero): z = self.zero*0 def _z(): return repeat( z ) return PowerSeries(_z) else: return PowerSeries() else: return self.deep_map( lambda x: x*entry ) @memoizedGenerator def _mul(): f0 = self.zero g0 = entry.zero yield f0 * g0 F = self.tail G = entry.tail mterms = [(F * G).xmul] if is_powerseries(f0) or f0 != 0: f0G = G.deep_map( lambda x: x*f0 ) mterms.append(f0G) if is_powerseries(g0) or g0 != 0: g0F = F.deep_map( lambda x: x*g0 ) mterms.append(g0F) for terms in zip(*mterms): yield sum(terms) return PowerSeries(_mul) __rmul__ = __mul__ def __truediv__(self, entry): if is_powerseries(entry): return entry.__rtruediv__(self) elif entry == 1: return self elif entry == 0: raise ValueError("Zero division error") else: return self * (F(1, 1) / entry) def __rtruediv__(self, entry): """ Implements division of power series P/Q. If Q has an integer constant term != 1, the P/Q will be given as a power series of Fractions even if P is an integer power series. Examples: >>> A = 10/ (1 - X) >>> Equal(A, 1/(1-X) * 10 ) True >>> B = 1 / (1 - X - X*Y) >>> Equal(1/B, 1-X-X*Y) True >>> C = 100*solve( Y - X*exp(X) )[0].tail >>> Equal( C/C, 1 ) True """ @memoizedGenerator def _rdiv(): f0 = self.zero if isinstance(f0, int): recip = F(1, f0) else: recip = 1 / f0 if not is_powerseries(entry): yield entry * recip for term in ( (self.tail * R).deep_map( lambda x: -x*recip ) ): yield term else: yield entry.zero * recip for term in ( (entry.tail-self.tail * R).deep_map( lambda x: x*recip ) ): yield term R = PowerSeries(_rdiv) return R __div__ = __truediv__ __rdiv__ = __rtruediv__ def __pow__( self, alpha ): """ Implements taking powers of power series. For positive integers as arguments where are no restrictions on the power series. For all other exponents the power series needs to have a non-zero constant coefficient. This function is based on P. Donis' code. Examples: >>> Equal(X**0, I) True >>> Equal(X*X, X**2) True >>> Equal( log((1/(1+X))**(F(3,2))), -F(3,2)*log(1+X)) True >>> Equal(exp( X + 3*Y )**F(-4,7), exp( -F(4,7) * (X + 3*Y) )) True """ f0 = self.zero if not is_powerseries(f0) and f0 == 0: if isinstance(alpha, int) and alpha >= 0: if alpha == 0: return self*0 + 1 @memoizedGenerator def _pow(): for e in repeat(0, alpha): yield e for term in self.tail ** alpha: yield term return PowerSeries(_pow) else: raise ValueError("Can't raise powerseries with vanishing first term to non positive integer power") c0 = self.zero**alpha if is_powerseries(self.zero) or self.zero != 1 else 1 @memoizedGenerator def _pow(): for term in integral(alpha * P * D(self) / self, c0 ): yield term P = PowerSeries(_pow) return P def compose(self, *args): """ Implements general power series composition. The first argument is composed with the first variable or nestedness level, the second with the second nestedness level and so on. In power series symbols, compose with arguments f_1, ..., f_n calculates P( f_1(x,y,z), ..., f_n(x,y,z), x, y, z, ...) Note that we continue with x,y,z if we have more variables then arguments. For instance, >>> P = X + 3*Y >>> Equal( P(Y, exp(X)-1), Y + 3*exp(X)-3 ) True Composition can also be used to shuffle the variables of power series if necessary: >>> P = X*exp(Y) >>> Equal( P(Y, X), Y*exp(X) ) True Furthermore we can reduce the depth of the powerseries by associating different variables. >>> Equal( P(X,X), X*exp(X) ) True Note that P(X) gives the same result as P(X,X) if P is a bivariate power series. Examples: >>> Equal((1/(1-X-X*Y))(X,X), 1/(1-X-X**2)) True >>> A = exp(X) >>> B = log(1/(1-X)) >>> Equal( A(B), 1/(1-X) ) True >>> Equal((1/(1-X-X*Y))(Y,X), 1/(1-Y-Y*X)) True >>> Equal((1/(1-X-X*Y))(Y), 1/(1-Y-Y*X)) True >>> Equal((1/(1-X-Z))(X,Y,X*Y), 1/(1-X-X*Y)) True >>> Equal((1/(1-X))(Y), 1/(1-Y)) True """ n = len(args) try: k,a = next( ( (k,a) for k,a in enumerate(args) if not is_powerseries(a) ) ) if a == 0: if n > 1: return self.deep_map( lambda x: x.zero, k )( *(args[:k] + args[k+1:]) ) else: return self.zero else: raise ValueError("Can't calculate powerseries at non-zero value") except StopIteration: pass get_zero = lambda d: d.zero if is_powerseries(d) else d get_D = lambda d: D(d) if is_powerseries(d) else 0 @memoizedGenerator def _compose(): G = ( self.deep_map( D, k ) for k in range(n) ) F = map( D, args ) r = sum( g.deep_map(lambda x, f=f: x*f, n) for g,f in zip(G, F) ) + self.deep_map( get_D, n ) z = self.deep_map( get_zero, n ) c0 = z( *map( lambda x: x.zero, args ) ) for term in integral(r(*args), c0): yield term return PowerSeries(_compose) def __call__( self, *args ): return self.compose(*args) def exp( self ): """ Implements the exponential on power series. This function is based on P. Donis implementation. Examples: >>> e = exp(X) >>> Equal( e, D(e) ) True >>> Equal( e, integral(e, 1) ) True >>> Equal( log(e), X ) True >>> d = exp(3*X*X) >>> Equal(d*e, exp(X + 3*X**2)) True """ if not is_powerseries(self): if self == 0: return 1 else: raise ValueError("You can't calculate exp of %d with the powerseries package" % self) f0 = self.zero if is_powerseries( f0 ): c0 = exp(f0) elif f0 == 0: c0 = 1 else: raise ValueError("Can't take exp of powerseries with non-zero constant term") @memoizedGenerator def _exp(): for term in integral( E * D(self), c0 ): yield term E = PowerSeries(_exp) return E def log( self ): """ Implements the logarithm on power series. This function is based on P. Donis implementation. Examples: >>> l = log(1+X) >>> Equal( 3*l, log((1+X)*(1+X)*(1+X)) ) True >>> Equal( D(l), 1/(1+X) ) True """ f0 = self.zero if is_powerseries( f0 ): c0 = log(f0) elif f0 == 1: c0 = 0 else: raise ValueError("Can't take log of powerseries with non-unit constant term") @memoizedGenerator def _log(): for term in integral( D(self)/self, c0 ): yield term return PowerSeries(_log) def D( self, n=1 ): """ Gives the term-wise derivative of a power series. """ if n == 1: @memoizedGenerator def _D(): return starmap( lambda n,x: (n+1)*x, enumerate(self.tail) ) return PowerSeries(_D) elif n == 0: return f elif isinstance(n, int) and n > 1: return D( D(self), n-1 ) else: raise ValueError("Can't take %d-th derivative" % n) def integral( self, const=0 ): """ Gives the term-wise integral of a power series. """ @memoizedGenerator def _int(): return chain( (const,), starmap( lambda n,x: F(1,n+1)*x, enumerate(self) ) ) return PowerSeries(_int) def exp( f ): if is_powerseries(f): return f.exp() else: return math.exp(f) def log( f ): if is_powerseries(f): return f.log() else: return math.log(f) def D( f, n=1 ): return f.D(n) def integral( f, const=0 ): return f.integral(const) def tensor( *args ): """ Multiplies two power series and concatinates the variables. That means if f_1, ..., f_n are given as arguments, tensor calculates, f_1(X_1, ..., X_n) f_2(X_(n+1), ..., X_m) f_3(X_(m+1), ... ) ... Example: >>> A = exp(X) >>> B = log(1+X) >>> Equal( tensor(A,B)(X,X), A*B ) True """ if len(args) == 1: return args[0] elif len(args) == 2: f0, f1 = args[0], args[1] if not is_powerseries(f0) or not is_powerseries(f1): return f0 * f1 else: return f0.deep_map( lambda x: tensor(x, f1) ) elif len(args) > 2: return tensor( args[0], tensor( *args[1:] ) ) else: return 0 def Equal( entry1, entry2, n=pstestlimit ): if not is_powerseries( entry1 ) and not is_powerseries( entry2 ): return entry1 == entry2 elif not is_powerseries( entry1 ): return Equal(entry2.zero, entry1) and Equal(entry2.tail, PowerSeries()) elif not is_powerseries( entry2 ): return Equal(entry1.zero, entry2) and Equal(entry1.tail, PowerSeries()) else: return all( Equal( s, e, n) for s,e in islice(zip(entry1, entry2), n) ) def is_powerseries( entry ): return isinstance(entry, PowerSeries) def linsolve( M, b ): """ Helper function that solves linear equation systems Mx = b for x where entries of the matrix M and the vector b can be power series. >>> W = [ [ exp(X+2*Y), log(1+Y) ], [ X**2 - exp(Y*(exp(X)-1)), 1/(1-X*Y-X) ] ] >>> B = [ X + Y*3 , 1/(1-X*Y) ] >>> W2 = W[:] >>> B2 = B[:] >>> R = linsolve( W, B ) >>> Equal(R[0]*W2[0][0] + R[1]*W2[0][1] - B2[0], tensor(ZERO, ZERO)) True >>> Equal(R[0]*W2[1][0] + R[1]*W2[1][1] - B2[1], tensor(ZERO, ZERO)) True """ get_deep_zero = lambda d: get_deep_zero(d.zero) if is_powerseries(d) else d n = len(M) diag = [0]*n for i in range(n): for k in range(i, n): if get_deep_zero(M[k][i]) != 0: break else: raise ValueError("Zero division Error") if k != i: M[i], M[k] = M[k], M[i] b[i], b[k] = b[k], b[i] inv = F(1,1)/M[i][i] diag[i] = inv for j in range(i+1, n): d = M[j][i]*inv b[j] = b[j] - b[i]*d M[j]= [0]*(i+1) + [ t - r*d for t,r in islice(zip(M[j], M[i]), i+1, n) ] for i in reversed(range(n)): b[i] = diag[i]*(b[i] - sum( M[i][j]*b[j] for j in range(i+1,n) )) return b def solve( *args ): """ This function solves arbitrary equation systems for power series (as far as the solution in terms of power series is straightforward). Each argument is an equation giving a restriction on the solution. In power series symbols this function with f_1, ..., f_n given as arguments calculates the solutions g_1, ..., g_n of f_1(g_1(X,Y,...),..., g_n(X,Y,...),X,Y,...) = 0 f_2(g_1(X,Y,...),..., g_n(X,Y,...),X,Y,...) = 0 ... f_n(g_1(X,Y,...),..., g_n(X,Y,...),X,Y,...) = 0 The solutions g_1, ..., g_n are returned as a tuple. Examples: >>> Equal(solve( Y-1 + exp(X))[0], log(1-X)) True >>> T = [ log(1+X) + exp(Y)-1 + Z, 1/(1-X-X*Y) - 1 + Z ] >>> all( Equal(t( solve(t)[0] ), tensor(ZERO, ZERO)) for t in T ) True >>> W = [ X + Y + 2*Z + Y*Y - Y*Y*Y, X + Z + X*X ] >>> R = solve(*W) >>> Equal( W[0](*R), ZERO ) True >>> Equal( W[1](*R), ZERO ) True """ get_zero = lambda d: d.zero if is_powerseries(d) else d get_D = lambda d: D(d) if is_powerseries(d) else 0 n = len(args) a_n_zero = args for i in range(n): a_n_zero = tuple( a.zero for a in a_n_zero ) if any( not is_powerseries(az) for az in a_n_zero ): if all( az == 0 for az in a_n_zero ): return (0,)*n else: raise ValueError("No solution") c0s = solve( *[ a.deep_map( get_zero, n ) for a in args ] ) m = [ [ a.deep_map( D, k ) for k in range(n) ] for a in args ] b = [ -a.deep_map( get_D, n ) for a in args ] dfs = linsolve( m, b ) def make_solver( df, c0 ): @memoizedGenerator def _solve(): for term in integral( df(*SOL), c0 ): yield term return PowerSeries(_solve) SOL = tuple( make_solver( df, c0 ) for df, c0 in zip(dfs, c0s) ) return SOL ZERO = PowerSeries() I = 1 + ZERO X = I.xmul Y = tensor(I, X) Z = tensor(I, Y) if __name__ == '__main__': import doctest doctest.testmod()
{ "repo_name": "michibo/pwrsrs", "path": "pwrsrs.py", "copies": "1", "size": "19361", "license": "mit", "hash": 2497000329371177500, "line_mean": 24.4415243101, "line_max": 115, "alpha_frac": 0.4776096276, "autogenerated": false, "ratio": 3.539488117001828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9459208349273303, "avg_score": 0.011577879065705074, "num_lines": 761 }
from fractions import Fraction as f import sys import math # strange patterns by looking at pythagorean triples # # this is using the '1-t^2,1+t^2' paramterization of the circle # # but with attempting to make 'rings' instead of the circle itself # using fractions as input to 't', we get a pretty smooth rational tessellation # of the unit circle, where rational means that each point has rational # coordinates. # # as with pythpattern12, this is not symmetrical. its easy to see this # by looking at the 'crowding' near the middle (on the top-bottom axis) # # also, as with pythpattern 12, if you try to 'make' it symmetrical # by inserting y,x for every x,y point, you get a sort of messy # tessellation with lots of tiny bits... and its not really symmetrical # either along every axis. # # # note - blue, red, and green quadrance are from Norman Wildberger's # Chromogeometry def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] depth=15 layers=[[]] for j in range(0,depth): layer=layers[j] layers+=[[]] for i in range(2*j): num = i denom = 2*j layers[j] += [f(num,denom)] layers[j+1]+=[f(1,1)] #for i in layers: # print i,'\n' for layer in layers: for t in layer: if blueq(0,0,1,t)==0: continue x = len(layer)*f(redq(0,0,1,t),blueq(0,0,1,t)) y = len(layer)*f(greenq(0,0,1,t),blueq(0,0,1,t)) xs += [x] ys += [y] xs += [-x] ys += [y] xs += [-x] ys += [-y] xs += [x] ys += [-y] xs=[] ys=[] for nn in range(1,15): # layers[0:4]: angle = 0 for t in range(0,4*nn+1): #angle += 360/len(layer) angle = (float(t)/float(4*nn))*(math.pi) x = nn*math.cos(angle) y = nn*math.sin(angle) print t,nn,float(t)/float(nn),angle,angle/math.pi,x,y xs+=[x] ys+=[y] xs+=[x] ys+=[-y] max=max(xs+ys) for i in range(0,len(xs)): #xs[i] = f(xs[i], max ) #ys[i] = f(ys[i], max ) xs[i] = xs[i] / max ys[i] = ys[i] / max #print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show() for p in range(len(xs)): print xs[p],ys[p] print len(xs), 'points'
{ "repo_name": "donbright/piliko", "path": "experiment/miscpatterns/pythpattern16.py", "copies": "1", "size": "2265", "license": "bsd-3-clause", "hash": -6053218248368979000, "line_mean": 22.112244898, "line_max": 79, "alpha_frac": 0.6335540839, "autogenerated": false, "ratio": 2.3230769230769233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.34566310069769235, "avg_score": null, "num_lines": null }
from fractions import Fraction as f import sys # draw points of squares->tiling a rectangle # size of squares = fibonacci seq def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] class Cursor: direction=[0,1] position=[0,0] def forward(self,n): self.position[0]=self.position[0]+self.direction[0]*n self.position[1]=self.position[1]+self.direction[1]*n def turnleft(self): # North->West->South->East->North # 0,1 -> -1,0 -> 0,-1 -> 1,0 -> 0,1 tmp=self.direction[0] self.direction[0]=-1*self.direction[1] self.direction[1]=tmp cursor=Cursor() rabbits=[0,1] depth=10 for i in range(1,depth): cursor.forward(rabbits[-1]) cursor.turnleft() cursor.forward(rabbits[-1]) x,y = [cursor.position[0],cursor.position[1]] qx,qy=sqr(x),sqr(y) zq=qx+qy la=f(qx,zq) yoo=f(qy,zq) print la,yoo xs += [x] ys += [y] rabbits+=[rabbits[-1]+rabbits[-2]] #print rabbits #print cursor.position[0],cursor.position[1],x,y,blueq(0,0,x,y) max=max(xs+ys) for i in range(0,len(xs)): xs[i] = f(xs[i], max ) ys[i] = f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/fiborec2.py", "copies": "1", "size": "1353", "license": "bsd-3-clause", "hash": -5658109309877241000, "line_mean": 22.7368421053, "line_max": 64, "alpha_frac": 0.6555801922, "autogenerated": false, "ratio": 2.107476635514019, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3263056827714019, "avg_score": null, "num_lines": null }
from fractions import Fraction as F import sys # rational paramterization / approximation of bernoulli's lemniscate # in a 3 dimensional 'dumbbell' arrangement. # (note - this uses terms from Norman Wildberger's rational # trigonometry/chromogeometry. briefly for a vector from 0,0 to x,y: # # blue quadrance (x,y) = x^2 + y^2 # red quadrance (x,y) = x^2 - y^2 # green quadrance (x,y) = 2*x*y # ) # theory: # # step one is the rational paramterization of bernoulli's lemniscate # we found this in pythbern.py # # step two is to 'grow' it into three d as some kind of dumbbell shape. # # how..? hrm. # # consider each 'x' as a 'distance' from origin for generating a circle. # consider 'y' as the radius of the circle. # now, draw the circle--- using rational points # we will end up with a 'stack' of circles in the dumbbell shape # as though we had sliced the dumbbell. # imagine def sqr(x): return x*x def greenq_pts(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq_pts(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq_pts(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) def greenq(m,n): return greenq_pts(0,0,m,n) def redq(m,n): return redq_pts(0,0,m,n) def blueq(m,n): return blueq_pts(0,0,m,n) xs,ys,zs=[],[],[] depth = 10 for m in range(-depth,depth): for n in range(0,depth): if redq(m,n)==0: continue if greenq(m,n)==0: continue bq = blueq(m,n) rq = redq(m,n) gq = greenq(m,n) for m2 in range(-depth,depth): for n2 in range(-depth,depth): if blueq(m2,n2)==0: continue xdumb = F(bq,rq) * F( 1, blueq( F(bq,rq), F(gq, rq) ) ) y = F(gq,rq) * F( 1, blueq( F(bq,rq), F(gq, rq) ) ) radius = y ydumb = F(redq(m2,n2),blueq(m2,n2)) zdumb = F(greenq(m2,n2),blueq(m2,n2)) ydumb *= radius zdumb *= radius xs += [xdumb] ys += [ydumb] zs += [zdumb] max=max(xs+ys+zs) for i in range(0,2): print str(xs[i])+','+str(ys[i])+','+str(zs[i]), print '....' for i in range(0,len(xs)): xs[i] = F( xs[i], max ) ys[i] = F( ys[i], max ) zs[i] = F( zs[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/bernoulli/pythberntest.py", "copies": "1", "size": "2265", "license": "bsd-3-clause", "hash": -8104407733391525000, "line_mean": 26.2891566265, "line_max": 72, "alpha_frac": 0.6291390728, "autogenerated": false, "ratio": 2.2403560830860534, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8100945057129375, "avg_score": 0.05371001975133572, "num_lines": 83 }
from fractions import Fraction as f import sys # rational paramterization of a 'green' hyperbola, using Norman # Wildberger's Chromogeometry. # for a full explanation see the file 'pythhyp1.py'. # this file, pythhyp2, differs only in that we generate the 'green' # hyperbola ( based on the equation 2xy = r^2 = constant ) instead of # the 'red' one. # a very simple rational paramterization would be something like y=2/x. # and then x is something like 0, 1/3, 2/3, 3/3, 4/3, 5/3, . . . # but it seems kind of cool that we can also do it with chromogeometry # and get a pretty good looking 'green disc' tessellation: # # # namely, x = green quadrance(0,0,1,t)/red quadrance(0,0,1,t) # y = red quadrance(0,0,1,t)/green quadrance(0,0,1,t) # # where t is between 0 and 1 def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] depth=30 layers=[[]] for j in range(0,depth): layer=layers[j] layers+=[[]] for i in range(j): num = i denom = j layers[j] += [f(num,denom)] # layers[j+1]+=[f(1,1)] for i in layers: print i,'\n' for layer in layers: for t in layer: if greenq(0,0,1,t)==0: continue if redq(0,0,1,t)==0: continue x = len(layer)*f(greenq(0,0,1,t),redq(0,0,1,t)) y = len(layer)*f(redq(0,0,1,t),greenq(0,0,1,t)) xs += [x] ys += [y] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = f(xs[i], max ) ys[i] = f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show() #for p in range(len(xs)): # print xs[p],ys[p]
{ "repo_name": "donbright/piliko", "path": "experiment/pythhyp2.py", "copies": "1", "size": "1744", "license": "bsd-3-clause", "hash": 1945501276878332400, "line_mean": 23.5633802817, "line_max": 72, "alpha_frac": 0.6381880734, "autogenerated": false, "ratio": 2.2416452442159382, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8117136078321552, "avg_score": 0.05253944785887732, "num_lines": 71 }
from fractions import Fraction as f import sys # rational paramterization of hyperbola, using Norman Wildberger's # Chromogeometry. # # step 1. lets review the rational paramterization of an ordinary circle # (blue circle). in an ordinary circle, x^2+y^2 = radius^2. for a unit # circle, you can say x^2+y^2=1. in chromogeometry, you can say the blue # quadrance between 0,0 and x,y is 1. # # now, a 'rational parametirzation' of a circle will give you the x,y # coordinates of the circle where x and y are both rational numbers. if # your radius is rational too, this basically means you are generating # points that are exactly on the circle, with no sin/cos approximation # involved. fun fact: if your radius is rational, you are basically # generating pythagorean triples. # # # here is a common rational parameterization of the circle you will see # in various places, like so: first, generate a bunch of integers, m and # n. then make x,y coordinates like so: # # # x,y = m^2-n^2 / m^2+n^2 , 2*m*n / m^2+n^2 # # # this can be thought of in chromogeometry using red,blue,and green quadrances # between 0,0 and a sequence of made-up coordinates, m,n. like so: # # x,y = red q(0,0,m,n)/blue q(0,0,m,n), green q(0,0,m,n)/blue q(0,0,m,n) # # Note here that another popular rational circle paramterization that # you see, '1-t^2 / 1+t^2, 2t / 1+t^2' is just setting m to '1' and # varying n. or vice versa. we can also rerite that paramterization with # chromogeometry # x,y = red q(0,0,1,t)/blue q(0,0,1,t), green q(0,0,1,t)/blue q(0,0,1,t) # to simplify,.... # x,y = redq/blueq, greenq/blueq # what does this have to do with hyperbolas? # in chromogeometry, the x^2-y^2=k hyperbola is called a 'red circle' # # lets just switch around the terms in our paramterization. # for the blue circle we had # # x,y = red q/blue q, green q/blue q # # after playing around with the above alot (see the pythpattern*py programs) # it becomes evident the 'divisor' or 'denominator' term kind of has a lot # to do with the shape here. # # # well, what if for the 'red circle' we can try this: # # x,y = blue q/red q, green q/red q ?? # # plot it out and what do we get? # # a hyperbola! interesting. # # but lets not stop there. # pythpattern15 gave a rational 'tessellation' of a disk, or a filled circle. # in other words, it drew a bunch of concentric rational approximations of # circles. # can we have a 'red disk' in chromogemtry? can we 'tessellate' it with # 'concentric red circles'? yes, yes we can. this program does it. the # resulting shape looks like some kind of single-wing glider from outer # space or maybe like a fish fin. def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] depth=15 layers=[[]] for j in range(0,depth): layer=layers[j] layers+=[[]] for i in range(j): num = i denom = j layers[j] += [f(num,denom*2)] layers[j+1]+=[f(1,1)] for i in layers: print i,'\n' for layer in layers: for t in layer: if redq(0,0,1,t)==0: continue x = len(layer)*f(blueq(0,0,1,t),redq(0,0,1,t)) y = len(layer)*f(greenq(0,0,1,t),redq(0,0,1,t)) xs += [x] ys += [y] xs += [x] ys += [-y] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = f(xs[i], max ) ys[i] = f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show() for p in range(len(xs)): print xs[p],ys[p]
{ "repo_name": "donbright/piliko", "path": "experiment/pythhyp3.py", "copies": "2", "size": "3625", "license": "bsd-3-clause", "hash": 912623015376498300, "line_mean": 26.8846153846, "line_max": 79, "alpha_frac": 0.6708965517, "autogenerated": false, "ratio": 2.522616562282533, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4193513113982533, "avg_score": null, "num_lines": null }
from fractions import Fraction as f import sys # strange patterns by looking at pythagorean triples # # in this example the rational paramterization of the circle # is superimposed upon the 'raw' pythagorean triples # # it forms a sort of weird non-symmetrical rational tesellation of the circle # (in that all the points have rational coordinates) # # note the parastiches (apparent spirals) coming from the center # (or are they apparent parabolas?) # # note - blue, red, and green quadrance are from Norman Wildberger's # Chromogeometry def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] r=14 for m in range(-r,r): for n in range(-r,r): if blueq(0,0,m,n)==0: continue x = f(redq(0,0,m,n),1) y = f(greenq(0,0,m,n),1) x2 = f(redq(0,0,m,n),blueq(0,0,m,n)) y2 = f(greenq(0,0,m,n),blueq(0,0,m,n)) xs += [x] ys += [y] xs2 += [x2] ys2 += [y2] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = 2*f(xs[i], max ) ys[i] = 2*f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs+xs2,ys+ys2) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/miscpatterns/pythpattern8.py", "copies": "1", "size": "1369", "license": "bsd-3-clause", "hash": -1978826158160213000, "line_mean": 23.4464285714, "line_max": 77, "alpha_frac": 0.650109569, "autogenerated": false, "ratio": 2.1661392405063293, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.33162488095063297, "avg_score": null, "num_lines": null }
from fractions import Fraction as f import sys # strange patterns by looking at pythagorean triples # # this is an attempt to have different 'rings' of the circle # instead of just a flat circle # it provides a non-symmetrical but totally rational 'tessellation' of # some rational points on a circle ... in that all the points of the # tessellation, as well as the points on the circle, have rational x,y # coordinates. # note - blue, red, and green quadrance are from Norman Wildberger's # Chromogeometry def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] r=24 rq=sqr(r) for m in range(0,r): for n in range(0,r): if blueq(0,0,m,n)==0: continue x = m*f(redq(0,0,m,n),blueq(0,0,m,n)) y = m*f(greenq(0,0,m,n),blueq(0,0,m,n)) if (x<0): continue xs += [x] ys += [y] xs += [-x] ys += [y] xs += [x] ys += [-y] xs += [-x] ys += [-y] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = f(xs[i], max ) ys[i] = f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/miscpatterns/pythpattern12.py", "copies": "1", "size": "1282", "license": "bsd-3-clause", "hash": 7546570581992916000, "line_mean": 23.1886792453, "line_max": 71, "alpha_frac": 0.635725429, "autogenerated": false, "ratio": 2.2530755711775043, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8088867354194468, "avg_score": 0.05998672919660736, "num_lines": 53 }
from fractions import Fraction as f import sys # strange patterns by looking at pythagorean triples # # this is using the '1-t^2,1+t^2' paramterization of the circle # # but with attempting to make 'rings' instead of the circle itself # also using the farey seq as input to 't' # result is an interesting sort of tessellation, but not quite as # smooth as pythpattern12 # # note - blue, red, and green quadrance are from Norman Wildberger's # Chromogeometry def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] depth=4 layers=[[f(0,1),f(1,1)]] for j in range(0,depth): layer=layers[j] layers+=[[]] for i in range(len(layer)-1): num = layer[i].numerator+layer[i+1].numerator denom = layer[i].denominator+layer[i+1].denominator layers[j+1] += [layer[i],f(num,denom)] layers[j+1]+=[f(1,1)] for i in layers: print i,'\n' for layer in layers: for t in layer: if blueq(0,0,1,t)==0: continue x = len(layer)*f(redq(0,0,1,t),blueq(0,0,1,t)) y = len(layer)*f(greenq(0,0,1,t),blueq(0,0,1,t)) xs += [x] ys += [y] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = f(xs[i], max ) ys[i] = f(ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/miscpatterns/pythpattern14.py", "copies": "1", "size": "1452", "license": "bsd-3-clause", "hash": 3578969215421626000, "line_mean": 22.8032786885, "line_max": 69, "alpha_frac": 0.6542699725, "autogenerated": false, "ratio": 2.2546583850931676, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3408928357593168, "avg_score": null, "num_lines": null }
from fractions import Fraction as F # exploring the sides of the triangles formed by the centers of # ford circles def sqr(x): return x*x def f2s(x): return str(x.numerator) + '/' + str(x.denominator) class fordcirc: def __init__(self,numerator,denominator): self.xcoord = F(numerator,denominator) self.radius = F(1,2*sqr(denominator)) def __str__(self): return '['+f2s(self.xcoord)+':'+f2s(self.radius)+']' def findpythq( circ1, circ2 ): a = circ1.radius - circ2.radius b = circ2.xcoord - circ1.xcoord c = circ1.radius + circ2.radius qa = sqr(a) qb = sqr(b) qc = sqr(c) return [f2s(qa),f2s(qb),f2s(qc)] def nextcirc( circ1, circ2 ): a = circ1.xcoord.numerator b = circ1.xcoord.denominator c = circ2.xcoord.numerator d = circ2.xcoord.denominator return fordcirc( a+c, b+d ) c1=fordcirc(0,1) c2=fordcirc(1,1) psides = findpythq( c1, c2 ) print c1, c2, ':-:', psides[0:2], ':', psides[2] for i in range(0,5): c2 = nextcirc( c1, c2 ) psides = findpythq( c1, c2 ) print c1, c2, ':-:', psides[0:2], ':', psides[2]
{ "repo_name": "donbright/piliko", "path": "experiment/fordpyth.py", "copies": "1", "size": "1046", "license": "bsd-3-clause", "hash": 8689890312249166000, "line_mean": 23.3255813953, "line_max": 64, "alpha_frac": 0.65583174, "autogenerated": false, "ratio": 2.288840262582057, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3444672002582057, "avg_score": null, "num_lines": null }
from fractions import Fraction as Frac from copy import copy def pivot(matrix, line, column): store = [ [0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))] for l in range(len(matrix)): for c in range(len(matrix[0])): if l == line and c == column: store[l][c] = Frac(1, matrix[l][c]) elif l == line: store[l][c] = matrix[l][c] / matrix[line][column] elif c == column: store[l][c] = -matrix[l][c] / matrix[line][column] else: store[l][c] = matrix[l][c] - (matrix[l][column] * matrix[line][c] / matrix[line][column]) return store def debug(matrix): for line in matrix: string = "" for el in line: reduced_frac = str(el.numerator) + "/" + str(el.denominator) if el.numerator == 0: reduced_frac = "0" elif el.denominator == 1: reduced_frac = str(el.numerator) string += "& " + reduced_frac + " " print(string) def main(): a = [[1, 2, 2, 1], \ [-3, 0, 1, -1], \ [-2, -1, 0, -1], \ [-3, -4, -5, 0] \ ] n = 3 for i in range(len(a)): for j in range(len(a[0])): a[i][j] = Frac(a[i][j], 1) debug(a) for it in range(6): flag = 0 for line in range(n): if a[line][n] < 0: mn = 10000 sel_column = 0 for col in range(n): if a[line][col] < 0: if mn > a[line][n] / a[line][col]: mn = a[line][n] / a[line][col] sel_column = col a = pivot(a, line, sel_column) print('Pivot around ' + str(line + 1) + ' ' + str(sel_column + 1)) debug(a) flag = 1 break if flag == 1: continue for column in range(n): if a[n][column] < 0: mn = 10000 sel_line = 0 for line in range(n): if a[line][n] == 0: continue if a[line][column] > 0: if mn > a[line][n] / a[line][column]: mn = a[line][n] / a[line][column] sel_line = line a = pivot(a, sel_line, column) print('Pivot around ' + str(sel_line + 1) + ' ' + str(column + 1)) debug(a) break print('yello') if __name__=="__main__": main()
{ "repo_name": "rdragos/work", "path": "research/implementations/simplex/main.py", "copies": "1", "size": "2640", "license": "mit", "hash": -3455021598792578000, "line_mean": 29.3448275862, "line_max": 105, "alpha_frac": 0.4007575758, "autogenerated": false, "ratio": 3.6464088397790055, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45471664155790054, "avg_score": null, "num_lines": null }
from fractions import Fraction as Fract import sys # rational paramterization / approximation of bernoulli's lemniscate # traditional form: ( x^2 + y^2 ) ^2 = 2*( x^2 - y^2 ) # chromogeometry form: # x = (blueq/redq) / blueq( blueq/redq, greenq/redq ) # y = (greenq/redq) / blueq( blueq/redq, greenq/redq ) # where q = quadrance between 0,0 and integer point m,n # please see pythbernlem.py for full explanation def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] depth = 13 for m in range(-depth,depth): for n in range(-depth,depth): if redq(0,0,m,n)==0: continue bq,rq,gq = blueq(0,0,m,n),redq(0,0,m,n),greenq(0,0,m,n) x = Fract( Fract(bq,rq), blueq(0,0,Fract(bq,rq),Fract(gq,rq)) ) y = Fract( Fract(gq,rq), blueq(0,0,Fract(bq,rq),Fract(gq,rq)) ) xs += [x] ys += [y] max=max(xs+ys) for i in range(0,2): print xs[i],',',ys[i], print '....' for i in range(0,len(xs)): xs[i] = Fract( xs[i], max ) ys[i] = Fract( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/bernoulli/pythbernlem2.py", "copies": "1", "size": "1332", "license": "bsd-3-clause", "hash": 6925270413695541000, "line_mean": 27.9565217391, "line_max": 68, "alpha_frac": 0.6306306306, "autogenerated": false, "ratio": 2.0683229813664594, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7904263901403049, "avg_score": 0.05893794211268208, "num_lines": 46 }
from fractions import Fraction as Fract ########## # # rational parameterization of the 'dumbbell' p-orbital shape. sort of # like bernoulli's lemniscate, but in 3d. using four input variables, # m1,n1 m2,n2 all rational/integer # # chromogeometry notation is used here. 3 'quadrance' functions, input is 'a,b' # blue quadrance from point (0,0) to point (a,b) = a^2+b^2 # red quadrance from point (0,0) to point (a,b) = a^2-b^2 # green quadrance from point (0,0) to point (a,b) = 2ab # thus "blue/red" = m^2+n^2 / m^2-n^2 # basic equation of lemniscate for x,y: # # (x^2+y^2)^2 = 2*(x^2-y^2) # # (blueq)^2 = 2*redq # # equation of lemniscate inverse (the hyperbola): # # y=1/x # # paramterization of lemniscate inverse (hyperbola): # # x=blue/red y=green/red # # so then, using the paramterization of the hyperbola, from pythhyp*.py, # and the 4-variable paramterization of the sphere, pythsphere*.py, # we sort of 'combine' those techniques. # step one is to say that 'x' and 'l' are going to be the 'distance' from # origin and 'radius' of the 'dumbbell'. now, y and z will help us to make # an actual rational x,y,z point on the surface of the dumbbell. # # now. first we find rational paramterization of x and l. # we know (x^2+l^2)^2 = 2*(x^2-l^2) and some people can use that to find # a rational parameterization. i am not that smart so i use the fact that # hyperbola inverse = lemniscate. # # preliminaries # xh = Fract(blue,red) # yh = Fract(green,red) # OH = blueq(xh,yh) # # we know OH*OL = k^2, because thats what inversion is. similar triangle # hypoteneuses. be rearranging, you find that (xh/xl)^2=oh/ol and thus # xl^2 = xh^2*(ol/oh), but ol/oh is k^1/(oh^2) and we can find oh. # so xl is k/oh * xh. # # so for x and l we can say # # x = k/oh * blue/red and l = k/oh * green/red # # # the next step is noting that z^2+y^2 = l^2. using a similar technique # from paramterizing the sphere we go (z/l)^2 + (y/l)^2 = 1, therefore # z/l = red/blue and y/l = green/blue. thus z = l * red/blue, # and y = l * green/blue. # # # x = Fract(k,OH) * blue1/red1 # l = Fract(k,OH) * green1/red1 # y = l * Fract( green2, blue2 ) # z = l * Fract( red2, blue2 ) # xs,ys,zs=[],[],[] depth=8 k=1 def blueq(a,b): return a*a+b*b def redq(a,b): return a*a-b*b def greenq(a,b): return 2*a*b for m1 in range(-depth,depth): for n1 in range(-depth,depth): for m2 in range(-depth/2,depth/2): for n2 in range(-depth/2,depth/2): blue1,red1,green1 = blueq(m1,n1),redq(m1,n1),greenq(m1,n1) blue2,red2,green2 = blueq(m2,n2),redq(m2,n2),greenq(m2,n2) if red1==0: continue if blue2==0: continue xh = Fract(blue1,red1) yh = Fract(green1,red1) OH = blueq(xh,yh) x = Fract(k,OH) * xh l = Fract(k,OH) * yh y = l * Fract( green2, blue2 ) z = l * Fract( red2, blue2 ) #print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [y] zs += [z] max=max(xs+ys+zs) for i in range(0,len(xs)): xs[i] = Fract( xs[i], max ) ys[i] = Fract( ys[i], max ) zs[i] = Fract( zs[i], max ) print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/ratparam3d/pythdumbell.py", "copies": "1", "size": "3319", "license": "bsd-3-clause", "hash": -842917242504187600, "line_mean": 26.2049180328, "line_max": 79, "alpha_frac": 0.6272973787, "autogenerated": false, "ratio": 2.3032616238723107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3430559002572311, "avg_score": null, "num_lines": null }
from fractions import Fraction as Fract ########## # # rational parameterization of the torus # ######### # # consider a basic torus # # x^2 + y^2 = 1 - l ^2 # l^2 + z^2 = 1 # # use similar method to param of sphere, we get m1,n1,m2,n2 forming the torus. # xs,ys,zs=[],[],[] depth=8 big_radius = 5 small_radius = 2 def blueq(m,n): return m*m+n*n def redq(m,n): return m*m-n*n def greenq(m,n): return 2*m*n for m in range(-depth,depth): for n in range(-depth,depth): for m1 in range(-depth/2,depth/2): for n1 in range(-depth/2,depth/2): if m+n==0: continue if m1+n1==0: continue bq,rq,gq = blueq(m,n),redq(m,n),greenq(m,n) bq1,rq1,gq1 = blueq(m1,n1),redq(m1,n1),greenq(m1,n1) z = small_radius * Fract( rq1, bq1 ) l = small_radius * Fract( gq1, bq1 ) x = (big_radius-l) * Fract( rq, bq ) y = (big_radius-l) * Fract( gq, bq ) print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [y] zs += [z] max=max(xs+ys+zs) for i in range(0,len(xs)): xs[i] = Fract( xs[i], max ) ys[i] = Fract( ys[i], max ) zs[i] = Fract( zs[i], max ) print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/ratparam3d/pythtorus.py", "copies": "1", "size": "1354", "license": "bsd-3-clause", "hash": -7243578622081862000, "line_mean": 20.8387096774, "line_max": 78, "alpha_frac": 0.5731166913, "autogenerated": false, "ratio": 2.1189358372456963, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7853079260721403, "avg_score": 0.06779465356485863, "num_lines": 62 }
from fractions import Fraction as Fract ########## # # rational parameterization of the torus # # # this torus has a non-circular 'tube' cross-section. its kind of warped # triangular. # ######### # theory,briefly: consider a torus. # # x^2 + y^2 = 1 - l ^2 # l^2 + z^2 = 1 # # use similar method to param of sphere, we get m1,n1,m2,n2 forming the torus. # # note chromogeometry notation is used. # # # the 'warped' cross section comes as follows: # # see pythcircwarp.py # # an ordinary circle has this paramterization for rationals m,n: # x=red(0,0,m,n)/blue(0,0,m,n), y=green(0,0,m,n)/blue(0,0,m,n) # # a 'warped' circle can go like this: # x=red(0,0,m,n)/blue(-n,0,m,n), y=green(0,0,m,n)/blue(0,0,m,n) # # so... for the torus... if you use this 'warped' version for 'z' and # 'l' instead of x,y you get a warped cross-section for your torus tube # instead of a circle. # # # in fact, i suspect you could use basically any 2d curve paramterization # here to create any kind of cross section for your torus that you want. # (well almost any...its only stuff that has rational paramaterization ) xs,ys,zs=[],[],[] depth=5 big_radius = 5 small_radius = 2 def blueq(m,n): return m*m+n*n def redq(m,n): return m*m-n*n def greenq(m,n): return 2*m*n def blueq_pts(a1,b1,a2,b2): return (a2-a1)*(a2-a1)+(b2-b1)*(b2-b1) for m in range(-depth,depth): for n in range(-depth,depth): for m1 in range(-depth,depth): for n1 in range(-depth,depth): if m+n==0: continue if m1+n1==0: continue bq,rq,gq = blueq(m,n),redq(m,n),greenq(m,n) bq1,rq1,gq1 = blueq(m1,n1),redq(m1,n1),greenq(m1,n1) wbq1 = blueq_pts(-n1,0,m1,n1) z = small_radius * Fract( rq1, wbq1 ) l = small_radius * Fract( gq1, bq1 ) x = (big_radius-l) * Fract( rq, bq ) y = (big_radius-l) * Fract( gq, bq ) print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [z] zs += [y] max=max(xs+ys+zs) for i in range(0,len(xs)): xs[i] = Fract( xs[i], max ) ys[i] = Fract( ys[i], max ) zs[i] = Fract( zs[i], max ) print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/ratparam3d/pythtorus3.py", "copies": "1", "size": "2299", "license": "bsd-3-clause", "hash": 1912181482502070500, "line_mean": 25.125, "line_max": 78, "alpha_frac": 0.6180948238, "autogenerated": false, "ratio": 2.240740740740741, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.804680008965985, "avg_score": 0.062407094976178135, "num_lines": 88 }
from fractions import Fraction as Fr import sys import numpy as np import matplotlib.pylab as plt def plot(xs, ys): maxx=max(xs) minx=min(xs) maxy=max(ys) miny=min(ys) fig,ax = plt.subplots(figsize=(8,8)) ax.set_xlim([minx-2,maxx+2]) ax.set_ylim([miny-2,maxy+2]) ax.scatter(xs,ys) ax.plot(xs,ys) plt.show() class vector: x,y=0,0 def __init__(self,x1,y1): self.x=x1 self.y=y1 def __str__(self): return '['+str(self.x)+','+str(self.y)+']' def __repr__(self): return self.__str__() def split(v): mx=Fr(v.x,2) my=Fr(v.y,2) qx=Fr(v.x,4) qy=Fr(v.y,4) nx = mx-qy ny = my-qx v1 = vector(nx,ny) v2 = vector(v.x-nx,v.y-ny) return v1, v2 vecs = [vector(1,0)] xs,ys=[],[] curs = vector(0,0) depth=10 for i in range(depth): newvecs=[] for v in vecs: curs.x += v.x curs.y += v.y xs+=[curs.x] ys+=[curs.y] nv1, nv2 = split(v) newvecs += [nv1] newvecs += [nv2] vecs = newvecs for i in range(len(xs)): xs[i] = float(xs[i]) ys[i] = float(ys[i]) plot(xs,ys)
{ "repo_name": "donbright/piliko", "path": "phyllo/grow.py", "copies": "1", "size": "1060", "license": "bsd-3-clause", "hash": -1157534941902116900, "line_mean": 17.9285714286, "line_max": 62, "alpha_frac": 0.5594339623, "autogenerated": false, "ratio": 2.124248496993988, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7782953519543946, "avg_score": 0.08014578795000842, "num_lines": 56 }
from fractions import Fraction as rational import Environment import Exceptions import Schemify import Evaluate import Parser if __name__ == '__main__': '''Run from the command line.''' import os, sys # Create the base environment. base_environment = Environment.Environment() # Load the global environment. if os.path.isdir('globals'): base_environment.Import('globals') # Run files as given. if len(sys.argv) > 1: for filename in sys.argv[:1]: base_environment.Load(Evaluate, filename) # Start the REPL. # Generate a parser. parse = Parser.Parser() # Keep going until (exit) or (quit) while True: code = '' # Read at least one line, until parens match. # TODO: Add scheme-like tab support (maybe?) lparens = 0 rparens = 0 print '\nSchempy>', while code == '' or lparens > rparens: if code != '': print ' ', code += raw_input('') lparens = code.count('(') + code.count('[') rparens = code.count(')') + code.count(']') # Got the input, try to evaluate it. try: exps = parse(code) for exp in exps: result = Schemify.Schemify(Evaluate.Evaluate(exp, base_environment)) if result: print result # Something broke, report the error. except Exceptions.ParserException as ex: print '\nParse Error: %s' % str(ex) # Something broke, report the error. except Exceptions.SchempyException as ex: print '\nSchempy Error: %s' % str(ex) # Stop requested. except Exceptions.StopException: break
{ "repo_name": "jpverkamp/schempy", "path": "Schempy.py", "copies": "1", "size": "1511", "license": "bsd-3-clause", "hash": 5486998871713610000, "line_mean": 22.609375, "line_max": 72, "alpha_frac": 0.6565188617, "autogenerated": false, "ratio": 3.27765726681128, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44341761285112796, "avg_score": null, "num_lines": null }
from fractions import Fraction, gcd from math import sqrt, ceil from itertools import count def af(x): if x >= 2.0 / (1 + sqrt(5)): return None else: return x / (1 - x - x*x) xx = [(1, 2), (2, 3), (3, 4), (3, 5), (5, 6), (4, 7), (5, 7), (5, 8), (5, 9), (7, 9), (7, 10), (5, 11), (7, 11), (7, 12), (11, 12), (7, 13), (8, 13), (9, 13), (9, 14), (8, 15), (11, 15), (9, 16), (11, 16), (9, 17), (10, 17), (11, 17), (11, 18), (13, 19), (11, 20), (13, 20), (11, 21), (13, 21), (13, 22), (15, 22), (12, 23), (13, 23), (14, 23), (15, 23), (13, 24), (17, 24), (13, 25), (14, 25), (16, 25)] xx = [Fraction(*x) for x in xx] #for x in xx: # a = af(x) # if not a is None: # a = float(a) # print(x, a) counter = 0 last_x = 0 for den in count(2): num = int(last_x * den) while True: while True: num += 1 if gcd(num, den) == 1: break x = Fraction(num, den) a = af(x) a_is_integer = a is not None and a.denominator == 1 #print("{} Af({})={}".format("*" if a_is_integer else " ", x, "NONE" if a == None else float(a))) if a_is_integer: counter += 1 print(counter, int(a), x) last_x = x if counter == 15: quit() if a == None: break
{ "repo_name": "peterstace/project-euler", "path": "OLD_PY_CODE/project_euler_old_old/137/137.py", "copies": "1", "size": "1325", "license": "unlicense", "hash": 415491898630126850, "line_mean": 29.1136363636, "line_max": 404, "alpha_frac": 0.4339622642, "autogenerated": false, "ratio": 2.6185770750988144, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.35525393392988147, "avg_score": null, "num_lines": null }
from fractions import Fraction, gcd from number_theory import isqrt, factors, decomp, prime_sieve, decomp_sieve from math import sqrt SIZE = 1000000000000 found = [] primes = prime_sieve(70000000) for sqrtn in range(1, isqrt(SIZE)): n = sqrtn * sqrtn for d in range(2, sqrtn): q = n // d r = n % d a, b, c = sorted((d, q, r)) if a == 0: continue if Fraction(b, a) == Fraction(c, b): print("n={}, sqrtn={}, pd={}".format(n, sqrtn, decomp(sqrtn))) print(" d = {} = {}".format(d, decomp(d, primes))) print(" q = {} = {}".format(q, decomp(q, primes))) print(" r = {} = {}".format(r, decomp(r, primes))) print(" ratio = {} = {}".format(Fraction(b, a), b / a)) print() found.append(n) break print(sum(found)) quit() """ n=9, sqrtn=3, pd={3: 1} d = 2 = {2: 1} q = 4 = {2: 2} r = 1 = {} n=10404, sqrtn=102, pd={17: 1, 2: 1, 3: 1} d = 72 = {2: 3, 3: 2} q = 144 = {2: 4, 3: 2} r = 36 = {2: 2, 3: 2} n=16900, sqrtn=130, pd={2: 1, 5: 1, 13: 1} d = 75 = {3: 1, 5: 2} q = 225 = {3: 2, 5: 2} r = 25 = {5: 2} n=97344, sqrtn=312, pd={2: 3, 3: 1, 13: 1} d = 92 = {2: 2, 23: 1} q = 1058 = {2: 1, 23: 2} r = 8 = {2: 3} n=576081, sqrtn=759, pd={11: 1, 3: 1, 23: 1} d = 360 = {2: 3, 3: 2, 5: 1} q = 1600 = {2: 6, 5: 2} r = 81 = {3: 4} n=6230016, sqrtn=2496, pd={2: 6, 3: 1, 13: 1} d = 1472 = {2: 6, 23: 1} q = 4232 = {2: 3, 23: 2} r = 512 = {2: 9} n=7322436, sqrtn=2706, pd={11: 1, 41: 1, 2: 1, 3: 1} d = 2420 = {2: 2, 11: 2, 5: 1} q = 3025 = {11: 2, 5: 2} r = 1936 = {2: 4, 11: 2} n=12006225, sqrtn=3465, pd={11: 1, 3: 2, 5: 1, 7: 1} d = 2450 = {2: 1, 5: 2, 7: 2} q = 4900 = {2: 2, 5: 2, 7: 2} r = 1225 = {5: 2, 7: 2} n=36869184, sqrtn=6072, pd={11: 1, 2: 3, 3: 1, 23: 1} d = 5760 = {2: 7, 3: 2, 5: 1} q = 6400 = {2: 8, 5: 2} r = 5184 = {2: 6, 3: 4} n=37344321, sqrtn=6111, pd={97: 1, 3: 2, 7: 1} d = 5292 = {2: 2, 3: 3, 7: 2} q = 7056 = {2: 4, 3: 2, 7: 2} r = 3969 = {3: 4, 7: 2} n=70963776, sqrtn=8424, pd={2: 3, 3: 4, 13: 1} d = 7452 = {2: 2, 3: 4, 23: 1} q = 9522 = {2: 1, 3: 2, 23: 2} r = 5832 = {2: 3, 3: 6} """ SIZE = 100000 pds = decomp_sieve(SIZE) square_residues = [i*i for i in range(1, int(SIZE ** 0.25) + 1)] square_residue_sqrts = [isqrt(r) for r in square_residues] def mul_pd(a, b): c = dict() for p in a.keys() | b.keys(): c[p] = (a[p] if p in a else 0) + (b[p] if p in b else 0) return c def geometric_seq(a, b, c): if a == 0 or b == 0 or c == 0: return False a, b, c = sorted((a, b, c)) return Fraction(b, a) == Fraction(c, b) for sqrt_n in range(1, int(SIZE ** 0.5) + 1): n = sqrt_n * sqrt_n for sqrt_r in square_residue_sqrts: n_minus_r_pd = mul_pd(pds[sqrt_n - sqrt_r], pds[sqrt_n + sqrt_r]) n_minus_r = (sqrt_n - sqrt_r) * (sqrt_n + sqrt_r) for f in factors(n_minus_r_pd): if f * f > n_minus_r: break if geometric_seq(f, n_minus_r // f, sqrt_r * sqrt_r): print(n_minus_r + sqrt_r * sqrt_r)
{ "repo_name": "peterstace/project-euler", "path": "OLD_PY_CODE/project_euler_old_old/141/141.py", "copies": "1", "size": "3128", "license": "unlicense", "hash": -7173329828947846000, "line_mean": 25.0666666667, "line_max": 75, "alpha_frac": 0.4718670077, "autogenerated": false, "ratio": 2.1797909407665506, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8097737168662619, "avg_score": 0.010784155960786395, "num_lines": 120 }
from fractions import Fraction, gcd from string import find, count, split # use this for errors in this module class Error(Exception): pass class Contradiction(Error): pass # kinds of inequalities GT, GE, LE, LT = range(4) comp_str = {GT: '>', GE: '>=', LT: '<', LE: '<='} # swaps GT and LT, GE and LE def comp_reverse(i): return 3 - i # to record where each fact came from ADD, MUL, HYP, FUN = range(4) ############################################################################### # # TERMS # # Add_pair(a1, t1) represents a1 * t1 # # Add_term([(a1, t1), ..., (ak, tk)]) represents a1 * t1 + ... + ak * tk # stored internally as a list of Add_pair's # # Mul_pair((t1, n1)) represents t1 ^ n1 # # Mul_term([(t1, n1), ..., (tk, nk)]) represents t1 ^ n1 * .... * tk ^ nk # stored internally as a list of Mul_pairs # # Func_term(f,[t1,...,tn]) represents f(t1,t2,...,tn) # # An ordering on expressions is defined recursively, using Python's # built-in lexicographic orderings on pairs and lists # # TODO: canonize should check for duplicates and combine them # TODO: complete documentation ############################################################################### class Term: def __repr__(self): return self.__str__() def __str__(self): raise NotImplementedError() def __truediv__(self, other): return self / other def __rtruediv__(self, other): return other * self ** (-1) def __rdiv__(self, other): return (self ** (-1)) * other def __neg__(self): return self * (-1) def __sub__(self, other): return self +other * (-1) def __rsub__(self, other): return (-1) * self +other def __rmul__(self, other): return self * other def __radd__(self, other): return self +other class Const(Term): def __init__(self, name): self.name = name def __str__(self): return "Const({0!s})".format(self.name) def __cmp__(self, other): if isinstance(other, Const): return cmp(self.name, other.name) else: return -1 def __mul__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return Const("0") elif other == 1: return self else: num = Fraction(self.name) return Const(str(num * other)) return other * self def __add__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return self return Add_term([Add_pair(1, self), Add_pair(other, one)]) if isinstance(other, Add_term): addpairs = other.addpairs coeff = 1 pair = next((p for p in addpairs if p.term == self), None) if pair: addpairs.remove(pair) coeff = pair.coeff + 1 addpairs.append(Add_pair(coeff, self)) return Add_term(addpairs) return Add_term([Add_pair(1, self), Add_pair(1, other)]) def __pow__(self, other): if not isinstance(other, (int, float, Fraction)): raise Exception("Cannot have variables in the exponent") if other == 0: return one if other == 1: return self return Mul_term(Mul_pair(self, other)) def __div__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: raise Exception("Cannot divide by 0") if other == 1: return self coeff = (1 / Fraction(other) if isinstance(other, float)\ else Fraction(1, other)) return Add_term([Add_pair(coeff, self)]) return self * other ** (-1) def structure(self): return "Const" one = Const("1") zero = Const("0") class Var(Term): def __init__(self, name): self.name = name def __str__(self): return self.name def __cmp__(self, other): if isinstance(other, Const): return 1 elif isinstance(other, Var): return cmp(self.name, other.name) else: return -1 def __mul__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return zero if other == 1: return self return Add_term([Add_pair(other, self)]) if isinstance(other, Mul_term): mulpairs = other.mulpairs mulpairs.append(Mul_pair(self, 1)) return Mul_term(mulpairs) return Mul_term([Mul_pair(self, 1), Mul_pair(other, 1)]) def __add__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return self return Add_term([Add_pair(1, self), Add_pair(other, one)]) if isinstance(other, Add_term): addpairs = other.addpairs coeff = 1 pair = next((p for p in addpairs if p.term == self), None) if pair: addpairs.remove(pair) coeff = pair.coeff + 1 addpairs.append(Add_pair(coeff, self)) return Add_term(addpairs) return Add_term([Add_pair(1, self), Add_pair(1, other)]) def __pow__(self, other): if not isinstance(other, (int, float, Fraction)): raise Exception("Cannot have variables in the exponent") if other == 0: return one if other == 1: return self return Mul_term(Mul_pair(self, other)) def __div__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: raise Exception("Cannot divide by 0") if other == 1: return self coeff = (1 / Fraction(other) if isinstance(other, float)\ else Fraction(1 / other)) return Add_term([Add_pair(coeff, self)]) return self * other ** (-1) def structure(self): return "Var" class Add_pair: def __init__(self, coeff, term): self.coeff = coeff self.term = term def __str__(self): if self.coeff == 1: return str(self.term) elif self.term == one: return str(self.coeff) else: return str(self.coeff) + "*" + str(self.term) def __repr__(self): return self.__str__() def __cmp__(self, other): return cmp((self.term, self.coeff), (other.term, other.coeff)) # used only to scale an addpair by a constant def __div__(self, factor): num = (Fraction(self.coeff) if isinstance(self.coeff, float)\ else self.coeff) denom = (Fraction(factor) if isinstance(factor, float) else factor) return Add_pair(Fraction(num, denom), self.term) def __mul__(self, factor): return Add_pair(self.coeff * factor, self.term) # this is useful for canonization def __pow__(self, n): return Add_pair(pow(self.coeff, n), Mul_pair(self.term, n)) class Add_term(Term): def __init__(self, l): if isinstance(l, Term): self.addpairs = [Add_pair(1, l)] elif isinstance(l, Add_pair): self.addpairs = [l] elif isinstance(l, list): if not l: self.addpairs = l elif isinstance(l[0], Add_pair): self.addpairs = l else: self.addpairs = [Add_pair(p[0], p[1]) for p in l] else: raise Error("Add_term of:" + str(l)) def __str__(self): return ("(" + " + ".join([str(a) for a in self.addpairs]) + ")") def __cmp__(self, other): if isinstance(other, (Const, Var)): return 1 elif isinstance(other, Add_term): return cmp(self.addpairs, other.addpairs) else: return -1 # used to scale by a constant def __div__(self, factor): if isinstance(factor, (int, float, Fraction)): return Add_term([s / (Fraction(factor)\ if isinstance(factor, float) else factor)\ for s in self.addpairs]) return self * factor ** (-1) def __mul__(self, factor): if isinstance(factor, (int, float, Fraction)): return Add_term([s * factor for s in self.addpairs]) if isinstance(factor, Mul_term): mulpairs = factor.mulpairs mulpairs.append(Mul_pair(self, 1)) return Mul_term(mulpairs) return self * Mul_term([Mul_pair(factor, 1)]) def __add__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return self return self +Add_term([Add_pair(other, one)]) if isinstance(other, Add_term): addpairs = [] addpairs.extend(self.addpairs) for a in other.addpairs: for b in addpairs: if b.term == a.term: addpairs.remove(b) if a.coeff != -b.coeff: addpairs.append(Add_pair(a.coeff + b.coeff, a.term)) break else: addpairs.append(a) # if not addpairs: # print self, other # raise Error("Add_term zero") # return zero return(Add_term(addpairs)) return self +Add_term([Add_pair(1, other)]) def __pow__(self, other): if not isinstance(other, (int, float, Fraction)): raise Exception("Cannot have variables in the exponent") if other == 0: return one if other == 1: return self return Mul_term(Mul_pair(self, other)) def structure(self): s = "AddTerm(" for t in self.addpairs: s += t.term.structure() + "," s = s[:-1] + ")" return s class Mul_pair: def __init__(self, term, exp): self.term = term self.exp = exp def __str__(self): if self.exp == 1: return str(self.term) else: return str(self.term) + "^" + str(self.exp) def __repr__(self): return self.__str__() def __cmp__(self, other): return cmp((self.term, self.exp), (other.term, other.exp)) def __pow__(self, n): if isinstance(n, int) or \ (isinstance(n, Fraction) and n.denominator % 2 == 1): return Mul_pair(self.term, self.exp * n) else: return Mul_pair(Mul_term([self]), n) # allow a constant multiplier, for the multiplicative part class Mul_term(Term): def __init__(self, l, const=1): self.const = const if isinstance(l, Term): self.mulpairs = [Mul_pair(l, 1)] elif isinstance(l, Mul_pair): self.mulpairs = [l] elif isinstance(l, list): if not l: self.mulpairs = l elif isinstance(l[0], Mul_pair): self.mulpairs = l else: self.mulpairs = [Mul_pair(p[0], p[1]) for p in l] else: raise Error("Mul_term of: " + str(l)) for item in self.mulpairs: if not isinstance(item, Mul_pair): print item, 'is not a mul_pair!' raise Exception def __str__(self): if self.const == 1: factorlist = [] else: factorlist = [str(self.const)] factorlist.extend([str(m) for m in self.mulpairs]) return "(" + " * ".join(factorlist) + ")" def __cmp__(self, other): if isinstance(other, (Const, Var, Add_term)): return 1 else: return cmp(self.mulpairs, other.mulpairs) def __mul__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return zero con = self.const * other return Mul_term(self.mulpairs, con) if isinstance(other, Mul_term): mulpairs = list(self.mulpairs) for a in other.mulpairs: for b in mulpairs: if b.term == a.term: mulpairs.remove(b) if a.exp != -b.exp: mulpairs.append(Mul_pair(a.term, a.exp + b.exp)) break else: mulpairs.append(a) return Mul_term(mulpairs, self.const * other.const) return self * Mul_term([Mul_pair(other, 1)]) def __add__(self, other): if isinstance(other, (int, float, Fraction)): if other == 0: return self return Add_term([Add_pair(other, one)]) + self if isinstance(other, Mul_term): return Add_term([Add_pair(1, self), Add_pair(1, other)]) return other + self def __pow__(self, n): if not isinstance(n, (int, float, Fraction)): raise Exception("Cannot have variables in the exponent") mulpairs = [pow(m, n) for m in self.mulpairs] return Mul_term(mulpairs, pow(Fraction(self.const), n)) def __div__(self, other): return self * pow(other, -1) def structure(self): s = "MulTerm(" for t in self.mulpairs: s += t.term.structure() + "," s = s[:-1] + ")" return s class Func_term(Term): def __init__(self, name, args, const=1): self.name = name self.args = [] for a in args: if isinstance(a, Term): self.args.append(a) else: print 'a is not a term, but a... ?', type(a) self.args.append(eval(a)) self.const = const def __add__(self, other): if isinstance(other, Add_term): return other + self if isinstance(other, Func_term) and\ other.name == self.name and other.args == self.args: if other.const + self.const == 0: return zero return Func_term(self.name, self.args, other.const + self.const) return Add_term([Add_pair(1, other)]) + self def __mul__(self, other): if isinstance(other, (int, float, Fraction)): return Func_term(self.name, self.args, self.const * other) if isinstance(other, Mul_term): return other * self return Mul_term([Mul_pair(other, 1)]) * self def __div__(self, other): return self * pow(other, -1) def __pow__(self, n): if not isinstance(n, (int, float, Fraction)): raise Exception("Cannot have variables in the exponent") return Mul_term([Mul_pair(self, n)]) def __cmp__(self, other): if isinstance(other, Func_term): if other.name != self.name: return cmp(self.name, other.name) return cmp(self.args, other.args) return 1 def __str__(self): s = ('' if self.const == 1 else str(self.const) + '*') + self.name + '(' for a in self.args: s += str(a) + ', ' s = s[:-2] + ')' return s def structure(self): s = ('' if self.const == 1 else str(self.const)) + 'Func_term(' for a in self.args: s += a.structure() + ',' s = s[:-1] + ')' return s ############################################################################### # # COMPARISON CLASSES # ############################################################################### # Comparison and its subclasses are used in the Boole interface. class Comparison(): def __init__(self): self.dir = None self.left = None self.right = None # Returns a canonized Zero_comparison def canonize(self): term = self.left - self.right zero_comp = Zero_comparison(term, self.dir) return canonize_zero_comparison(zero_comp) def __str__(self): return "{0!s}{1!s}{2!s}"\ .format(self.left, comp_str[self.dir], self.right) def neg(self): """Return the negated comparison """ raise NotImplementedError() class CompGT(Comparison): # Left and right are terms def __init__(self, left, right): Comparison.__init__(self) self.dir = GT self.left = left self.right = right def neg(self): return CompLE(self.left, self.right) class CompGE(Comparison): # Left and right are terms def __init__(self, left, right): Comparison.__init__(self) self.dir = GE self.left = left self.right = right def neg(self): return CompLT(self.left, self.right) class CompLT(Comparison): # Left and right are terms def __init__(self, left, right): Comparison.__init__(self) self.dir = LT self.left = left self.right = right def neg(self): return CompGE(self.left, self.right) class CompLE(Comparison): # Left and right are terms def __init__(self, left, right): Comparison.__init__(self) self.dir = LE self.left = left self.right = right def neg(self): return CompGT(self.left, self.right) # Comparison between one term a_i and 0 # a_i comp 0 class Zero_comparison_data: def __init__(self, comp, provenance=None): self.comp = comp self.provenance = provenance def to_string(self, term): return str(term) + ' ' + comp_str[self.comp] + ' 0' # comparison between two terms, a_i and a_j # a_i comp coeff * a_j class Comparison_data: def __init__(self, comp, coeff=1, provenance=None): self.comp = comp self.coeff = coeff self.provenance = provenance def to_string(self, term1, term2): if self.coeff == 1: return str(term1) + ' ' + comp_str[self.comp] + ' ' + str(term2) else: return (str(term1) + ' ' + comp_str[self.comp] + ' ' + \ str(self.coeff) + '*' + str(term2)) def __str__(self): return 'comparison: ' + comp_str[self.comp] + ' ' + str(self.coeff) def __repr__(self): return self.__str__() # used to figure out strength of inequalities def ge(self, other): if (self.comp in [LT, LE] and other.comp in [GT, GE]) \ or (self.comp in [GT, GE] and other.comp in [LT, LE]): return True return self.coeff > other.coeff \ or (self.coeff == other.coeff and self.comp in [LT, GT] \ and other.comp in [LE, GE]) def le(self, other): if (self.comp in [LT, LE] and other.comp in [GT, GE]) \ or (self.comp in [GT, GE] and other.comp in [LT, LE]): return True return self.coeff < other.coeff \ or (self.coeff == other.coeff and self.comp in [LT, GT] \ and other.comp in [LE, GE]) def __cmp__(self, other): if self.coeff == other.coeff and self.comp == other.comp: return 0 return 1 # Stores term comp 0 # Used in the additive routine class Zero_comparison: def __init__(self, term, comp): self.term = term self.comp = comp def __str__(self): return str(self.term) + ' ' + comp_str[self.comp] + ' 0' def __repr__(self): return self.__str__() def __eq__(self, other): if not isinstance(other, Zero_comparison): return False return self.comp == other.comp and self.term == other.term # The multiplicative procedure makes use of inequalities like t > 1, where # t is a Mul_term. class One_comparison: def __init__(self, term, comp): self.term = term self.comp = comp def __str__(self): return str(self.term) + ' ' + comp_str[self.comp] + ' 1' def __repr__(self): return self.__str__() ############################################################################### # # CANONIZING TERMS # # A canonical term is one of the following # a variable or the constant 1 # an additive term ((a1, t1), ..., (a1, tk)) where # each ti is a canonical term # (variable, the constant 1, or multiplicative) # t1 < t2 < ... < tk # a1 = 1 (so the term is normalized) # a multiplicative term ((t1, n1), ..., (tk, nk)) where # each ti is a canonical term (variable or additive) # n1 < n2 < ... < nk # # Add_pair(r, t) is said to be canonical if t is a canonical term. # # "canonize" converts any term to a canonical Add_pair # # The order for sorting is built into the term classes. # ############################################################################### def product(l): return reduce((lambda x, y: x * y), l, 1) # returns an Add_pair def canonize(t): if isinstance(t, Const) or isinstance(t, Var): return Add_pair(1, t) elif isinstance(t, Add_term): addpairs = [canonize(p.term) * p.coeff for p in t.addpairs] addpairs.sort() coeff = addpairs[0].coeff if coeff == 0: print t, addpairs term = Add_term([p / coeff for p in addpairs]) if len(term.addpairs) == 1: coeff = coeff * term.addpairs[0].coeff term = term.addpairs[0].term return Add_pair(coeff, term) elif isinstance(t, Mul_term): mulpairs = [pow(canonize(p.term), p.exp) for p in t.mulpairs] mulpairs.sort() coeff = product([p.coeff for p in mulpairs]) * t.const term = Mul_term([p.term for p in mulpairs]) return Add_pair(coeff, term) elif isinstance(t, Func_term): args = t.args nargs = [] for p in args: cp = canonize(p) if cp.coeff == 1: nargs.append(cp.term) else: nargs.append(cp.coeff * cp.term) term = Func_term(t.name, nargs, 1) return Add_pair(t.const, term) def test_canonize(): x = Var("x") y = Var("y") z = Var("z") t1 = Mul_term([(Add_term([(2, x), (-3, y), (1, z)]), 3), (x, 2)]) t2 = Mul_term([(Add_term([(2, x), (-5, y), (1, z)]), 3), (x, 2)]) t3 = Mul_term([(x, 2), (Add_term([(-3, y), (1, z), (2, x)]), 3)]) print "t1 =", t1 print "t2 =", t2 print "t3 =", t3 print "t1 < t2:", t1 < t2 print "t1 < x:", t1 < x print "t1 == t3:", t1 == t3 print "Canonize t1:", canonize(t1) print "Canonize t2:", canonize(t2) print "Canonize t3:", canonize(t3) print "Canonize x:", canonize(x) print "canonize(t1) == canonize(t2):", canonize(t1) == canonize(t3) # Takes an (uncanonized) Zero_comparison. # Returns a canonized Zero_comparison with positive coefficient. def canonize_zero_comparison(h): canon = canonize(h.term) if canon.coeff > 0: return Zero_comparison(canon.term, h.comp) elif canon.coeff < 0: return Zero_comparison(canon.term, comp_reverse(h.comp)) else: raise Error("0 in hypothesis") ############################################################################### # # NAMING SUBTERMS # # The heuristic procedure starts by naming all subterms. We'll use # "IVars" for the name, e.g. a0, a1, a2, ... # ############################################################################### # internal variables -- just an index class IVar(Term, Var): def __init__(self, index): Var.__init__(self, "a" + str(index)) self.index = index def __str__(self): return self.name def __cmp__(self, other): if isinstance(other, Const): return 1 elif isinstance(other, Var): return cmp(self.index, other.index) else: return -1 def __eq__(self, other): # print "IVAR EQ CALLED" if isinstance(other, IVar): return self.index == other.index return False def __ne__(self, other): if isinstance(other, IVar): return self.index != other.index return True # Looks in Heuristic_data H to see if self < other is known. def lt_rel(self, other, H): i, j = self.index, other.index if i > j: return other.gt_rel(self, H) if i == j: return False if i == 0 and j in H.zero_comparisons.keys(): if H.zero_comparisons[j].comp == GT: return True return False signi, signj = H.sign(i), H.sign(j) wsigni, wsignj = H.weak_sign(i), H.weak_sign(j) if wsignj != 0: if signi == -1 and signj == 1: return True if signi == 1 and signj == -1: return False # both signs are the same. if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] for c in comps: if ((wsignj == 1 and ((c.comp == LT and c.coeff <= 1)\ or (c.comp == LE and c.coeff < 1))) or (wsignj == -1 and ((c.comp == LT and (c.coeff < 0 or c.coeff >= 1)) or (c.comp == LE and (c.coeff < 0 or c.coeff > 1))))): return True return False # sign info on right is unknown if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] if (any((c.comp == LT and c.coeff <= 1) or (c.comp == LE and c.coeff < 1)\ for c in comps) and \ any(((c.comp == LT and (c.coeff < 0 or c.coeff >= 1))\ or (c.comp == LE and (c.coeff < 0 or c.coeff > 1)))\ for c in comps)): return True return False def gt_rel(self, other, H): i, j = self.index, other.index if i > j: return other.lt_rel(self, H) if i == j: return False if i == 0 and j in H.zero_comparisons.keys(): if H.zero_comparisons[j].comp == LT: return True return False signi, signj = H.sign(i), H.sign(j) wsigni, wsignj = H.weak_sign(i), H.weak_sign(j) if wsignj != 0: if signi == -1 and signj == 1: return False if signi == 1 and signj == -1: return True # both signs are the same. if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] for c in comps: if ((wsignj == 1 and ((c.comp == GT and c.coeff >= 1)\ or (c.comp == GE and c.coeff > 1))) or (wsignj == -1 and ((c.comp == GT and c.coeff <= 1)\ or (c.comp == GE and c.coeff < 1)))): return True return False # sign info on right is unknown if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] if (any((c.comp == GT and c.coeff >= 1)\ or (c.comp == GE and c.coeff > 1) for c in comps) and any((c.comp == GT and c.coeff <= 1)\ or (c.comp == GE and c.coeff < 1) for c in comps)): return True return False def le_rel(self, other, H): i, j = self.index, other.index if i > j: return other.ge_rel(self, H) if i == j: return True if i == 0 and j in H.zero_comparisons.keys(): if H.zero_comparisons[j].comp in [GT, GE]: return True return False # signi, signj = H.sign(i), H.sign(j) wsigni, wsignj = H.weak_sign(i), H.weak_sign(j) if wsignj != 0: if wsigni == -1 and wsignj == 1: return True if wsigni == 1 and wsignj == -1: return False # both signs are the same. if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] for c in comps: if (c.comp in [LE, LT] and ((wsignj == 1 and c.coeff <= 1) or (wsignj == -1 and ((c.coeff < 0 or c.coeff >= 1))))): return True return False # sign info on right is unknown if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] if (any((c.comp in [LT, LE] and c.coeff <= 1) for c in comps) and any((c.comp in [LT, LE] and (c.coeff < 0 or c.coeff >= 1)) for c in comps)): return True return False def ge_rel(self, other, H): i, j = self.index, other.index if i > j: return other.le_rel(self, H) if i == j: return True if i == 0 and j in H.zero_comparisons.keys(): if H.zero_comparisons[j].comp in [LT, LE]: return True return False # signi, signj = H.sign(i), H.sign(j) wsigni, wsignj = H.weak_sign(i), H.weak_sign(j) if wsignj != 0: if wsigni == -1 and wsignj == 1: return False if wsigni == 1 and wsignj == -1: return True # both signs are the same. if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] for c in comps: if c.comp in [GT, GE] and ((wsignj == 1 and c.coeff >= 1) or (wsignj == -1 and c.coeff <= 1)): return True return False # sign info on right is unknown if (i, j) in H.term_comparisons.keys(): comps = H.term_comparisons[i, j] if (any((c.comp in [GT, GE] and c.coeff >= 1) for c in comps) and any((c.comp in [GT, GE] and c.coeff <= 1) for c in comps)): return True return False def eq_rel(self, other, H): i, j = self.index, other.index if i == j: return True if self -other in H.zero_equations or other - self in H.zero_equations: return True return False def neq_rel(self, other, H): i, j = self.index, other.index if i > j: return other.neq_rel(self, H) if i == j: return False return self.gt_rel(other, H) or self.lt_rel(other, H) # creates a name for every subterm in the list of terms args # returns a list of all subterms (the ith name names the ith subterms) # and dictionaries with all the name definitions def make_term_names(terms): name_defs = {} subterm_list = [one] name_defs[0] = one # makes this term and all subterms have names, defining new names # if necessary; and returns the name # # notes that subterm_list and name_defs are global to this procedure, # which augments them as it recurses through t def process_subterm(t): if t in subterm_list: return IVar(subterm_list.index(t)) else: new_def = None if isinstance(t, Var): new_def = t elif isinstance(t, Add_term): addpairs = [] for a in t.addpairs: addpairs.append(Add_pair(a.coeff, process_subterm(a.term))) new_def = Add_term(addpairs) elif isinstance(t, Mul_term): mulpairs = [] for m in t.mulpairs: mulpairs.append(Mul_pair(process_subterm(m.term), m.exp)) new_def = Mul_term(mulpairs) elif isinstance(t, Func_term): args = [] for m in t.args: args.append(process_subterm(m)) new_def = Func_term(t.name, args, t.const) l = len(subterm_list) # index of new term subterm_list.append(t) name_defs[l] = new_def return IVar(l) for t in terms: process_subterm(t) return subterm_list, name_defs def test_make_term_names(): x = Var("x") y = Var("y") z = Var("z") t1 = Mul_term([(Add_term([(2, x), (-3, y), (1, z)]), 3), (x, 2)]) t2 = Mul_term([(Add_term([(2, x), (-3, y), (1, z)]), 3), (x, 3)]) t3 = Mul_term([(x, 2), (Add_term([(-3, y), (1, z), (2, x)]), 3)]) t4 = Add_term([(2, t1), (3, t2), (1, x)]) terms = [t1, t2, t3, t4] subterm_list, name_defs = make_term_names(terms) print print "Terms:", terms print print "Subterms:" for i in range(len(subterm_list)): print IVar(i), "=", subterm_list[i] print print "Definitions:" for i in range(len(subterm_list)): print IVar(i), "=", name_defs[i]
{ "repo_name": "avigad/boole", "path": "boole/interfaces/ineqs/classes.py", "copies": "1", "size": "33640", "license": "apache-2.0", "hash": -2231618062790129400, "line_mean": 30.234911792, "line_max": 92, "alpha_frac": 0.4906064209, "autogenerated": false, "ratio": 3.7599195260981335, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9697748856502303, "avg_score": 0.010555418099166039, "num_lines": 1077 }
from fractions import Fraction # compute voltage drops across empty hex board, with 1.0 on top and 0.0 on bottom # remove connection between adjacent cells in first and last row, as # these are not in any minimal winning path # notice that node with biggest voltage drop is 2,2, not center :) slim, n = True, 2 assert(n>1) nsq = n*n Voltages = [0.5] * nsq #print(Voltages) Nbrs = [] for j in range(nsq): UL,UR,L,R,DL,DR = j-n, 1+j-n, j-1, j+1, j+n-1, j+n # up left, up right, ... if j==0: if slim: Nbrs.append([DR]) else: Nbrs.append([DR,R]) elif j==nsq-1: if slim: Nbrs.append([UL]) else: Nbrs.append([UL,L]) elif j==n-1: if slim: Nbrs.append([DL,DR]) else: Nbrs.append([DL,DR,L]) elif j== nsq-n: if slim: Nbrs.append([UR,UL]) else: Nbrs.append([UR,UL,R]) elif j<n: if slim: Nbrs.append([DL,DR]) else: Nbrs.append([DL,DR,L,R]) elif j>=nsq-n: if slim: Nbrs.append([UR,UL]) else: Nbrs.append([UR,UL,R,L]) elif 0 == j%n: Nbrs.append([UL,UR,R,DR]) elif n-1 == j%n: Nbrs.append([DR,DL,L,UL]) else: Nbrs.append([UL,UR,L,R,DL,DR]) def show(X,n): print('') for j in range(n): for k in range(n): print X[n*j+k], print('') def flipshow(X,n): print('') for k in range(n): for j in range(n): print int(round(100.0*X[n*j+k])), print('') def update(V,N,n): for j in range(n*n): if j < n: v,c = 1.0, 1 # implicit nbr at top, voltage 1.0 elif j >= n*n-n: v,c = 0.0, 1 # implicit nbr at bottom, voltage 0.0 else: v,c = 0.0, 0 for k in N[j]: v+= V[k] c += 1 V[j] = v/c def VDrops(V,Nbrs,n): Drops = [] #for j in range(n): # Drops.append(1.0-V[j]) #for j in range(n,n*n): for j in range(n*n): delta, v = 0.0, V[j] if j<n: delta = 1.0-V[j] # implicit nbr for k in Nbrs[j]: if V[k] > v: delta += V[k] - v Drops.append(delta) return Drops #show(Nbrs,n) for t in range(3**n): update(Voltages, Nbrs, n) #show(Voltages,n) flipshow(Voltages,n) #for d in Voltages: #print(d, Fraction.from_float(d).limit_denominator(99999999)) D = VDrops(Voltages,Nbrs,n) show(D,n) flipshow(D,n)
{ "repo_name": "ryanbhayward/games-puzzles-algorithms", "path": "simple/hex/voltage/volt.py", "copies": "1", "size": "2207", "license": "mit", "hash": 5461877393816983000, "line_mean": 22.9891304348, "line_max": 81, "alpha_frac": 0.566379701, "autogenerated": false, "ratio": 2.3329809725158563, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8127104377022107, "avg_score": 0.05445125929874985, "num_lines": 92 }
from fractions import Fraction from .array import Array class EndOfAlgorithm(Exception): ''' The algorithm stopped on an optimal solution. ''' pass class Unbounded(Exception): ''' There is no optimal solution (unbounded). ''' pass class Empty(Exception): ''' There is no optimal solution (empty). ''' pass def latexWrap(string): return string.replace('_', '\_') def fractionToLatex(n): if abs(n.denominator) == 1: if n >= 0: return '+%s' % n else: return str(n) else: return '%s\\frac{%s}{%s}' % (('+' if n>0 else '-'), abs(n.numerator), abs(n.denominator)) class Simplex: ''' A class to run the simplex algorithm. Uses the tableaux representation. ''' def __init__(self, tableaux = None): if not tableaux is None: self.tableaux = Array(tableaux) self.nbConstraints = len(self.tableaux) - 1 self.nbVariables = len(self.tableaux[0]) - self.nbConstraints - 1 self.basicVariables = [None]+list(range(self.nbVariables, self.nbVariables+self.nbConstraints)) else: self.tableaux = None self.nbVariables = 0 self.nbConstraints = 0 self.basicVariables = [None] self.objective = None self.variableFromIndex = {} self.indexFromVariable = {} def __repr__(self): return '\n'.join([ 'nbConstraints: %d' % self.nbConstraints, 'nbVariables: %d' % self.nbVariables, 'basicVariables: %s' % self.basicVariables, 'variableFromIndex: %s' % self.variableFromIndex, 'indexFromVariable: %s' % self.indexFromVariable, '\n'.join(' '.join(str(self.tableaux[i][j]).ljust(6) for j in range(len(self.tableaux[i]))) for i in range(len(self.tableaux))) ]) @staticmethod def fractionToString(f): if f == 1: return '+' elif f == -1: return '-' elif f > 0: return '+%s' % f else: return str(f) def entryToString(self, entryID, avoid = None, sep = ' ', fractionPrint=None): fractionPrint = fractionPrint or self.fractionToString return sep.join('%s%s' % (fractionPrint((-1 if avoid is None or i < len(self.tableaux[0])-1 else 1)*self.tableaux[entryID][i]), latexWrap(self.variableFromIndex.get(i, ''))) for i in range(len(self.tableaux[0])) if i != avoid and self.tableaux[entryID][i] != 0) def __str__(self, sep = ' '): return '\n'.join([ 'MAXIMIZE', self.entryToString(0), 'SUBJECT TO' ] + [ '%s = %s' % (self.variableFromIndex[self.basicVariables[i]], self.entryToString(i, self.basicVariables[i], sep)) for i in range(1, len(self.tableaux)) ]) def toLatex(self): return '\\begin{align*}\n%s\n\\end{align*}\n\n' % ('\n'.join([ '\\text{Maximize}\\\\', '&%s\\\\' % self.entryToString(0, fractionPrint=fractionToLatex), '\\text{Subject to}\\\\' ] + [ '%s &= %s\\\\' % (latexWrap(self.variableFromIndex[self.basicVariables[i]]), self.entryToString(i, self.basicVariables[i], fractionPrint=fractionToLatex)) for i in range(1, len(self.tableaux)) ])) def choosePivot(self): ''' Choose the entering and leaving variables. ''' column = self.tableaux[0].argmin(0, -1) if column == len(self.tableaux[0]) -1 or self.tableaux[0][column] >= 0: raise EndOfAlgorithm row = None for r in range(1, len(self.tableaux)): if self.tableaux[r][column] > 0: if row is None: row = r elif self.tableaux[r][-1]/self.tableaux[r][column] < self.tableaux[row][-1]/self.tableaux[row][column]: row = r if row is None: raise Unbounded('Variable %d' % column) return row, column def performPivot(self, row, column, verbose = False, latex=None): ''' Perform a pivot, given the entering and leaving variables. ''' if verbose: print('Entering variable: %s' % self.variableFromIndex[column]) print('Leaving variable: %s' % self.variableFromIndex[self.basicVariables[row]]) if latex: latex.write('Entering variable: $%s$\n\n' % latexWrap(self.variableFromIndex[column])) latex.write('Leaving variable: $%s$\n\n' % latexWrap(self.variableFromIndex[self.basicVariables[row]])) self.basicVariables[row] = column self.tableaux[row]/=self.tableaux[row][column] for r in range(len(self.tableaux)): if r != row: coeff = self.tableaux[r][column] self.tableaux[r] -= coeff*self.tableaux[row] if verbose: print(self, '\n') if latex: latex.write(self.toLatex()) def runSimplex(self, verbose = False, latex=None): ''' Run the basic simplex (without first phase). ''' while(True): try: row, column = self.choosePivot() except EndOfAlgorithm: break self.performPivot(row, column, verbose, latex) return self.tableaux[0][-1] def addVariable(self): ''' Add a new variable. ''' self.tableaux.addColumn(Fraction(-1)) self.tableaux[0][0] = Fraction(1) self.basicVariables = [None]+[x+1 for x in self.basicVariables[1:]] self.nbVariables += 1 self.variableFromIndex = {i+1:var for i, var in self.variableFromIndex.items()} self.variableFromIndex[0] = '_phase1_' self.indexFromVariable = {var:i+1 for var, i in self.indexFromVariable.items()} self.indexFromVariable['_phase1_'] = 0 def removeVariable(self): ''' Remove the variable which was added by addVariable. ''' if 0 in self.basicVariables: row = self.basicVariables.index(0) assert self.tableaux[row][-1] == 0 column = 1 while column < len(self.tableaux[row]) and self.tableaux[row][column] == 0: column += 1 assert column < len(self.tableaux[row]) self.performPivot(row, column) self.tableaux.removeColumn() self.nbVariables -= 1 self.basicVariables = [None]+[x-1 for x in self.basicVariables[1:]] self.variableFromIndex = {i-1:var for i, var in self.variableFromIndex.items() if i != 0} self.indexFromVariable = {var:i-1 for var, i in self.indexFromVariable.items() if i != 0} def firstPhaseLeavingVariable(self): ''' Choose the leaving variable of the first phase's first pivot. ''' imin = 1 for i in range(2, len(self.tableaux)): if self.tableaux[i][-1] < self.tableaux[imin][-1]: imin = i return imin, self.tableaux[imin][-1] def updateObjective(self): ''' Update the objective function after the first phase. ''' for row, column in enumerate(self.basicVariables): if column is None: continue self.tableaux[0] -= self.tableaux[0][column]*self.tableaux[row] def solve(self, verbose = False, latex=None): ''' Perform the whole simplex algorithm, first phase included. ''' if verbose: print(self, '\n') if latex: latex.write(self.toLatex()) firstPhaseVariable, constantValue = self.firstPhaseLeavingVariable() if verbose: print('\n\n# FIRST PHASE\n') if latex: latex.write('\\section*{First phase}\n\n') if constantValue < 0: objective = self.tableaux[0].copy() self.tableaux[0] = self.tableaux[0].__class__([0]*len(self.tableaux[0])) self.addVariable() if verbose: print(self, '\n') if latex: latex.write(self.toLatex()) self.performPivot(firstPhaseVariable, 0, verbose, latex) if self.runSimplex(verbose, latex) != 0: raise Empty self.removeVariable() for i, col in enumerate(objective): self.tableaux[0][i] = objective[i] self.updateObjective() if verbose: print('Remove the variable and put back the objective function:') print(self, '\n') if latex: latex.write('Remove the variable and put back the objective function:\n') latex.write(self.toLatex()) if verbose: print('\n\n# SECOND PHASE\n') if latex: latex.write('\\section*{Second phase}\n\n') opt = self.runSimplex(verbose, latex) optSol = {self.variableFromIndex[varID] : Fraction(0) for varID in range(self.nbVariables)} for constraint in range(1, self.nbConstraints+1): if self.basicVariables[constraint] < self.nbVariables: # not a slack variable optSol[self.variableFromIndex[self.basicVariables[constraint]]] = self.tableaux[constraint][-1] return opt, optSol
{ "repo_name": "Ezibenroc/simplex", "path": "simplex/simplex.py", "copies": "1", "size": "9469", "license": "mit", "hash": 3189466330715884000, "line_mean": 37.4918699187, "line_max": 139, "alpha_frac": 0.5549688457, "autogenerated": false, "ratio": 3.883921246923708, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49388900926237084, "avg_score": null, "num_lines": null }
from fractions import Fraction from collections import namedtuple import math class Durations(object): whole = Fraction(1, 1) dot_half = Fraction(3,4) half = Fraction(1, 2) dot_quarter = Fraction(3, 8) quarter = Fraction(1, 4) dot_eighth = Fraction(3, 16) eighth = Fraction(1, 8) dot_sixteenth = Fraction(3, 32) sixteenth = Fraction(1, 16) dot_thirtysecond = Fraction(3, 64) thirtysecond = Fraction(1, 32) dot_sixtyfourth = Fraction(3, 128) sixtyfourth = Fraction(1, 64) meter = namedtuple("meter", "numerator denominator duration") meters = {"6/4": meter(6, 4, Durations.whole + Durations.half), "4/4": meter(4, 4, Durations.whole), "3/4": meter(3, 4, Durations.dot_half), "2/4": meter(2, 4, Durations.half), "12/8": meter(12, 8, Durations.dot_quarter * 4), "9/8": meter(9, 8, Durations.dot_half + Durations.dot_quarter), "6/8": meter(6, 8, Durations.dot_half), "3/8": meter(3, 8, Durations.dot_quarter), "2/8": meter(2, 8, Durations.quarter)} class TabDrawer(object): def __init__(self, tab, top=20, spacing=18): self.tab = tab self.string_count = len(self.tab["strings"]) self.top = top self.spacing = spacing self.measure_duration = meters[tab["meter"]].duration self.min_space = 20 # start with an irrationally large minimum duration self.min_duration = Durations.whole # find the shortest duration in the tab for duration in [note[0] for note in self.tab["content"]]: if duration < self.min_duration: self.min_duration = duration def _note_space(self, duration): return (self.min_space * (math.log(duration / self.min_duration, 2) + 1)) def draw(self, canvas): x = 20 canvas.draw_strings(self.top, self.spacing, self.string_count) canvas.draw_strings(self.top + self.spacing * 10, self.spacing, self.string_count) for note in self.tab["content"]: for glyph in note[1]: symbol, string = glyph canvas.draw_note(symbol, string, x, self.top, self.spacing) x += self._note_space(note[0]) if __name__ == "__main__": tab = {"meter": "4/4", "partial": 0, "strings": ("e,", "a,", "d", "g", "b", "e'"), "title": "An Example", "composer": "Jason R. Fruit", "content": [(Durations.quarter, [("0", 0), ("1", 1), ("0", 2), ("3", 4)]), (Durations.quarter, [("0", 0), ("1", 1), ("0", 2), ("3", 4)]), (Durations.half, [("0", 1), ("1", 1), ("0", 2), ("3", 4)]), (Durations.quarter, [("0", 0), ("1", 1), ("0", 2), ("3", 4)]), (Durations.quarter, [("0", 0), ("1", 1), ("0", 2), ("3", 4)]), (Durations.half, [("0", 1), ("1", 1), ("0", 2), ("3", 4)])]} td = TabDrawer(tab) td.draw(None)
{ "repo_name": "JasonFruit/Tabinator", "path": "tab.py", "copies": "1", "size": "3667", "license": "unlicense", "hash": -239037586389369630, "line_mean": 34.9509803922, "line_max": 75, "alpha_frac": 0.4346877557, "autogenerated": false, "ratio": 3.851890756302521, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4786578512002521, "avg_score": null, "num_lines": null }
from fractions import Fraction from copy import deepcopy from functools import reduce ENV = {} def scanner(input_str): '''Scans the input string from standard input and replaces '(' with ' [ ' and ')' with ' ] ' ''' split_tokens = [] input_str = input_str.replace('(', ' ( ') input_str = input_str.replace(')', ' ) ') split_tokens = input_str.split() return split_tokens def parser(un_parsed_list_of_tokens): '''sends each un parsed element from un parsed list of tokens and uses item_parser funtion to parse those items''' parsed_list_of_tokens = [] def item_parser(x): '''parses individual items from un_parsed list of tokens''' try: int(x) return (int(x)) except ValueError: return (x) def build_list(un_parsed_tokens): new_list = [] x = 0 if(un_parsed_tokens[x] == '('): x += 1 while(x < len(un_parsed_tokens)): if(un_parsed_tokens[x] == ')'): return new_list # base Return elif(un_parsed_tokens[x] == '('): respective_close_int = find_respective_close(un_parsed_tokens,x) sub_list = build_list(un_parsed_tokens[x:respective_close_int + 1]) x = respective_close_int + 1 new_list.append(sub_list) elif(un_parsed_tokens[x] != ')' or '('): new_list.append(un_parsed_tokens[x]) x += 1 return new_list for x in range(0,len(un_parsed_list_of_tokens)): parsed_list_of_tokens.append(item_parser(un_parsed_list_of_tokens[x])) return build_list(parsed_list_of_tokens) def find_respective_close(token_list,open_index): open_p = 0 close_p = 0 for x in range(open_index,len(token_list)+1): if(token_list[x] == '('): open_p += 1 elif(token_list[x] == ')'): close_p += 1 if (open_p == close_p): return x def eval_and_return(token, fn_env = None): if(type(token) is list): return evaluator(token) elif(type(token) is str): try: return fn_env[token] except (KeyError, TypeError) as e: try: return ENV[token] except KeyError: print ("Variable not found") # else: # try: # return ENV[token] # except KeyError: # print ("Variable not found") elif(type(token) is int): return token elif(type(token) is float): return token def arithmetic_operator(s_expression,fn_env = None): if(s_expression[0] == '+'): if (len(s_expression) == 2): return eval_and_return(s_expression[1]) return reduce((lambda x,y : (eval_and_return(x,fn_env)) + (eval_and_return(y,fn_env))),s_expression[1:]) # testing fn_env if(s_expression[0] == '-'): if(len(s_expression) == 2): return (-1 * eval_and_return(s_expression[1])) return reduce((lambda x,y : (eval_and_return(x,fn_env)) - (eval_and_return(y,fn_env))),s_expression[1:]) # testing fn_env if(s_expression[0] == '*'): if(len(s_expression) == 2): return eval_and_return(s_expression[1]) return reduce((lambda x, y : (eval_and_return(x, fn_env)) * (eval_and_return(y,fn_env))),s_expression[1:]) # testing fn_env if(s_expression[0] == '/'): if(len(s_expression) == 2): # special case to return (/ 5) as (1/5) return 1/eval_and_return(s_expression[1]) return reduce((lambda x,y : (eval_and_return(x,fn_env)) / (eval_and_return(y,fn_env))),s_expression[1:]) # testing fn_env def relational_operator(s_expression): ''' expects a list with first element with either '>' or '<' returns #t or #f based on the operands''' if(len(s_expression) == 2): return '#t' x = 2 for y in range(0,len(s_expression)): if(type(s_expression[y]) == type([])): s_expression[y] = evaluator(s_expression[y]) if(s_expression[0] == '<'): while x < len(s_expression): if ( s_expression[x-1] >= s_expression[x]): return '#f' x += 1 return '#t' if(s_expression[0] == '>'): while x < len(s_expression): if (s_expression[x-1] <= s_expression[x]): return '#f' x += 1 return '#t' if(s_expression[0] == '<='): while x < len(s_expression): if ( s_expression[x-1] > s_expression[x]): return '#f' x += 1 return '#t' if(s_expression[0] == '>='): while x < len(s_expression): if (s_expression[x-1] < s_expression[x]): return '#f' x += 1 return '#t' def bind_variable(s_expression): try: if(s_expression[2][0] == 'lambda'): ENV[s_expression[1]] = s_expression[2] return ENV except TypeError: pass ENV[s_expression[1]] = eval_and_return(s_expression[2]) return ENV # review needed to decide the return type def if_statement(s_expression): if (evaluator(s_expression[1]) == '#t'): if(type(s_expression[2]) == type([])): return evaluator(s_expression[2]) elif(type(s_expression[2]) == type(0)): return s_expression[2] elif(type(s_expression[2] == type(''))): try: return (ENV[s_expression[2]]) except KeyError: print("variable not found") else: if(type(s_expression[3]) == type([])): return evaluator(s_expression[3]) elif(type(s_expression[3]) == type(0)): return s_expression[3] elif(type(s_expression[3] == type(''))): try: return (ENV[s_expression[3]]) except KeyError: print("variable not found") def function_call(s_expression, lambda_expression): fn_env = {} if(len(s_expression[1:]) != len(lambda_expression[1])): raise SyntaxError ("number of actual args and formal args not matching") for x in range(0,len(lambda_expression[1])): # building function_env fn_env[lambda_expression[1][x]] = eval_and_return(s_expression [x+1]) # assigning s_expression's args to saved lambda's variables in function_env dict # return function_env # return for testing purpose # global ENV if(fn_env == {}): fn_env = None # ENV = {**ENV , **function_env} # workaround and needs to be changed print ("lambda expr :",lambda_expression[2],"fn_env",fn_env) return evaluator(lambda_expression[2],fn_env) def evaluator(s_expression, fn_env = None): ''' gets a list as input and dispatches the list to various functions based on the first element of the list ''' if (s_expression[0] == '+' or s_expression[0] == '-' or s_expression[0] == '*' or s_expression[0] == '/'): result = arithmetic_operator(s_expression, fn_env) return result elif(s_expression[0] == '>' or s_expression[0] == '<' or s_expression[0] == '>=' or s_expression[0] == '<='): result = relational_operator(s_expression) return result elif (s_expression[0] == 'define'): bind_variable(s_expression) # review needed to decide what return to put return ENV elif (s_expression[0] == 'if'): return if_statement(s_expression) elif(s_expression[0] == 'begin'): for x in range(0,len(s_expression)): if(type(s_expression[x]) == type([])): result = evaluator(s_expression[x]) if(x == (len(s_expression) - 1)): return result elif(s_expression[0] == 'max' or s_expression[0] == 'min'): result = max_min(s_expression, s_expression[0]) return result elif(s_expression[0] == 'quote'): result = quote_fn(s_expression) return result elif(s_expression[0] in ENV): # user defined function call if type(ENV[s_expression[0]]) == list: if (ENV[s_expression[0]][0] == 'lambda'): lambda_expression = deepcopy(ENV[s_expression[0]]) # point return function_call(s_expression,lambda_expression) def max_min(s_expression, func=None): if(func == 'max'): return max(map(eval_and_return, s_expression[1:])) elif(func == 'min'): return min(map(eval_and_return, s_expression[1:])) def quote_fn(s_expression): s_expression[1] = str(s_expression[1]).replace("[","(").replace("]",")").replace("'",'').replace(",",'') return s_expression[1] def make_float_fraction(float_value): return str(Fraction(float_value).limit_denominator()) if __name__ == '__main__': while True: # REPL input_value = input("manoj's lispy >>> ") result = evaluator((parser(scanner(input_value)))) if(isinstance(result,float)): result = make_float_fraction(result) print ("LISPY output : ",result)
{ "repo_name": "manoj-makkuboy/lisp-scheme-interpreter", "path": "lispy.py", "copies": "1", "size": "9237", "license": "mit", "hash": 3141046700680921000, "line_mean": 31.6395759717, "line_max": 160, "alpha_frac": 0.5416260691, "autogenerated": false, "ratio": 3.5636574074074074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46052834765074074, "avg_score": null, "num_lines": null }
from fractions import Fraction from copy import deepcopy z_val = {} def gcd(a, b): if b == 0: return a return gcd(b, a%b) def lcm(a, b): return a * b / gcd(a, b) class PolyTerm(object): def __init__(self, frac=Fraction(0, 1)): self.coef = frac self.a = [] # a_i^j sub & pow [ [1, 2], [2, 1], ... ] def mul_coef(self, frac): self.coef *= frac def inner_sort(self): self.a = sorted(self.a, reverse=False) def out(self): print("coef: %s, term: %s" % (self.coef, self.a)) class Poly(object): def __init__(self): self.poly = [] def mul_coef(self, coef): for term in self.poly: term.mul_coef(coef) def mul_ai(self, sub): new_poly = deepcopy(self.poly) for term in new_poly: find = False for a in term.a: if a[0] == sub: find = True a[1] += 1 break if not find: term.a.append([sub, 1]) term.inner_sort() self.poly = new_poly def add_poly(self, polyb): ret_poly = Poly() all_terms = [] ret_terms = [] for terma in self.poly: all_terms.append(terma) for termb in polyb.poly: all_terms.append(termb) ll = len(all_terms) for i in range(ll): for j in range(i+1, ll): sta = set([ (s, p) for s, p in all_terms[i].a ] ) stb = set([ (s, p) for s, p in all_terms[j].a ] ) if sta == stb: all_terms[i].coef = all_terms[i].coef + all_terms[j].coef all_terms[j].coef = 0 for term in all_terms: if term.coef != 0: ret_terms.append(term) ret_poly.poly = deepcopy(ret_terms) return ret_poly def get_poly(self): ret = deepcopy(self.poly) return ret def out(self): for term in self.poly: term.out() print("poly end") def get_z_val(n): """ https://en.wikipedia.org/wiki/Cycle_index """ global z_val if n in z_val: return deepcopy(z_val[n]) if n == 0: one = PolyTerm(Fraction(1.0)) poly = Poly() poly.poly = [one] z_val[n] = deepcopy(poly) return z_val[n] res = Poly() for i in range(1, n+1): v1 = get_z_val(n - i) v = deepcopy(v1) v.mul_ai(i) res = res.add_poly(v) res.mul_coef(Fraction(1, n)) z_val[n] = deepcopy(res) return z_val[n] def func(n, m): poly_n = get_z_val(n) poly_m = get_z_val(m) # poly_n.out() # poly_m.out() ret_poly = Poly() for terma in poly_n.poly: for termb in poly_m.poly: new_term = PolyTerm() new_term.coef = terma.coef * termb.coef for ta in terma.a: for tb in termb.a: sa = ta[0] pa = ta[1] sb = tb[0] pb = tb[1] ll = lcm(sa, sb) new_term.a.append([ll, (sa * sb * pa * pb / ll)]) ret_poly.poly.append(new_term) return ret_poly def subs(term, v): total = 1 for a in term.a: total *= v**a[1] return term.coef * total def answer(w, h, s): poly = func(w, h) total = 0 for term in poly.poly: total += subs(term, s) return str(total) def table(): for i in range(1, 11): for j in range(1, 11): if i * j > 25: continue ans = answer(i, j, 2) s = "ans[%s][%s] = %s;" % (i, j, ans) print(s) def main(): with open("out", "w") as f: for i in range(1, 11): for j in range(1, 11): if i * j > 25: continue ans = answer(i, j, 2) s = "%s\n" % (ans) f.write(s) if __name__ == "__main__": table() # main()
{ "repo_name": "ecustacm/ecustacm.github.io", "path": "assets/2017-05-08/a/solution/main.py", "copies": "1", "size": "4094", "license": "mit", "hash": -4697172123889366000, "line_mean": 19.9948717949, "line_max": 77, "alpha_frac": 0.4433317049, "autogenerated": false, "ratio": 3.246629659000793, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.917730794481237, "avg_score": 0.00253068381768463, "num_lines": 195 }
from fractions import Fraction from decimal import Decimal from collections import Counter import itertools as it from math import factorial from dice_roller.DiceParser import DiceParser from dice_roller.DiceThrower import DiceThrower import sympy class DiceProbability(object): parser = DiceParser() def calcThrow(self, dexp='1d1', target=2): parsed_roll = self.parser.parse_input(dexp) numberOfDice = int(parsed_roll['number_of_dice']) numberOfSides = int(parsed_roll['sides']) total_possibilities = numberOfSides ** numberOfDice s_op = parsed_roll['s']['operator'] s_val = parsed_roll['s']['val'] f_op = parsed_roll['f']['operator'] f_val = parsed_roll['f']['val'] dice = Counter(range(1, numberOfSides + 1)) success_set = self.calc(s_op, s_val, dice) fail_set = self.calc(f_op, f_val, dice) success_probability = Fraction(len(success_set), numberOfSides) die_probability = Fraction(len(fail_set), numberOfSides) print('---- Counts') print(total_possibilities) print('---- Win ' + str(target)) chance = self.hit_chance(numberOfDice, target, success_probability) print('{0:.2f}'.format(chance.numerator / Decimal(chance.denominator) * 100)) print('---- Fail') chance = 1 - chance print('{0:.2f}'.format(chance.numerator / Decimal(chance.denominator) * 100)) crit_target = round((numberOfDice / 2) + 1) print('---- Crit Fail ' + str(crit_target)) chance = self.hit_chance(numberOfDice, crit_target, die_probability) print('{0:.2f}'.format(chance.numerator / Decimal(chance.denominator) * 100)) def bruteThrow(self, dexp='1d1', target=2): # parse parsed_roll = self.parser.parse_input(dexp) numberOfDice = int(parsed_roll['number_of_dice']) numberOfSides = int(parsed_roll['sides']) s_op = parsed_roll['s']['operator'] s_val = parsed_roll['s']['val'] f_op = parsed_roll['f']['operator'] f_val = parsed_roll['f']['val'] dice = Counter(range(1, numberOfSides + 1)) total_possibilities = numberOfSides ** numberOfDice success_set = self.calc(s_op, s_val, dice) fail_set = self.calc(f_op, f_val, dice) totalSuccess = 0 totalFails = 0 totalCritFails = 0 crit_target = round((numberOfDice / 2) + 1) for i in it.product(dice, repeat=numberOfDice): successes = 0 fails = 0 totals = Counter(i) for j in success_set: successes += totals[j] for j in fail_set: fails += totals[j] if fails >= crit_target: totalFails += 1 totalCritFails += 1 elif successes >= target: totalSuccess += 1 else: totalFails += 1 win = Fraction(totalSuccess, total_possibilities) fail = Fraction(totalFails, total_possibilities) crits = Fraction(totalCritFails, total_possibilities) print('---- Counts') print(total_possibilities) print('---- Win ' + str(target)) print('{0:.2f}'.format(win.numerator / Decimal(win.denominator) * 100)) print('---- Fail') print('{0:.2f}'.format(fail.numerator / Decimal(fail.denominator) * 100)) print('---- Crit Fail ' + str(crit_target)) print('{0:.2f}'.format(crits.numerator / Decimal(crits.denominator) * 100)) def statThrow(self, dexp='1d1', target=2, pool=100000): dice = DiceThrower() parsed_roll = self.parser.parse_input(dexp) numberOfDice = int(parsed_roll['number_of_dice']) totalSuccess = 0 totalFails = 0 totalCritFails = 0 crit_target = round((numberOfDice / 2) + 1) for i in range(pool): result = dice.throw(dexp) if int(result['fail']) >= crit_target: totalFails += 1 totalCritFails += 1 elif int(result['success']) >= target: totalSuccess += 1 else: totalFails += 1 win = Fraction(totalSuccess, pool) fail = Fraction(totalFails, pool) crits = Fraction(totalCritFails, pool) print('---- Counts') print(pool) print('---- Win ' + str(target)) print('{0:.2f}'.format(win.numerator / Decimal(win.denominator) * 100)) print('---- Fail') print('{0:.2f}'.format(fail.numerator / Decimal(fail.denominator) * 100)) print('---- Crit Fail ' + str(crit_target)) print('{0:.2f}'.format(crits.numerator / Decimal(crits.denominator) * 100)) def calc(self, op, val, space): """Subset of sample space for which a condition is true.""" return {element for element in space if sympy.sympify(str(element) + op + val)} def binomial(self, x, y): try: binom = factorial(x) // factorial(y) // factorial(x - y) except ValueError: binom = 0 return binom def exact_hit_chance(self, n, k, p): """Return the probability of exactly k hits from n dice""" # a hit is a 5 or 6, so 1/3 chance. return self.binomial(n, k) * (p) ** k * (1 - p) ** (n - k) def hit_chance(self, n, k, p): """Return the probability of at least k hits from n dice""" return sum([self.exact_hit_chance(n, x, p) for x in range(k, n + 1)])
{ "repo_name": "pknull/rpg-dice", "path": "dice_roller/DiceProbabilty.py", "copies": "1", "size": "5541", "license": "mit", "hash": 5967422565423916000, "line_mean": 35.2156862745, "line_max": 87, "alpha_frac": 0.5728207905, "autogenerated": false, "ratio": 3.6121251629726205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.468494595347262, "avg_score": null, "num_lines": null }
from fractions import Fraction from functools import reduce from operator import mul def is_curious(num, den): if(num==den): return False num_s, den_s = str(num), str(den) if num_s[1] == den_s[1] == '0': return False try: if num_s[0] == den_s[0] and Fraction(num, den) ==Fraction(int(num_s[1]),int(den_s[1])): return True if num_s[1] == den_s[0] and Fraction(num, den) ==Fraction(int(num_s[0]),int(den_s[1])): return True if num_s[0] == den_s[1] and Fraction(num, den) ==Fraction(int(num_s[1]),int(den_s[0])): return True if num_s[1] == den_s[1] and Fraction(num, den) ==Fraction(int(num_s[0]),int(den_s[0])): return True except: pass return False def find_curious(): for num in range(11, 100): for den in range(num, 100): if is_curious(num, den): print(num, den) yield Fraction(num, den) if __name__ == '__main__': g = find_curious() product = reduce(mul, g) print(product.denominator)
{ "repo_name": "dawran6/project-euler", "path": "33-digit-cancelling-fractions.py", "copies": "1", "size": "1087", "license": "mit", "hash": 7180736491412512000, "line_mean": 30.0571428571, "line_max": 95, "alpha_frac": 0.5427782889, "autogenerated": false, "ratio": 3.0880681818181817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41308464707181813, "avg_score": null, "num_lines": null }
from fractions import Fraction from functools import reduce def findCancelling(): # Need num/denom with at least one digit in common # but not the same or multiple of 10 # i.e. no 0's fracList = [] for i in range(1, 10): for j in range(1, 10): if i == j: continue num = i * 10 + j for k in range(1, 10): denom = i * 10 + k if checkFraction(num, denom, i): fracList.append(Fraction(num, denom)) denom = k * 10 + i if checkFraction(num, denom, i): fracList.append(Fraction(num, denom)) denom = k * 10 + j if checkFraction(num, denom, j): fracList.append(Fraction(num, denom)) denom = j * 10 + k if checkFraction(num, denom, j): fracList.append(Fraction(num, denom)) return fracList def checkFraction(num, denom, digit): original = Fraction(num, denom) if original >= 1: return False dig = str(digit) n1 = str(num).replace(dig, '') n2 = str(denom).replace(dig, '') if not (n1 and n2): return False if Fraction(int(n1), int(n2)) == original: return True fracList = findCancelling() print(fracList) print(reduce(lambda x, y: x*y, fracList, 1))
{ "repo_name": "WalrusCow/euler", "path": "Solutions/problem33.py", "copies": "1", "size": "1365", "license": "mit", "hash": -8759356507908133000, "line_mean": 30.0227272727, "line_max": 57, "alpha_frac": 0.5318681319, "autogenerated": false, "ratio": 3.8022284122562673, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9701448129472865, "avg_score": 0.026529682936680545, "num_lines": 44 }
from fractions import Fraction from itertools import chain, cycle from typing import Generator, Iterable, List, Tuple from ..sqrt import sqrt def convergent_sequence(generator: Iterable[int]) -> \ Generator[Fraction, None, None]: h = (0, 1) k = (1, 0) for a in generator: h = h[1], a * h[1] + h[0] k = k[1], a * k[1] + k[0] yield Fraction(h[-1], k[-1]) def continued_fraction_sqrt(n: int) -> Tuple[List[int], List[int]]: sqrt_n = sqrt(n) remainders = [] remainder = (0, 1) # remainder is an + (sqrt(n) - p) / q and these are initial. continued_fraction = [] while remainder not in remainders: remainders.append(remainder) p, q = remainder q = (n - (p * p)) // q a = int((sqrt_n + p) / q) p = a * q - p continued_fraction.append(a) remainder = (p, q) index = remainders.index(remainder) return continued_fraction[1:index], continued_fraction[index:] def convergents_sqrt(n: int) -> Generator[Fraction, None, None]: initial, repeat = continued_fraction_sqrt(n) convergents = convergent_sequence(chain(initial, cycle(repeat))) yield from convergents
{ "repo_name": "cryvate/project-euler", "path": "project_euler/library/number_theory/continued_fractions.py", "copies": "1", "size": "1208", "license": "mit", "hash": -5600411549018548000, "line_mean": 23.6530612245, "line_max": 68, "alpha_frac": 0.5985099338, "autogenerated": false, "ratio": 3.364902506963788, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9463412440763788, "avg_score": 0, "num_lines": 49 }
from fractions import Fraction from itertools import product, combinations from functools import reduce from operator import mul def sols(i, target, current_subset, pool, pool_rev_acc): s = 0 if pool[i] == target: yield current_subset if i == len(pool) - 1: return if pool_rev_acc[i+1] >= target: for s in sols(i+1, target, current_subset, pool, pool_rev_acc): yield s if target > pool[i]: for s in sols(i+1, target - pool[i], current_subset + (pool[i],), pool, pool_rev_acc): yield s def rev_acc(seq): acc = 0 new = [] for s in reversed(seq): acc += s new.insert(0, acc) return new ################################################################# def find_subsets(target, pool): q = dict() remaining = [sum(pool[i:]) for i in range(len(pool))] for p, r in zip(pool, remaining): #print("p", p) #remove any that won't make it to the target keys_to_remove = [val for val in q if val + r < target] for key in keys_to_remove: del q[key] #for each in q, add in q+p to_add = [] for val in q: new_val = p + val if new_val > target: continue if new_val in q: q[new_val] += q[val] else: to_add.append((new_val, q[val])) for val, count in to_add: q[val] = count #add in p if r >= target: if p in q: q[p] += 1 else: q[p] = 1 ##### #print("q now has", len(q)) #for val in sorted(q): # print("{:.6} {} {}".format(float(val), val, q[val])) #print() #print(p, len(q)) ##### return 0 if target not in q else q[target] ################################################################ def find_subsets_with_sum_new(pool, target): #make a copy of the list and sort it pool = list(pool) pool.sort() pool.reverse() #set up a dict and accumulated sums (backwards) q = dict() remaining = [sum(pool[i:]) for i in range(len(pool))] #loop through each element in the pool for p, r in zip(pool, remaining): if p == Fraction(1, 900): print(q[Fraction(87811, 176400)]) print(Fraction(88007, 176400) in q) #remove any keys that won't make it to the target q = {k:v for k, v in q.items() if r + k >= target} #for each element in q, add in q + p to_add = dict() for k in q: if p == Fraction(1, 900) and k == Fraction(87811, 176400): print(q[Fraction(87811, 176400)]) print(Fraction(88007, 176400) in q) new_k = k + p if new_k > target: continue if new_k in q: q[new_k] += q[k] else: assert new_k not in to_add to_add[new_k] = q[k] for k, v in to_add.items(): assert k not in q q[k] = v #add in p itself if r >= target: if p in q: q[p] += 1 else: q[p] = 1 #print status print(p, len(q)) for k in sorted(q): if p == Fraction(1, 900) and k == Fraction(88007, 176400): print("HERE") print(" {} {}".format(k, q[k])) print() return 0 if target not in q else q[target] ################################################################# def powerset(iterable): for k in range(len(iterable) + 1): for item in combinations(iterable, k): yield item def find_subsets_with_sum(pool, target): counter = 0 for subset in powerset(pool): if sum(Fraction(1, s*s) for s in subset) == target: counter += 1 print(subset) return counter #return sum(1 if sum(subset) == target else 0 for subset in powerset(pool)) pool = [2,3,4,5,6,7,9,10,12,15,20,28,30,35,36,45,60] pool = [Fraction(1, p*p) for p in pool] print(find_subsets_with_sum_new(pool, Fraction(1, 2))) quit() ################################################################# #SIZE = 45 #pool = tuple(Fraction(1, n*n) for n in range(2, SIZE+1)) #pool_rev_acc = rev_acc(pool) #for s in sols(0, Fraction(1, 2), (), pool, pool_rev_acc): # print(s) #SIZE = 80 #pool = tuple(Fraction(1, n*n) for n in range(2, SIZE+1)) #pool = [] #for nums in product((1, 2, 4, 8, 16, 32, 64), (1, 3, 9, 27), (1, 5, 25), (1, 7, 49), (1, 11)): # n = reduce(mul, nums) # if n == 1: # continue # if n <= SIZE: # pool.append(Fraction(1, n*n)) #pool.sort() #pool.reverse() #pool = [2,3,4,5,6,7,9,10,12,15,20,28,30,35,36,45] #apool = [2,3,4,5,7,12,15,20,28,35] #bpool = [2,3,4,6,7,9,10,20,28,35,36,45] #cpool = [2,3,4,6,7,9,12,15,28,30,35,36,45] #pool = list(set(bpool) | set(cpool) | set(apool)) pool = [2, 3, 4, 5, 6, 7, 9, 10, 12, 15, 20, 28, 30, 35, 36, 45] remaining = [i for i in range(2, 81) if i not in pool] k = 1 while k <= len(remaining): print("K={}".format(k)) for chosen in combinations(remaining, k): frac_pool = [Fraction(1, p*p) for p in pool + list(chosen)] frac_pool.sort() frac_pool.reverse() print(chosen, find_subsets(Fraction(1, 2), frac_pool)) k += 1 if k == 2: break quit() pool = [Fraction(1, p*p) for p in pool] pool.sort() pool.reverse() print(len(pool), pool, "\n") print(find_subsets(Fraction(1, 2), pool))
{ "repo_name": "peterstace/project-euler", "path": "OLD_PY_CODE/project_euler_old_old/152/152.py", "copies": "1", "size": "5595", "license": "unlicense", "hash": 3986781973994174000, "line_mean": 24.9027777778, "line_max": 95, "alpha_frac": 0.4893655049, "autogenerated": false, "ratio": 3.17356778218945, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.416293328708945, "avg_score": null, "num_lines": null }
from fractions import Fraction from math import factorial import random import itertools def cross(A, B): "O conjunto de formas de concatenar os itens de A e B (produto cartesiano)" return {a + b for a in A for b in B } def combos(items, n): "Todas as combinações de n items; cada combinação concatenada em uma string" return {' '.join(combo) for combo in itertools.combinations(items, n) } def escolha(n, c): "Número de formas de escolher c itens de uma lista com n items" return factorial(n) // (factorial(c) * factorial(n - c)) def P(evento, espaco): """A probabilidade de um evento, dado um espaço amostral de resultados equiprováveis. evento: uma coleção de resultados, ou um predicado. espaco: um conjunto de resultados ou a distribuicao de probabilidade na forma de pares {resultado: frequencia}. """ if callable(evento): evento = tal_que(evento, espaco) if isinstance(espaco, ProbDist): return sum(espaco[o] for o in espaco if o in evento) else: return Fraction(len(evento & espaco), len(espaco)) def tal_que(predicado, espaco): """Os resultados no espaço amostral para os quais o predicado é verdadeiro. Se espaco é um conjunto, retorna um subconjunto {resultado, ...} Se espaco é ProbDist, retorna um ProbDist{resultado, frequencia}""" if isinstance(espaco, ProbDist): return ProbDist({o: espaco[o] for o in espaco if predicado(o)}) else: return {o for o in espaco if predicado(o)} class ProbDist(dict): "Uma distribuição de probablidade; um mapeamento {resultado: probabilidade}" def __init__(self, mapping=(), **kwargs): self.update(mapping, **kwargs) total = sum(self.values()) if total != 0: for outcome in self: self[outcome] = self[outcome]/total assert self[outcome] >= 0 def joint(A, B, sep=''): """A probabilidade conjunta de duas distribuições de probabilidade independentes. Resultado é todas as entradas da forma {a+sep+b: P(a)*P(b)}""" return ProbDist({a + sep + b: A[a] * B[b] for a in A for b in B}) ## predicados def soma_eh_primo(r): return eh_primo(sum(r)) def eh_primo(n): return n > 1 and not any(n % i == 0 for i in range(2, n)) def eh_par(n): return n % 2 == 0
{ "repo_name": "jacksongomesbr/academia-md", "path": "probabilidade/funcoes.py", "copies": "1", "size": "2410", "license": "cc0-1.0", "hash": 4627996829514267000, "line_mean": 34.1764705882, "line_max": 115, "alpha_frac": 0.6387959866, "autogenerated": false, "ratio": 3.062740076824584, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42015360634245835, "avg_score": null, "num_lines": null }
from fractions import Fraction from math import pi import numpy as np from bokeh.colors.named import colors from bokeh.io import show from bokeh.models import ColumnDataSource, Plot, PolarTransform from bokeh.plotting import figure, gridplot dark_colors = iter(color for color in colors if color.brightness < 0.6) color_map = {} def rose(k: Fraction, A: float = 1) -> Plot: n = k.numerator d = k.denominator T = d*(2 if n*d % 2 == 0 else 1) angle = np.linspace(0, T*pi, T*100) radius = A*np.cos(float(k)*angle) source = ColumnDataSource(dict(radius=radius, angle=angle)) t = PolarTransform() plot = figure( width=100, height=100, min_border=0, x_axis_type=None, y_axis_type=None, outline_line_color=None, ) if k in color_map: color = color_map[k] else: color = color_map[k] = next(dark_colors) plot.line(x=t.x, y=t.y, line_color=color, source=source) return plot def grid(N: int, D: int): for d in range(1, D + 1): for n in range(1, N + 1): yield rose(Fraction(n, d)) plot = gridplot(list(grid(9, 9)), ncols=9) show(plot)
{ "repo_name": "bokeh/bokeh", "path": "examples/plotting/file/polar.py", "copies": "1", "size": "1159", "license": "bsd-3-clause", "hash": 4887362504728388000, "line_mean": 23.1458333333, "line_max": 71, "alpha_frac": 0.6289905091, "autogenerated": false, "ratio": 3.066137566137566, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41951280752375664, "avg_score": null, "num_lines": null }
from fractions import Fraction from math import pi import numpy as np from bokeh.colors.named import colors from bokeh.io import show from bokeh.models import ColumnDataSource, PolarTransform, Range1d from bokeh.plotting import figure dark_colors = iter(color for color in colors if color.brightness < 0.6) color_map = {} def rose(xy, k: Fraction, A: float = 1) -> None: n = k.numerator d = k.denominator T = d*(2 if n*d % 2 == 0 else 1) angle = np.linspace(0, T*pi, T*100) radius = A*np.cos(float(k)*angle) source = ColumnDataSource(dict(radius=radius, angle=angle)) t = PolarTransform() if k in color_map: color = color_map[k] else: color = color_map[k] = next(dark_colors) r = xy.line(x=t.x, y=t.y, line_color=color, source=source) return r N = D = 9 h = 0.5 plot = figure(width=N*100, height=D*100, x_range=(1-h, N+h), y_range=(D+h, 1-h)) for d in range(1, D + 1): for n in range(1, N + 1): xy = plot.subplot( x_source=Range1d(start=-1, end=1), y_source=Range1d(start=-1, end=1), x_target=Range1d(start=n-h, end=n+h), y_target=Range1d(start=d-h, end=d+h), ) rose(xy, Fraction(n, d)) show(plot)
{ "repo_name": "bokeh/bokeh", "path": "examples/plotting/file/polar_subcoordinates.py", "copies": "1", "size": "1246", "license": "bsd-3-clause", "hash": 7057420847617400000, "line_mean": 24.9583333333, "line_max": 80, "alpha_frac": 0.6107544141, "autogenerated": false, "ratio": 2.8253968253968256, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3936151239496825, "avg_score": null, "num_lines": null }
from fractions import Fraction from math import sqrt from time import time ##half = 1/2 ## ##blue = 3 ##improve = 4/10 ##while True: ## red = blue * improve ## while red > 0: ## total = blue + red ## ## probability = (blue/total) * ((blue - 1) / (total - 1)) ## ## dif = abs(probability - 0.5) ## ## if dif < 0.00000000000001: ## improve = red/blue ## print("Blues: %d Reds: %d Total: %d Improve: %lf" % (blue, red, total, improve)) ## break ## elif probability > half: ## red += 1 ## elif probability < half: ## break ## blue += 1 ##half = Fraction(1, 2) ## ##blue = 3 ##improve = Fraction(4, 10) ##while True: ## red = blue * improve ## while red > 0: ## total = blue + red ## ## probability = Fraction(blue, total) * Fraction(blue - 1, total - 1) ## ## if probability > half: ## red += 1 ## elif probability < half: ## break ## else: ## improve = Fraction(red, blue) ## print("Blues: %d Reds: %d Total: %d" % (blue, red, total)) ## break ## blue += 1 ##half = 1/2 ## ##blue = 15 ##red = 6 ## ##improve = 4/10 ##while True: ## while red > 0: ## total = blue + red ## ## probability = (blue/total) * ((blue - 1) / (total - 1)) ## ## dif = abs(probability - 0.5) ## ## #print("Blues: %d Reds: %d Total: %d Probability: %lf Improve: %lf" % (blue, red, total, probability, improve)) ## ## if dif < 0.000000000000001: ## improve = red/blue ## print("Blues: %d Reds: %d Total: %d Improve: %lf" % (blue, red, total, improve)) ## break ## elif probability > half: ## red += 1 ## elif probability < half: ## break ## blue += 1 ## red = blue * improve ##start = time() ## ##half = Fraction(1, 2) ## ##total = 10 ** 6 ##blue = int(total / sqrt(2)) + 1 ##red = total - blue ## ##improve = Fraction(red, blue) ##found = False ##while not found: ## while red > 0: ## total = blue + red ## ## probability = Fraction(blue, total) * Fraction(blue - 1, total - 1) ## ## ##print("Blues: %d Reds: %d Probability: %s" % (blue, red, str(probability))) ## ## if probability > half: ## red += 1 ## elif probability < half: ## break ## else: ## improve = Fraction(red, blue) ## print("Blues: %d Reds: %d Total: %d" % (blue, red, total)) ## found = True ## break ## blue += 1 ## red = int(blue * improve) ## ##print("Time:", time() - start) """ 1/2 = (blue/total) * ((blue - 1) / (total - 1)) blue * (blue-1) 1 ------------------- = --- total * (total - 1) 2 total = red + blue total - red = blue 2 * (blue*blue - blue) = total*total - total blue * (blue - 1) = (10**24 - 10**12) / 2 blue = sqrt((10**24 - 10**12) / 2) """ ##Blues: 15 Reds: 6 Total: 21 Improve: 0.400000 ##Blues: 85 Reds: 35 Total: 120 Improve: 0.411765 ##Blues: 493 Reds: 204 Total: 697 Improve: 0.413793 ##Blues: 2871 Reds: 1189 Total: 4060 Improve: 0.414141 ##Blues: 16731 Reds: 6930 Total: 23661 Improve: 0.414201 ##Blues: 97513 Reds: 40391 Total: 137904 Improve: 0.414211 ##Blues: 568345 Reds: 235416 Total: 803761 Improve: 0.414213 ##Blues: 3312555 Reds: 1372105 Total: 4684660 Improve: 0.414213 ##Blues: 19306983 Reds: 7997214 Total: 27304197 Improve: 0.414214 ##Blues: 112529326 Reds: 46611172 Total: 159140498 Improve: 0.414214 ##Blues: 15 Reds: 6 Total: 21 Time: 0.000000 ##Blues: 85 Reds: 35 Total: 120 Time: 0.010000 ##Blues: 493 Reds: 204 Total: 697 Time: 0.017000 ##Blues: 2871 Reds: 1189 Total: 4060 Time: 0.031000 ##Blues: 16731 Reds: 6930 Total: 23661 Time: 0.090000 ##Blues: 97513 Reds: 40391 Total: 137904 Time: 0.478000 ##Blues: 568345 Reds: 235416 Total: 803761 Time: 2.464000 ##Blues: 3312555 Reds: 1372105 Total: 4684660 Time: 13.987000 ##Blues: 19306983 Reds: 7997214 Total: 27304197 Time: 80.909000 ##Blues: 112529341 Reds: 46611179 Total: 159140520 Time: 469.191000 ##From this line on, by: euler100.cpp ##Blues: 655869061 Reds: 271669860 Total: 927538921 Time: 36 ##Can't calculate anything beyond this, due to overflow... ##For example... (this is actually wrong - I only noticed when checking for overflow) ##Blues: 3822685023 Reds: 1583407981 Total: 5406093004 Time: 210 ##start = time() ## ##LIMIT = 10**2 # Apparently this logic is correct, but it's still very slow ##blue = int(LIMIT / sqrt(2)) ##red = LIMIT - blue ####blue -= 1 ####red -= 1 ## ##improve_num = red ##improve_den = blue ##total = 0 ##found = False ##while not found: ## while red > 0: ## total = blue + red ## ## num = blue * (blue - 1) ## den = total * (total - 1) ## #### print("Blues: %d Reds: %d Total: %d Time: %f" % #### (blue, red, total, time() - start)) ## print(blue, red, num/den) ## ## if num * 2 == den: ## improve_num = red ## improve_den = blue ## print("Blues: %d Reds: %d Total: %d Time: %f" % ## (blue, red, total, time() - start)) ## found = True ## break ## elif num * 2 > den: ## red += 1 ## #print("next red") ## else: ## #print("next blue") ## break ## blue += 1 ## red = blue * improve_num // improve_den ##Blues: 707119501233 Reds: 292898487629 Total: 1000017988862 Time: 1 ##Blues: 707196729163 Reds: 292930476485 Total: 1000127205648 Time: 7 ##Blues: 707212723591 Reds: 292937101594 Total: 1000149825185 Time: 8 ##Blues: 707235343128 Reds: 292946470913 Total: 1000181814041 Time: 10 ##Blues: 707251337556 Reds: 292953096022 Total: 1000204433578 Time: 15 ##Blues: 707289951521 Reds: 292969090450 Total: 1000259041971 Time: 18 ##Blues: 707305945949 Reds: 292975715559 Total: 1000281661508 Time: 19 ##Blues: 707328565486 Reds: 292985084878 Total: 1000313650364 Time: 20 ##Blues: 707344559914 Reds: 292991709987 Total: 1000336269901 Time: 22 start = time() last_display = start sqrt2 = 2**0.5 #sqrt(2) blue = int(10**12 / sqrt2) while True: total = int(blue * sqrt2) red = total - blue num = blue * (blue - 1) den = total * (total - 1) #print(total, blue, red, num/den) if time() - last_display > 60: print("[Progress] Blues: %d Reds: %d Total: %d Time: %d" % (blue, red, total, int(time() - start))) last_display = time() if num * 2 == den: print("Blues: %d Reds: %d Total: %d Time: %f" % (blue, red, total, time() - start)) if total >= 10**12: break blue += 1 ##Blues: 112529341 Reds: 46611179 Total: 159140520 Time: 6 ##Blues: 655869061 Reds: 271669860 Total: 927538921 Time: 34 ##Blues: 3822685023 Reds: 1583407981 Total: 5406093004 Time: 197 ##Blues: 6989500985 Reds: 2895146102 Total: 9884647087 Time: 367 ##Blues: 8301239106 Reds: 3438485822 Total: 11739724928 Time: 434 ##b = 6989500985 ##t = 9884647087 ##print(Fraction(b, t) * Fraction(b-1, t-1))
{ "repo_name": "feliposz/project-euler-solutions", "path": "python/euler100.py", "copies": "1", "size": "7103", "license": "mit", "hash": 5697255830186038000, "line_mean": 28.4730290456, "line_max": 121, "alpha_frac": 0.5697592567, "autogenerated": false, "ratio": 2.7898664571877454, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8717268874743944, "avg_score": 0.02847136782876015, "num_lines": 241 }
from fractions import Fraction from math import sqrt from time import time # Looking at the data, I stumbled upon 2 "magic" numbers for this # problem. # One is the ratio blue chips / total chips that converges to sqrt(2). # So I use an approximation to get the value of total based on the # current estimate for blue chips. # The other is the ratio between two successive exact solutions. # For example: # Blue Reds Totals # 2871 1189 4060 # 16731 6930 23661 # The tree ratios quickly converge to 5,8284... # 5,827586207 5,82842725 5,827832512 # I took advantage of this to find the next solution very quickly start = time() last_display = start sqrt2 = 2 ** 0.5 sqrt2num = int(sqrt2 * 10**16) sqrt2den = 10**16 blue = 15 while True: total = blue * sqrt2num // sqrt2den red = total - blue num = blue * (blue - 1) den = total * (total - 1) #print(total, blue, red, num/den) if num * 2 == den: print("Blues: %d Reds: %d Total: %d Time: %f" % (blue, red, total, time() - start)) # MAGIC number... actually, if I improve the precision, it # "skips" some numbers. I don't know why yet... blue = blue * 582842 // 100000 - 1 if total >= 10**12: break # Last "MAGIC" improvement didn't land on a solution, increase 1 # and try it blue += 1
{ "repo_name": "feliposz/project-euler-solutions", "path": "python/euler100e.py", "copies": "1", "size": "1383", "license": "mit", "hash": 896459871761372200, "line_mean": 22.8448275862, "line_max": 70, "alpha_frac": 0.6240057845, "autogenerated": false, "ratio": 3.2928571428571427, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4416862927357143, "avg_score": null, "num_lines": null }
from fractions import Fraction from midi import MIDI import numbers import itertools # These functions should remain static if MidiBackend is ever made a class. def insert_keyed(in_list, val, key): # Locate the leftmost value >= x for idx, element in enumerate(in_list): if key(element) >= key(val): in_list.insert(idx, val) return in_list.append(val) def insert_keyed_after(in_list, val, key): # Locate the rightmost value <= x for idx in range(0, len(in_list), -1): element = in_list[idx] if key(element) <= key(val): in_list.insert(idx + 1, val) return in_list.insert(0, val) def parse_frac(infrac): if type(infrac) == str: slash_pos = infrac.find('/') if slash_pos != -1: num = infrac[:slash_pos] den = infrac[slash_pos + 1:] return Fraction(num) / Fraction(den) return Fraction(infrac) def ticks2time(ticks, tickrate): time_frac = Fraction(ticks) / tickrate measures = time_frac // 4 beats = int(time_frac) % 4 remainder = time_frac - (4 * measures) - beats return '{!s:<8}{!s:<8}{!s:<8}'.format(measures, beats, remainder) def time2ticks(time, tickrate): # Converts a string representation of time to ticks. splitted = time.split(':') measures = Fraction(splitted[0]) beats = 0 if len(splitted) >= 2: beats = Fraction(splitted[1]) other_frac = 0 if len(splitted) >= 3: other = splitted[2] other_frac = parse_frac(other) out_beats = 4 * measures + beats + other_frac out_ticks = round(out_beats * tickrate) return out_ticks def skip_spaces(in_str, index, character=None): """ @type in_str: str @type index: int """ return in_str.split(character, index)[index] def instr2num(inst_name): return dict_find(inst_name, MIDI.Number2patch) def num2instr(patch_num): return dict_loose(patch_num, MIDI.Number2patch) def perc2note(perc_name): return dict_find(perc_name, MIDI.Notenum2percussion) def dict_find(value, dic): value = value.replace('_', ' ') result = None if isinstance(value, numbers.Number) or value.isnumeric(): result = int(value) # if result < 0 or result > 127: # raise Exception('Invalid instrument!') else: patch_names = dic.values() # Find all key-insensitive matches. # If there are multiple matches, none of which are perfect, # then error out. matches = [patch for patch in patch_names if patch.lower().find(value.lower()) != -1] matches.sort(key=len) if (len(matches) == 0) or \ (len(matches) != 1 and len(matches[0]) != len(value)): print('Invalid instrument: {}'.format(value)) print('{} matches:'.format(len(matches))) for match in matches: print(match) print('Exact matches will NOT trigger this error, try extending?') raise Exception result = next(key for key, value in dic.items() if value == matches[0]) return result def dict_loose(key, dic): """ :type key: int :type dic: dict :return: str """ return dic.get(key, str(key)) def clip_127(in_val): # Returns a value, error_str tuple. if in_val > 127: return 127, 1 if in_val < 0: return 0, -1 return in_val, 0 def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue=fillvalue)
{ "repo_name": "jimbo1qaz/sseq3midi", "path": "msh/util.py", "copies": "1", "size": "3702", "license": "mit", "hash": -5641433541091159000, "line_mean": 24.5310344828, "line_max": 93, "alpha_frac": 0.5983252296, "autogenerated": false, "ratio": 3.472795497185741, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4571120726785741, "avg_score": null, "num_lines": null }
from fractions import Fraction from numbers import Integral from weakref import WeakValueDictionary class QFormat: """The precision and position of the binary point in a signed fixed point number. """ _instances = WeakValueDictionary() @classmethod def from_str(cls, s): """Create a QFormat from a string of the format 'Qm.n' where m and n are integers. Args: s: A string of the form 'Qm.n' where m is an integer specifying the number of bits of precision in the integer part and n is the number of bits of precision in the fractional part. Returns: A QFormat. """ if not s.startswith("Q"): raise ValueError("Q format {!r} does not conform to Qm.n".format(s)) s_integer, _, s_fraction = s[1:].partition('.') try: integer_bits = int(s_integer) fraction_bits = int(s_fraction) except ValueError: raise ValueError("Q format {!r} does not conform to Qm.n".format(s)) return cls(integer_bits, fraction_bits) @classmethod def from_qformats(cls, *qformats): """Create a QFormat with sufficient precision to represent values with the given QFormats. Args: *qformats: One or more QFormat objects. Returns: A QFormat. Raises: TypeError: If at least one QFormat is not supplied. """ if len(qformats) < 1: raise TypeError("At least one QFormat must be supplied.") max_integer_bits = max(q.integer_bits for q in qformats) max_fraction_bits = max(q.fraction_bits for q in qformats) return cls(max_integer_bits, max_fraction_bits) def __new__(cls, integer_bits, fraction_bits): """Initialize a QFormat with specified integer and fractional precision.""" precision = (integer_bits, fraction_bits) try: obj = cls._instances[precision] except KeyError: obj = super().__new__(cls) obj._integer_bits = integer_bits obj._fraction_bits = fraction_bits cls._instances[precision] = obj return obj @property def integer_bits(self): """The number of bits of integer precision.""" return self._integer_bits @property def fraction_bits(self): """The number of bits of fractional precision.""" return self._fraction_bits @property def denominator(self): """The divisor by which the numerator in a a fixed point value must be divided to give the number value.""" return 2**self.fraction_bits def _max_signed_numerator(self): return 2 ** (self.integer_bits + self.fraction_bits - 1) - 1 def _min_signed_numerator(self): return -(2 ** (self.integer_bits + self.fraction_bits - 1)) def rescale_numerator(self, src_numerator, src_qformat): """Rescale a numerator to a different QFormat. Args: src_numerator: A numerator representing a value in a src_qformat. src_qformat: The QFormat in which src_numerator represents a value. Returns: An integer numerator representing in this QFormat the same value as represented by src_numerator and src_qformat. """ # We use fraction here to implicitly perform the division, rather than true division which is limited by the # precision of floats), or floor division which doesn't round correctly. ratio = Fraction(self.denominator, src_qformat.denominator) numerator = round(src_numerator * ratio) return self.check_numerator(numerator) def check_numerator(self, numerator): """Check that a numerator is within the bound representable by this QFormat. Args: numerator: The integer numerator value to be checked. Returns: The checked numerator (i.e. the argument value) Raises: OverflowError: If numerator is out of bounds. """ assert isinstance(numerator, Integral) lower = self._min_signed_numerator() upper = self._max_signed_numerator() if not lower <= numerator <= upper: raise OverflowError("Numerator {} is out of range {} <= numerator <= {} for {!r}" .format(numerator, lower, upper, self)) return numerator def __repr__(self): return "{}({!r}, {!r})".format(self.__class__.__name__, self._integer_bits, self._fraction_bits) def __str__(self): return "Q{}.{}".format(self._integer_bits, self._fraction_bits)
{ "repo_name": "sixty-north/fixedpointtest", "path": "fixedpoint/qformat.py", "copies": "1", "size": "4682", "license": "mit", "hash": -6998757928772263000, "line_mean": 35.3023255814, "line_max": 116, "alpha_frac": 0.6121315677, "autogenerated": false, "ratio": 4.454804947668887, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5566936515368887, "avg_score": null, "num_lines": null }
from fractions import Fraction from queue import Queue from typing import Callable, Generator, Tuple # noqa: F401 (used in comment) from .euler_totient import phi_range def mediant(left: Fraction, right: Fraction) -> Fraction: return Fraction(left.numerator + right.numerator, left.denominator + right.denominator) def stern_brocot_tree(left: Fraction=Fraction(0, 1), right: Fraction=Fraction(1, 1), classifier: Callable[[Fraction], bool]=None, depth: int=None) -> \ Generator[Fraction, None, None]: queue = Queue() # type: Queue[Tuple[Fraction, Fraction]] queue.put((left, right)) while not queue.empty(): left, right = queue.get() median = mediant(left, right) if classifier is not None and not classifier(median): continue if depth is not None and median.denominator > depth: continue yield median queue.put((left, median)) queue.put((median, right)) def size_stern_brocot_tree(depth: int=None) -> int: return sum(phi_range(depth)) - 1
{ "repo_name": "cryvate/project-euler", "path": "project_euler/library/number_theory/stern_brocot_tree.py", "copies": "1", "size": "1149", "license": "mit", "hash": -4180628722256273400, "line_mean": 27.725, "line_max": 77, "alpha_frac": 0.6153176675, "autogenerated": false, "ratio": 4.074468085106383, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5189785752606383, "avg_score": null, "num_lines": null }
from fractions import Fraction from SB import SB from CH import CH from config import * from GSM import * import numpy as np from convCode import convCode class SCH(CH): __burst__ = SB """ ncc = (decoded_data[ 7] << 2) | (decoded_data[ 6] << 1) | (decoded_data[ 5] << 0); bcc = (decoded_data[ 4] << 2) | (decoded_data[ 3] << 1) | (decoded_data[ 2] << 0); t1 = (decoded_data[ 1] << 10) | (decoded_data[ 0] << 9) | (decoded_data[15] << 8) | (decoded_data[14] << 7) | (decoded_data[13] << 6) | (decoded_data[12] << 5) | (decoded_data[11] << 4) | (decoded_data[10] << 3) | (decoded_data[ 9] << 2) | (decoded_data[ 8] << 1) | (decoded_data[23] << 0); t2 = (decoded_data[22] << 4) | (decoded_data[21] << 3) | (decoded_data[20] << 2) | (decoded_data[19] << 1) | (decoded_data[18] << 0); t3p = (decoded_data[17] << 2) | (decoded_data[16] << 1) | (decoded_data[24] << 0); t3 = 10 * t3p + 1; """ _fields_ = {"ncc":[7,6,5],"bcc":[4,3,2],"t1":[1,0,15,14,13,12,11,10,9,8,23],"t2":[22,21,20,19,18],"t3p":[17,16,24]} def __init__(self): CH.__init__(self) self.name = "SCH" self.hit = {} self.osr = float(SampleRate/SymbolRate) self.ovL = int(SB.overheadL()*self.osr) self.ovS = int(SB.overheadS()*self.osr) self.codec = convCode(convCode.sch_config) def callback(self,b,fn,state): if state.timingSyncState.state==1: p = b.peekL() pos = p.argmax()-self.ovL elif state.timingSyncState.state==2: p = b.peekS() pos = p.argmax() b.setChEst() b.viterbi_detector() self.msg = b.sbm0[3:]+b.sbm1[:-3] """ self.decoded_data = self.conv_decode() self.decode() if self.parity_check()!=0: print "fn",b.fn,"sn",b.sn,"error",self.last_error else: state.bcc = self.info['bcc'] """ self.decoded_data = self.codec.conv_decode(self.msg) self.decode() if self.codec.parity_check(self.decoded_data)!=0: print "fn",b.fn,"sn",b.sn,"error",self.codec.last_error else: state.bcc = self.info['bcc'] state.ncc = self.info['ncc'] state.t1 = self.info['t1'] state.t2 = self.info['t2'] state.t3 = self.info['t3'] sys_fn = self.sysLongFN() state.diff_fn = sys_fn - fn #print state.t1,state.t2,state.t3,state.diff_fn,sys_fn pos -= self.ovS if pos in self.hit: self.hit[pos] += 1 else: self.hit[pos] = 1 return 1,p def frameStart(self): p = 0 h = 0 for pos in self.hit: if self.hit[pos]>h: h=self.hit[pos] p = pos r = 0 for x in range(p-2,p+3): if x in self.hit: r += self.hit[x] self.hit = {} return p,r def sysLongFN(self): tt = ((self.info['t3'] + 26) - self.info['t2']) % 26 fn = self.info['t1']*51*26 + tt*51 + self.info['t3'] self.info['lfn'] = fn return fn def decode(self): self.info = {} for d in SCH._fields_: l = SCH._fields_[d] m = 0 for p in l: m *= 2 m += self.decoded_data[p] self.info[d]=m self.info['t3']=self.info['t3p']*10+1 return self.info def decodeBin(self,bin): self.info = {} for d in SCH._fields_: l = SCH._fields_[d] m = 0 for p in l: m *= 2 m += (bin>>p)&1 self.info[d]=m self.info['t3']=self.info['t3p']*10+1 return self.info
{ "repo_name": "RP7/R7-OCM", "path": "src/host/python/gsmlib/SCH.py", "copies": "2", "size": "3328", "license": "apache-2.0", "hash": 277755715420330600, "line_mean": 22.2727272727, "line_max": 116, "alpha_frac": 0.5438701923, "autogenerated": false, "ratio": 2.365316275764037, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3909186468064037, "avg_score": null, "num_lines": null }
from fractions import Fraction from .simplex import Simplex, Unbounded, Empty, latexWrap, fractionToLatex from .array import Array class Literal: ''' Represents a literal: a variable (a string) with a factor (a fraction). ''' def __init__(self, factor, variable): self.factor = factor self.variable = variable def __repr__(self): return '%s%s' % (self.factor, self.variable) def __eq__(self, other): return self.__dict__ == other.__dict__ def __hash__(self): return str(self).__hash__() def copy(self): return self.__class__(self.factor, self.variable) def copyInv(self): return self.__class__(-self.factor, self.variable) class Expression: ''' Represents an expression: a sum of literals which is between two (or less) bounds. ''' def __init__(self, leftBound=None, rightBound=None, literalList=None, constantTerm=0): self.leftBound = leftBound self.rightBound = rightBound self.literalList = literalList self.constantTerm = constantTerm def __repr__(self): left = '' if self.leftBound is None else '%s <= ' % self.leftBound right = '' if self.rightBound is None else '<= %s' % self.rightBound constant = '' if self.constantTerm == 0 else (' +%s' % self.constantTerm if self.constantTerm > 0 else ' %s'%self.constantTerm) return '%s%s%s%s' % (left, ' '.join(str(x) for x in self.literalList), constant, right) def __eq__(self, other): if self.leftBound != other.leftBound or self.rightBound != other.rightBound or self.constantTerm != other.constantTerm: return False return set(self.literalList) == set(other.literalList) def normalForm(self): ''' Return a list of equivalent expressions, such that each expression is in canonical form (no left bound). ''' left, right = None, None if not self.rightBound is None: right = Expression(None, self.rightBound, [lit.copy() for lit in self.literalList], self.constantTerm) if not self.leftBound is None: left = Expression(None, -self.leftBound, [lit.copyInv() for lit in self.literalList], -self.constantTerm) return [x for x in [left, right] if not x is None] class Variable: ''' Represents a variable (given by a string) and the transformations made to it during the normalization (eventual multiplication by -1, eventual addition of some constant). ''' def __init__(self, name, mult=1, add=0): self.name = name self.mult = mult self.add = add def __repr__(self): return '(%s: %d, %d)' % (self.name, self.mult, self.add) def __eq__(self, other): return self.__dict__ == other.__dict__ def invert(self): self.mult = -self.mult def translate(self, n): self.add += n def computeValue(self, n): return (n-self.add)*self.mult class LinearProgram: def __init__(self): self.objective = None self.objectiveFunction = None self.subjectTo = [] self.bounds = [] self.variables = {} def check(self): ''' Check the integrity of the linear program. ''' for expr, lineno in self.subjectTo + self.bounds: if (not expr.leftBound is None and not expr.rightBound is None and expr.leftBound > expr.rightBound): raise Exception('Error at line %s: impossible bounds.' % lineno) for lit in expr.literalList: if not lit.variable in self.variables: raise Exception('Error at line %s: unknown variable %s.' % (lineno, lit.variable)) for lit in self.objectiveFunction[0].literalList: if not lit.variable in self.variables: raise Exception('Error at line %s: unknown variable %s.' % (self.objectiveFunction[1], lit.variable)) for expr, lineno in self.bounds: if expr.leftBound is None and expr.rightBound is None: raise Exception('Error at line %s: unbounded variable %s.' % (lineno, expr.literalList[0].variable)) self.objectiveFunction = self.objectiveFunction[0] self.subjectTo = [x[0] for x in self.subjectTo] self.bounds = [x[0] for x in self.bounds] def invertVariable(self, variableName): ''' invert(x_1): x'_1:= -x_1 so x_1=-x'_1 ''' self.variables[variableName].invert() for expr in self.subjectTo + [self.objectiveFunction]: for lit in expr.literalList: if lit.variable == variableName: lit.factor = -lit.factor break def translateVariable(self, variableName, n): ''' translate(x_1, n): x'_1:= x_1+n so x_1=x'_1-n ''' self.variables[variableName].translate(n) for expr in self.subjectTo + [self.objectiveFunction]: for lit in expr.literalList: if lit.variable == variableName: expr.constantTerm -= lit.factor*n break def normalizeBounds(self): ''' Transform expr>=bound into -expr<=-bound. ''' for expr in self.bounds: if not expr.rightBound is None and (expr.rightBound <= 0 or expr.leftBound is None): self.invertVariable(expr.literalList[0].variable) expr.leftBound, expr.rightBound = -expr.rightBound, (-expr.leftBound if not expr.leftBound is None else None) if expr.leftBound != 0: self.translateVariable(expr.literalList[0].variable, -expr.leftBound) expr.leftBound, expr.rightBound = 0, (expr.rightBound - expr.leftBound if not expr.rightBound is None else None) if not expr.rightBound is None: self.subjectTo.append(Expression(None, expr.rightBound, expr.literalList)) def normalizeConstraints(self): self.subjectTo = [subexpr for expr in self.subjectTo for subexpr in expr.normalForm()] def replaceUnconstrained(self, var): ''' If x is an unconstrained variable, we replace it by two variables x1 and x2 such that x=x1-x2, with constraints x1>=0 and x2>=0. ''' v1 = '_0_'+var v2 = '_1_'+var self.variables.pop(var) self.variables[v1] = Variable(v1) self.variables[v2] = Variable(v2) l = list(filter(lambda lit: lit.variable == var, self.objectiveFunction.literalList)) if l: # the variable is in the objective function self.objectiveFunction.literalList = list(filter(lambda lit: lit.variable != var, self.objectiveFunction.literalList))\ + [Literal(l[0].factor, v1), Literal(-l[0].factor, v2)] for expr in self.subjectTo: l = list(filter(lambda lit: lit.variable == var, expr.literalList)) if l: # the variable is in the objective function expr.literalList = list(filter(lambda lit: lit.variable != var, expr.literalList))\ + [Literal(l[0].factor, v1), Literal(-l[0].factor, v2)] return v1, v2 def pullUnconstrainedVariables(self): ''' Replace all the unconstrained variables. ''' varBounds = set(expr.literalList[0].variable for expr in self.bounds) var = set(self.variables) unconstrained = var-varBounds self.unconstrained = {} for v in unconstrained: v1, v2 = self.replaceUnconstrained(v) self.unconstrained[v] = v1, v2 def pushUnconstrainedVariables(self, solution): ''' Compute the solution of the unconstrained variables, given the solution of their substitute. ''' for var, (v1, v2) in self.unconstrained.items(): assert(solution[v1] == 0 or solution[v2] == 0) self.variables[var] = Variable(var) if solution[v1] != 0: solution[var] = solution[v1] else: solution[var] = -solution[v2] solution.pop(v1) solution.pop(v2) def normalize(self): ''' Normalize the linear program. ''' self.normalizeBounds() self.normalizeConstraints() self.pullUnconstrainedVariables() def initSimplex(self): ''' Add a simplex attribute corresponding to the linear program. ''' nbVariables = len(self.variables) nbConstraints = len(self.subjectTo) tableaux = Array([[Fraction(0, 1)]*(nbVariables + nbConstraints + 1)\ for i in range(nbConstraints + 1)]) variableFromIndex, indexFromVariable = {}, {} for i, var in enumerate(sorted(self.variables)): variableFromIndex[i] = var indexFromVariable[var] = i for v in range(nbVariables, nbVariables + nbConstraints): variableFromIndex[v] = '_slack_%d' % (v-nbVariables) indexFromVariable['_slack_%d' % (v-nbVariables)] = v objFactor = -1 if self.objective == 'MAXIMIZE' else 1 for lit in self.objectiveFunction.literalList: tableaux[0][indexFromVariable[lit.variable]] = objFactor*lit.factor tableaux[0][-1] = -objFactor*self.objectiveFunction.constantTerm for constraint, expr in enumerate(self.subjectTo): for lit in expr.literalList: tableaux[constraint+1][indexFromVariable[lit.variable]] = lit.factor tableaux[constraint+1][nbVariables+constraint] = Fraction(1) tableaux[constraint+1][-1] = expr.rightBound-expr.constantTerm self.simplex = Simplex(tableaux) self.simplex.basicVariables = [None]+list(range(nbVariables, nbVariables+nbConstraints)) self.simplex.variableFromIndex = variableFromIndex self.simplex.indexFromVariable = indexFromVariable def solve(self, verbose=False, latex=None): ''' Solve the linear program, using the simplex algorithm. ''' self.initSimplex() try: opt, optSol = self.simplex.solve(verbose, latex) if self.objective == 'MINIMIZE': opt = -opt except Unbounded: print('No optimal solution (unbounded).') if latex: latex.write('No optimal solution (unbounded).\n') return except Empty: print('No optimal solution (empty).') if latex: latex.write('No optimal solution (empty).\n') return self.pushUnconstrainedVariables(optSol) print('Optimal solution: %s.' % opt) print('Found with the following affectation of the variables:') for var in sorted(optSol): print('%s = %s' % (var, self.variables[var].computeValue(optSol[var]))) if latex: latex.write('Optimal solution: %s.\n\n' % opt) latex.write('Found with the following affectation of the variables:\n\n') latex.write('\\[\\begin{cases}\n') for var in sorted(optSol): latex.write('%s &= %s\\\\\n' % (latexWrap(var), fractionToLatex(self.variables[var].computeValue(optSol[var])))) latex.write('\\end{cases}\\]\n\n')
{ "repo_name": "Ezibenroc/simplex", "path": "simplex/linearProgram.py", "copies": "1", "size": "11434", "license": "mit", "hash": -3384217499701639000, "line_mean": 41.1918819188, "line_max": 135, "alpha_frac": 0.5936680077, "autogenerated": false, "ratio": 4.048866855524079, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002873227085412162, "num_lines": 271 }
from fractions import Fraction from typing import Tuple import pytest from hypothesis import HealthCheck, assume, example, given, settings from hypothesis.strategies import integers from raiden.tests.unit.transfer.test_channel import make_hash_time_lock_state from raiden.tests.utils import factories from raiden.tests.utils.factories import ( NettingChannelEndStateProperties, NettingChannelStateProperties, ) from raiden.tests.utils.mediation_fees import ( get_amount_with_fees, get_initial_amount_for_amount_after_fees, ) from raiden.transfer.mediated_transfer.initiator import calculate_safe_amount_with_fee from raiden.transfer.mediated_transfer.mediation_fee import ( NUM_DISCRETISATION_POINTS, FeeScheduleState, Interpolate, calculate_imbalance_fees, linspace, ) from raiden.transfer.mediated_transfer.mediator import get_amount_without_fees from raiden.transfer.state import NettingChannelState from raiden.utils.mediation_fees import ppm_fee_per_channel from raiden.utils.typing import ( Balance, FeeAmount, PaymentAmount, PaymentWithFeeAmount, ProportionalFeeAmount, TokenAmount, ) def test_interpolation(): interp = Interpolate((0, 100), (0, 100)) for i in range(101): assert interp(i) == i interp = Interpolate((0, 50, 100), (0, 100, 200)) for i in range(101): assert interp(i) == 2 * i interp = Interpolate((0, 50, 100), (0, -50, 50)) assert interp(40) == -40 assert interp(60) == -30 assert interp(90) == 30 assert interp(99) == 48 interp = Interpolate((0, 100), (Fraction("12.35"), Fraction("67.2"))) assert interp(0) == Fraction("12.35") assert interp(50) == pytest.approx((12.35 + 67.2) / 2) assert interp(100) == Fraction("67.2") def test_imbalance_penalty(): r"""Test an imbalance penalty by moving back and forth The imbalance fee looks like 20 | / | / 10 |\. / | \. / 0 | \/ --------------- 0 50 100 For each input, we first assume the channel is used to forward tokens to a payee, which moves the capacity from x1 to x2. The we assume the same amount is mediated in the opposite direction (moving from x2 to x1) and check that the calculated fee is the same as before just with the opposite sign. """ v_schedule = FeeScheduleState( imbalance_penalty=[ (TokenAmount(0), FeeAmount(10)), (TokenAmount(50), FeeAmount(0)), (TokenAmount(100), FeeAmount(20)), ] ) reverse_schedule = FeeScheduleState( imbalance_penalty=[ (TokenAmount(0), FeeAmount(20)), (TokenAmount(50), FeeAmount(0)), (TokenAmount(100), FeeAmount(10)), ] ) for cap_fees, x1, amount, expected_fee_in, expected_fee_out in [ # Uncapped fees (False, 0, 50, -8, -10), (False, 50, 30, 20, 12), (False, 0, 10, -2, -2), (False, 10, 10, -2, -2), (False, 0, 20, -3, -4), (False, 40, 15, 0, 0), (False, 50, 31, None, 12), (False, 100, 1, None, None), # Capped fees (True, 0, 50, 0, 0), (True, 50, 30, 20, 12), (True, 0, 10, 0, 0), (True, 10, 10, 0, 0), (True, 0, 20, 0, 0), (True, 40, 15, 0, 0), ]: v_schedule.cap_fees = cap_fees amount_with_fees = get_amount_with_fees( amount_without_fees=PaymentWithFeeAmount(amount), balance_in=Balance(x1), balance_out=Balance(100), schedule_in=v_schedule, schedule_out=FeeScheduleState(cap_fees=cap_fees), receivable_amount=TokenAmount(100 - x1), ) if expected_fee_in is None: assert amount_with_fees is None else: assert amount_with_fees is not None assert amount_with_fees - amount == FeeAmount(expected_fee_in) reverse_schedule.cap_fees = cap_fees amount_with_fees = get_amount_with_fees( amount_without_fees=PaymentWithFeeAmount(amount), balance_in=Balance(0), balance_out=Balance(100 - x1), schedule_in=FeeScheduleState(cap_fees=cap_fees), schedule_out=reverse_schedule, receivable_amount=TokenAmount(100), ) if expected_fee_out is None: assert amount_with_fees is None else: assert amount_with_fees is not None assert amount_with_fees - amount == FeeAmount(expected_fee_out) def test_fee_capping(): r""" Test the capping when one section of the fee function crossed from the positive into negative fees. Here, our fee curve looks like: Fee | 5 + |\ | \ 0 +--+-----+-> incoming_amount | 25\ 100 | \ | \ | \ | \ -15 + \ 0 When capping it, we need to insert the intersection point of (25, 0) into our piecewise linear function before capping all y values to zero. Otherwise we would just interpolate between (0, 5) and (100, 0). """ schedule = FeeScheduleState( imbalance_penalty=[(TokenAmount(0), FeeAmount(0)), (TokenAmount(100), FeeAmount(20))], flat=FeeAmount(5), ) fee_func = FeeScheduleState.mediation_fee_func( schedule_in=FeeScheduleState(), schedule_out=schedule, balance_in=Balance(0), balance_out=Balance(100), receivable=TokenAmount(100), amount_with_fees=PaymentWithFeeAmount(5), cap_fees=True, ) assert fee_func(30) == 0 # 5 - 6, capped assert fee_func(20) == 5 - 4 def test_linspace(): assert linspace(TokenAmount(0), TokenAmount(4), 5) == [0, 1, 2, 3, 4] assert linspace(TokenAmount(0), TokenAmount(4), 4) == [0, 1, 3, 4] assert linspace(TokenAmount(0), TokenAmount(4), 3) == [0, 2, 4] assert linspace(TokenAmount(0), TokenAmount(4), 2) == [0, 4] assert linspace(TokenAmount(0), TokenAmount(0), 3) == [0, 0, 0] with pytest.raises(AssertionError): assert linspace(TokenAmount(0), TokenAmount(4), 1) with pytest.raises(AssertionError): assert linspace(TokenAmount(4), TokenAmount(0), 2) def test_rebalancing_fee_calculation(): sample = calculate_imbalance_fees(TokenAmount(200), ProportionalFeeAmount(50_000)) # 5% assert sample is not None assert len(sample) == NUM_DISCRETISATION_POINTS assert all(0 <= x <= 200 for x, _ in sample) assert max(x for x, _ in sample) == 200 assert all(0 <= y <= 10 for _, y in sample) assert max(y for _, y in sample) == 10 # 5% of the 200 TokenAmount capacity sample = calculate_imbalance_fees(TokenAmount(100), ProportionalFeeAmount(20_000)) # 2% assert sample is not None assert len(sample) == NUM_DISCRETISATION_POINTS assert all(0 <= x <= 100 for x, _ in sample) assert max(x for x, _ in sample) == 100 assert all(0 <= y <= 2 for _, y in sample) assert max(y for _, y in sample) == 2 # 2% of the 100 TokenAmount capacity sample = calculate_imbalance_fees(TokenAmount(15), ProportionalFeeAmount(50_000)) # 5% assert sample is not None assert len(sample) == 16 assert all(0 <= x <= 16 for x, _ in sample) assert max(x for x, _ in sample) == 15 assert all(0 <= y <= 1 for _, y in sample) assert max(y for _, y in sample) == 1 # 5% of the 5 rounded up # test rounding of the max_balance_fee calculation sample = calculate_imbalance_fees(TokenAmount(1000), ProportionalFeeAmount(5_490)) # 0.549% assert sample is not None assert len(sample) == NUM_DISCRETISATION_POINTS assert all(0 <= x <= 1000 for x, _ in sample) assert max(x for x, _ in sample) == 1000 assert all(0 <= y <= 5 for _, y in sample) assert max(y for _, y in sample) == 5 # 5.49 is rounded to 5 sample = calculate_imbalance_fees(TokenAmount(1000), ProportionalFeeAmount(5_500)) # 0.55% assert sample is not None assert len(sample) == NUM_DISCRETISATION_POINTS assert all(0 <= x <= 1000 for x, _ in sample) assert max(x for x, _ in sample) == 1000 assert all(0 <= y <= 6 for _, y in sample) assert max(y for _, y in sample) == 6 # 5.5 is rounded to 6 # test cases where no imbalance fee is created assert calculate_imbalance_fees(TokenAmount(0), ProportionalFeeAmount(1)) is None assert calculate_imbalance_fees(TokenAmount(10), ProportionalFeeAmount(0)) is None @pytest.mark.parametrize( "flat_fee, prop_fee, initial_amount, expected_amount", [ # pure flat fee (50, 0, 1000, 1000 - 50 - 50), # proportional fee (0, 1_000_000, 2000, 1000), # 100% per hop mediation fee (0, 100_000, 1100, 1000), # 10% per hop mediation fee (0, 50_000, 1050, 1000), # 5% per hop mediation fee (0, 10_000, 1010, 1000), # 1% per hop mediation fee (0, 10_000, 101, 100), # 1% per hop mediation fee (0, 4_990, 100, 100), # 0,499% per hop mediation fee gets rounded away # mixed tests (1, 500_000, 1000 + 500 + 2, 1000), (10, 500_000, 1000 + 500 + 20, 997), (100, 500_000, 1000 + 500 + 200, 967), # - (1, 100_000, 1000 + 100 + 2, 1000), (10, 100_000, 1000 + 100 + 20, 999), (100, 100_000, 1000 + 100 + 200, 991), # - (1, 10_000, 1000 + 10 + 2, 1000), (10, 10_000, 1000 + 10 + 20, 1000), (100, 10_000, 1000 + 10 + 200, 999), # - (100, 500_000, 1000 + 750, 1000), # - values found in run_test_mediated_transfer_with_fees (0, 200_000, 47 + 9, 47), (0, 200_000, 39 + 8, 39), ], ) def test_get_lock_amount_after_fees(flat_fee, prop_fee, initial_amount, expected_amount): """Tests mediation fee deduction.""" prop_fee_per_channel = ppm_fee_per_channel(ProportionalFeeAmount(prop_fee)) lock = make_hash_time_lock_state(amount=initial_amount) channel_in = factories.create( NettingChannelStateProperties( partner_state=NettingChannelEndStateProperties(balance=TokenAmount(2000)), fee_schedule=FeeScheduleState(flat=flat_fee, proportional=prop_fee_per_channel), ) ) channel_out = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=TokenAmount(2000)), fee_schedule=FeeScheduleState(flat=flat_fee, proportional=prop_fee_per_channel), ) ) locked_after_fees = get_amount_without_fees( amount_with_fees=lock.amount, channel_in=channel_in, channel_out=channel_out ) assert locked_after_fees == expected_amount @pytest.mark.parametrize( "cap_fees, flat_fee, prop_fee, imbalance_fee, initial_amount, expected_amount", [ # No capping of the mediation fees # The higher the imbalance fee, the stronger the impact of the fee iteration (False, 0, 0, 10_000, 50_000, 50_000 + 2_000), (False, 0, 0, 20_000, 50_000, 50_000 + 3_995), (False, 0, 0, 30_000, 50_000, 50_000 + 5_910), (False, 0, 0, 40_000, 50_000, 50_000 + 7_613), (False, 0, 0, 50_000, 50_000, 50_000 + 9_091), # Capping of mediation fees (True, 0, 0, 10_000, 50_000, 50_000), (True, 0, 0, 20_000, 50_000, 50_000), (True, 0, 0, 30_000, 50_000, 50_000), (True, 0, 0, 40_000, 50_000, 50_000), (True, 0, 0, 50_000, 50_000, 50_000), ], ) def test_get_lock_amount_after_fees_imbalanced_channel( cap_fees, flat_fee, prop_fee, imbalance_fee, initial_amount, expected_amount ): """Tests mediation fee deduction.""" balance = TokenAmount(100_000) prop_fee_per_channel = ppm_fee_per_channel(ProportionalFeeAmount(prop_fee)) imbalance_fee = calculate_imbalance_fees( channel_capacity=balance, proportional_imbalance_fee=ProportionalFeeAmount(imbalance_fee) ) lock = make_hash_time_lock_state(amount=initial_amount) channel_in = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=TokenAmount(0)), partner_state=NettingChannelEndStateProperties(balance=balance), fee_schedule=FeeScheduleState( cap_fees=cap_fees, flat=FeeAmount(flat_fee), proportional=prop_fee_per_channel, imbalance_penalty=imbalance_fee, ), ) ) channel_out = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=balance), partner_state=NettingChannelEndStateProperties(balance=TokenAmount(0)), fee_schedule=FeeScheduleState( cap_fees=cap_fees, flat=FeeAmount(flat_fee), proportional=prop_fee_per_channel, imbalance_penalty=imbalance_fee, ), ) ) locked_after_fees = get_amount_without_fees( amount_with_fees=lock.amount, channel_in=channel_in, channel_out=channel_out ) assert locked_after_fees == expected_amount @given( integers(min_value=0, max_value=100), integers(min_value=0, max_value=10_000), integers(min_value=0, max_value=50_000), integers(min_value=1, max_value=90_000_000_000_000_000), integers(min_value=1, max_value=100_000_000_000_000_000), integers(min_value=1, max_value=100_000_000_000_000_000), ) @settings(suppress_health_check=[HealthCheck.filter_too_much]) def test_fee_round_trip(flat_fee, prop_fee, imbalance_fee, amount, balance1, balance2): """Tests mediation fee deduction. First we're doing a PFS-like calculation going backwards from the target amount to get the amount that the initiator has to send. Then we calculate the fees from a mediator's point of view and check if `amount_with_fees - fees = amount`. """ # Find examples where there is a reasonable chance of succeeding amount = int(min(amount, balance1 * 0.95 - 1, balance2 * 0.95 - 1)) assume(amount > 0) total_balance = TokenAmount(100_000_000_000_000_000_000) prop_fee_per_channel = ppm_fee_per_channel(ProportionalFeeAmount(prop_fee)) imbalance_fee = calculate_imbalance_fees( channel_capacity=total_balance, proportional_imbalance_fee=ProportionalFeeAmount(imbalance_fee), ) channel_in = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=total_balance - balance1), partner_state=NettingChannelEndStateProperties(balance=balance1), fee_schedule=FeeScheduleState( cap_fees=False, flat=FeeAmount(flat_fee), proportional=prop_fee_per_channel, imbalance_penalty=imbalance_fee, ), ) ) channel_out = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=balance2), partner_state=NettingChannelEndStateProperties(balance=total_balance - balance2), fee_schedule=FeeScheduleState( cap_fees=False, flat=FeeAmount(flat_fee), proportional=prop_fee_per_channel, imbalance_penalty=imbalance_fee, ), ) ) # How much do we need to send so that the target receives `amount`? PFS-like calculation. fee_calculation = get_initial_amount_for_amount_after_fees( amount_after_fees=PaymentAmount(amount), channels=[(channel_in, channel_out)] ) assume(fee_calculation) # There is not enough capacity for the payment in all cases assert fee_calculation # How much would a mediator send to the target? Ideally exactly `amount`. amount_without_margin_after_fees = get_amount_without_fees( amount_with_fees=fee_calculation.total_amount, channel_in=channel_in, channel_out=channel_out, ) assume(amount_without_margin_after_fees) # We might lack capacity for the payment assert abs(amount - amount_without_margin_after_fees) <= 1 # Equal except for rounding errors # If we add the fee margin, the mediator must always send at least `amount` to the target! amount_with_fee_and_margin = calculate_safe_amount_with_fee( fee_calculation.amount_without_fees, FeeAmount(sum(fee_calculation.mediation_fees)) ) amount_with_margin_after_fees = get_amount_without_fees( amount_with_fees=amount_with_fee_and_margin, channel_in=channel_in, channel_out=channel_out ) assume(amount_with_margin_after_fees) # We might lack capacity to add margins assert amount_with_margin_after_fees >= amount @example(flat_fee=0, prop_fee=0, imbalance_fee=1277, amount=1, balance1=33, balance2=481) @given( integers(min_value=0, max_value=100), integers(min_value=0, max_value=10_000), integers(min_value=0, max_value=50_000), integers(min_value=1, max_value=90_000_000_000_000_000_000), integers(min_value=1, max_value=100_000_000_000_000_000_000), integers(min_value=1, max_value=100_000_000_000_000_000_000), ) @settings(suppress_health_check=[HealthCheck.filter_too_much]) def test_fee_add_remove_invariant(flat_fee, prop_fee, imbalance_fee, amount, balance1, balance2): """First adding and then removing fees must yield the original value""" total_balance = TokenAmount(100_000_000_000_000_000_000) prop_fee_per_channel = ppm_fee_per_channel(ProportionalFeeAmount(prop_fee)) imbalance_fee = calculate_imbalance_fees( channel_capacity=total_balance, proportional_imbalance_fee=ProportionalFeeAmount(imbalance_fee), ) fee_schedule = FeeScheduleState( cap_fees=False, flat=FeeAmount(flat_fee), proportional=prop_fee_per_channel, imbalance_penalty=imbalance_fee, ) channel_in = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=total_balance - balance1), partner_state=NettingChannelEndStateProperties(balance=balance1), fee_schedule=fee_schedule, ) ) channel_out = factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=balance2), partner_state=NettingChannelEndStateProperties(balance=total_balance - balance2), fee_schedule=fee_schedule, ) ) amount_with_fees = get_amount_with_fees( amount_without_fees=amount, schedule_in=channel_in.fee_schedule, schedule_out=channel_out.fee_schedule, receivable_amount=balance1, balance_in=total_balance - balance1, balance_out=balance2, ) assume(amount_with_fees) assert amount_with_fees amount_without_fees = get_amount_without_fees( amount_with_fees=amount_with_fees, channel_in=channel_in, channel_out=channel_out ) assume(amount_without_fees) assert amount - 1 <= amount_without_fees <= amount + 1 def running_sum(a): total = 0 for item in a: total += item yield total def make_channel_pair( fee_schedule: FeeScheduleState, balance1: int = 0, balance2: int = 0 ) -> Tuple[NettingChannelState, NettingChannelState]: balance1 = TokenAmount(balance1) balance2 = TokenAmount(balance2) return ( factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=balance2), partner_state=NettingChannelEndStateProperties(balance=balance1), fee_schedule=fee_schedule, ) ), factories.create( NettingChannelStateProperties( our_state=NettingChannelEndStateProperties(balance=balance1), partner_state=NettingChannelEndStateProperties(balance=balance2), fee_schedule=fee_schedule, ) ), ) def test_mfee1(): """Unit test for the fee calculation in the mfee1_flat_fee scenario""" amount = 10_000 deposit = 100_000 flat_fee = 100 // 2 fee_schedule = FeeScheduleState(flat=FeeAmount(flat_fee)) channels = make_channel_pair(fee_schedule, deposit) # How much do we need to send so that the target receives `amount`? PFS-like calculation. fee_calculation = get_initial_amount_for_amount_after_fees( amount_after_fees=PaymentAmount(amount), channels=[channels, channels] ) assert fee_calculation amount_with_margin = calculate_safe_amount_with_fee( fee_calculation.amount_without_fees, FeeAmount(sum(fee_calculation.mediation_fees)) ) assert amount_with_margin == 10_211 # print values for scenario print(deposit - amount_with_margin, amount_with_margin) for med_fee in running_sum(fee_calculation.mediation_fees): print(deposit - amount_with_margin + med_fee, amount_with_margin - med_fee) def test_mfee2(): """Unit test for the fee calculation in the mfee2_proportional_fees scenario""" amount = 10_000 deposit = 100_000 prop_fee = ppm_fee_per_channel(ProportionalFeeAmount(10_000)) fee_schedule = FeeScheduleState(proportional=ProportionalFeeAmount(prop_fee)) channels = make_channel_pair(fee_schedule, deposit) # How much do we need to send so that the target receives `amount`? PFS-like calculation. fee_calculation = get_initial_amount_for_amount_after_fees( amount_after_fees=PaymentAmount(amount), channels=[channels, channels] ) assert fee_calculation amount_with_margin = calculate_safe_amount_with_fee( fee_calculation.amount_without_fees, FeeAmount(sum(fee_calculation.mediation_fees)) ) assert amount_with_margin == 10_213 # print values for scenario print(deposit - amount_with_margin, amount_with_margin) for med_fee in running_sum(fee_calculation.mediation_fees): print(deposit - amount_with_margin + med_fee, amount_with_margin - med_fee) def test_mfee3(): """Unit test for the fee calculation in the mfee3_only_imbalance_fees scenario""" amount = 500_000_000_000_000_000 deposit = TokenAmount(1_000_000_000_000_000_000) imbalance_penalty = calculate_imbalance_fees(deposit, ProportionalFeeAmount(10_000)) fee_schedule = FeeScheduleState(imbalance_penalty=imbalance_penalty, cap_fees=False) channels = make_channel_pair(fee_schedule, deposit) # How much do we need to send so that the target receives `amount`? PFS-like calculation. fee_calculation = get_initial_amount_for_amount_after_fees( amount_after_fees=PaymentAmount(amount), channels=[channels] ) assert fee_calculation amount_with_margin = calculate_safe_amount_with_fee( fee_calculation.amount_without_fees, FeeAmount(sum(fee_calculation.mediation_fees)) ) assert amount_with_margin == 480_850_038_799_922_400 # print values for scenario print("{:_} {:_}".format(deposit - amount_with_margin, amount_with_margin)) for med_fee in running_sum(fee_calculation.mediation_fees): print( "{:_} {:_}".format( deposit - amount_with_margin + med_fee, amount_with_margin - med_fee ) ) def test_mfee4(): """Unit test for the fee calculation in the mfee4_combined_fees scenario""" amount = PaymentAmount(500_000_000_000_000_000) deposit = 1_000_000_000_000_000_000 prop_fee = ppm_fee_per_channel(ProportionalFeeAmount(10_000)) imbalance_penalty = calculate_imbalance_fees( TokenAmount(deposit * 2), ProportionalFeeAmount(20_000) ) fee_schedule = FeeScheduleState( flat=FeeAmount(100 // 2), proportional=prop_fee, imbalance_penalty=imbalance_penalty, cap_fees=False, ) channels = make_channel_pair(fee_schedule, deposit, deposit) # How much do we need to send so that the target receives `amount`? PFS-like calculation. fee_calculation = get_initial_amount_for_amount_after_fees( amount_after_fees=PaymentAmount(amount), channels=[channels, channels] ) assert fee_calculation amount_with_margin = calculate_safe_amount_with_fee( amount, FeeAmount(sum(fee_calculation.mediation_fees)) ) # Calculate mediation fees for both mediators med_fees = [] incoming_amount = amount_with_margin for _ in range(2): outgoing_amount = get_amount_without_fees( amount_with_fees=incoming_amount, channel_in=channels[0], channel_out=channels[1] ) assert outgoing_amount med_fees.append(incoming_amount - outgoing_amount) incoming_amount = outgoing_amount assert amount_with_margin == 543_503_066_141_505_551 # print values for scenario print("{:_} {:_}".format(deposit - amount_with_margin, deposit + amount_with_margin)) for med_fee in running_sum(med_fees): print( "{:_} {:_}".format( deposit - amount_with_margin + med_fee, deposit + amount_with_margin - med_fee ) )
{ "repo_name": "raiden-network/raiden", "path": "raiden/tests/unit/transfer/mediated_transfer/test_mediation_fee.py", "copies": "1", "size": "25218", "license": "mit", "hash": 1918191036204514800, "line_mean": 38.2192846034, "line_max": 99, "alpha_frac": 0.6423982869, "autogenerated": false, "ratio": 3.387694787748522, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4530093074648522, "avg_score": null, "num_lines": null }
from fractions import Fraction from warnings import warn class Simplex(object): def __init__(self, num_vars, constraints, objective_function): """ num_vars: Number of variables equations: A list of strings representing constraints each variable should be start with x followed by a underscore and a number eg of constraints ['1x_1 + 2x_2 >= 4', '2x_3 + 3x_1 <= 5', 'x_3 + 3x_2 = 6'] Note that in x_num, num should not be more than num_vars. Also single spaces should be used in expressions. objective_function: should be a tuple with first element either 'min' or 'max', and second element be the equation eg ('min', '2x_1 + 4x_3 + 5x_2') For solution finding algorithm uses two-phase simplex method """ self.num_vars = num_vars self.constraints = constraints self.objective = objective_function[0] self.objective_function = objective_function[1] self.coeff_matrix, self.r_rows, self.num_s_vars, self.num_r_vars = self.construct_matrix_from_constraints() del self.constraints self.basic_vars = [0 for i in range(len(self.coeff_matrix))] self.phase1() r_index = self.num_r_vars + self.num_s_vars for i in self.basic_vars: if i > r_index: raise ValueError("Infeasible solution") self.delete_r_vars() if 'min' in self.objective.lower(): self.solution = self.objective_minimize() else: self.solution = self.objective_maximize() self.optimize_val = self.coeff_matrix[0][-1] def construct_matrix_from_constraints(self): num_s_vars = 0 # number of slack and surplus variables num_r_vars = 0 # number of additional variables to balance equality and less than equal to for expression in self.constraints: if '>=' in expression: num_s_vars += 1 elif '<=' in expression: num_s_vars += 1 num_r_vars += 1 elif '=' in expression: num_r_vars += 1 total_vars = self.num_vars + num_s_vars + num_r_vars coeff_matrix = [[Fraction("0/1") for i in range(total_vars+1)] for j in range(len(self.constraints)+1)] s_index = self.num_vars r_index = self.num_vars + num_s_vars r_rows = [] # stores the non -zero index of r for i in range(1, len(self.constraints)+1): constraint = self.constraints[i-1].split(' ') for j in range(len(constraint)): if '_' in constraint[j]: coeff, index = constraint[j].split('_') if constraint[j-1] is '-': coeff_matrix[i][int(index)-1] = Fraction("-" + coeff[:-1] + "/1") else: coeff_matrix[i][int(index)-1] = Fraction(coeff[:-1] + "/1") elif constraint[j] == '<=': coeff_matrix[i][s_index] = Fraction("1/1") # add surplus variable s_index += 1 elif constraint[j] == '>=': coeff_matrix[i][s_index] = Fraction("-1/1") # slack variable coeff_matrix[i][r_index] = Fraction("1/1") # r variable s_index += 1 r_index += 1 r_rows.append(i) elif constraint[j] == '=': coeff_matrix[i][r_index] = Fraction("1/1") # r variable r_index += 1 r_rows.append(i) coeff_matrix[i][-1] = Fraction(constraint[-1] + "/1") return coeff_matrix, r_rows, num_s_vars, num_r_vars def phase1(self): # Objective function here is minimize r1+ r2 + r3 + ... + rn r_index = self.num_vars + self.num_s_vars for i in range(r_index, len(self.coeff_matrix[0])-1): self.coeff_matrix[0][i] = Fraction("-1/1") coeff_0 = 0 for i in self.r_rows: self.coeff_matrix[0] = add_row(self.coeff_matrix[0], self.coeff_matrix[i]) self.basic_vars[i] = r_index r_index += 1 s_index = self.num_vars for i in range(1, len(self.basic_vars)): if self.basic_vars[i] == 0: self.basic_vars[i] = s_index s_index += 1 # Run the simplex iterations key_column = max_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] > 0 while condition is True: key_row = self.find_key_row(key_column = key_column) self.basic_vars[key_row] = key_column pivot = self.coeff_matrix[key_row][key_column] self.normalize_to_pivot(key_row, pivot) self.make_key_column_zero(key_column, key_row) key_column = max_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] > 0 def find_key_row(self, key_column): min_val = float("inf") min_i = 0 for i in range(1, len(self.coeff_matrix)): if self.coeff_matrix[i][key_column] > 0: val = self.coeff_matrix[i][-1] / self.coeff_matrix[i][key_column] if val < min_val: min_val = val min_i = i if min_val == float("inf"): raise ValueError("Unbounded solution") if min_val == 0: warn("Dengeneracy") return min_i def normalize_to_pivot(self, key_row, pivot): for i in range(len(self.coeff_matrix[0])): self.coeff_matrix[key_row][i] /= pivot def make_key_column_zero(self, key_column, key_row): num_columns = len(self.coeff_matrix[0]) for i in range(len(self.coeff_matrix)): if i != key_row: factor = self.coeff_matrix[i][key_column] for j in range(num_columns): self.coeff_matrix[i][j] -= self.coeff_matrix[key_row][j] * factor def delete_r_vars(self): for i in range(len(self.coeff_matrix)): non_r_length = self.num_vars + self.num_s_vars + 1 length = len(self.coeff_matrix[i]) while length != non_r_length: del self.coeff_matrix[i][non_r_length-1] length -= 1 def update_objective_function(self): objective_function_coeffs = self.objective_function.split() for i in range(len(objective_function_coeffs)): if '_' in objective_function_coeffs[i]: coeff, index = objective_function_coeffs[i].split('_') if objective_function_coeffs[i-1] is '-': self.coeff_matrix[0][int(index)-1] = Fraction(coeff[:-1] + "/1") else: self.coeff_matrix[0][int(index)-1] = Fraction("-" + coeff[:-1] + "/1") def check_alternate_solution(self): for i in range(len(self.coeff_matrix[0])): if self.coeff_matrix[0][i] and i not in self.basic_vars[1:]: warn("Alternate Solution exists") break def objective_minimize(self): self.update_objective_function() for row, column in enumerate(self.basic_vars[1:]): if self.coeff_matrix[0][column] != 0: self.coeff_matrix[0] = add_row(self.coeff_matrix[0], multiply_const_row(-self.coeff_matrix[0][column], self.coeff_matrix[row+1])) key_column = max_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] > 0 while condition is True: key_row = self.find_key_row(key_column = key_column) self.basic_vars[key_row] = key_column pivot = self.coeff_matrix[key_row][key_column] self.normalize_to_pivot(key_row, pivot) self.make_key_column_zero(key_column, key_row) key_column = max_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] > 0 solution = {} for i, var in enumerate(self.basic_vars[1:]): if var < self.num_vars: solution['x_'+str(var+1)] = self.coeff_matrix[i+1][-1] for i in range(0, self.num_vars): if i not in self.basic_vars[1:]: solution['x_'+str(i+1)] = Fraction("0/1") self.check_alternate_solution() return solution def objective_maximize(self): self.update_objective_function() for row, column in enumerate(self.basic_vars[1:]): if self.coeff_matrix[0][column] != 0: self.coeff_matrix[0] = add_row(self.coeff_matrix[0], multiply_const_row(-self.coeff_matrix[0][column], self.coeff_matrix[row+1])) key_column = min_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] < 0 while condition is True: key_row = self.find_key_row(key_column = key_column) self.basic_vars[key_row] = key_column pivot = self.coeff_matrix[key_row][key_column] self.normalize_to_pivot(key_row, pivot) self.make_key_column_zero(key_column, key_row) key_column = min_index(self.coeff_matrix[0]) condition = self.coeff_matrix[0][key_column] < 0 solution = {} for i, var in enumerate(self.basic_vars[1:]): if var < self.num_vars: solution['x_'+str(var+1)] = self.coeff_matrix[i+1][-1] for i in range(0, self.num_vars): if i not in self.basic_vars[1:]: solution['x_'+str(i+1)] = Fraction("0/1") self.check_alternate_solution() return solution def add_row(row1, row2): row_sum = [0 for i in range(len(row1))] for i in range(len(row1)): row_sum[i] = row1[i] + row2[i] return row_sum def max_index(row): max_i = 0 for i in range(0, len(row)-1): if row[i] > row[max_i]: max_i = i return max_i def multiply_const_row(const, row): mul_row = [] for i in row: mul_row.append(const*i) return mul_row def min_index(row): min_i = 0 for i in range(0, len(row)): if row[min_i] > row[i]: min_i = i return min_i
{ "repo_name": "khalibartan/simplex-method", "path": "simplex.py", "copies": "1", "size": "10290", "license": "mit", "hash": 724590232115722100, "line_mean": 36.5547445255, "line_max": 145, "alpha_frac": 0.5430515063, "autogenerated": false, "ratio": 3.576642335766423, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.959165492074812, "avg_score": 0.005607784263660684, "num_lines": 274 }
from fractions import Fraction import io import logging import os import random import string import time try: from picamera import PiCamera except ImportError: print 'Warning: PiCamera module not available' from PIL import Image import config logger = logging.getLogger(__name__) class Camera(object): ISO_LIST = [100, 200, 320, 400, 500, 640, 800] # List from PiCamera docs def __init__(self, storage_path=None): self.camera = self._get_camera() self.file_path = storage_path or config.NEW_TRIAL_DIR self.min_brightness = config.MIN_BRIGHTNESS self.max_brightness = config.MAX_BRIGHTNESS self.min_ss = config.MIN_SHUTTER_SPEED self.max_ss = config.MAX_SHUTTER_SPEED def __del__(self): self.camera.close() def _get_camera(self): c = PiCamera() c.hflip = c.vflip = True return c def _create_file_name(self): """Create a random, 8-letter file name with JPEG extension.""" base_name = ''.join(random.sample(string.ascii_letters, 8)) file_name = '{0}.jpg'.format(base_name) return file_name def _get_brightness(self, img): """Compute the average pixel intensity of the input image. img - a 3-channel (color) PIL Image Returns an int 0-255. """ img_grey = img.convert('L') num_pixels = img.size[0] * img_grey.size[1] h = img_grey.histogram() brightness = sum([i * h[i] for i in range(len(h))]) / num_pixels logger.info('Brightness: {0}'.format(brightness)) return brightness def _max_settings_reached(self): """Return True if ISO and shutter speed are at max values.""" diff = abs(self.max_ss - self.camera.exposure_speed) if (self.camera.iso >= max(self.ISO_LIST) and diff <= self.max_ss * 0.001): logger.info('Max settings reached') return True def _is_correct_brightness(self, img): """Return True if image intensity is within prescribed limits.""" self.current_brightness = self._get_brightness(img) if (self.current_brightness > self.min_brightness and self.current_brightness < self.max_brightness): logger.info('Brightness is within limits') return True if self._max_settings_reached(): return True logger.info('Brightness is not within limits') def _increase_ss(self): """Increase shutter speed by one step.""" ONE_SECOND = 1000000 current_ss = self.camera.exposure_speed new_ss = min(self.max_ss, current_ss + config.SHUTTER_SPEED_STEP) logger.info('New shutter speed: {0}'.format(new_ss)) self.camera.framerate = Fraction(ONE_SECOND, new_ss) self.camera.shutter_speed = new_ss def _increase_iso(self): """Increase ISO by one step.""" current_iso = self.camera.analog_gain * 100 for iso in self.ISO_LIST: if iso > current_iso: logger.info('New ISO: {0}'.format(iso)) self.camera.iso = iso return logger.info('New ISO: {0}'.format(max(self.ISO_LIST))) self.camera.iso = max(self.ISO_LIST) def _adjust_brightness(self): if self.current_brightness < self.min_brightness: if self.camera.exposure_mode not in ['night', 'off']: logger.info('Exposure mode: night') self.camera.exposure_mode = 'night' time.sleep(3) else: logger.info('Analog Gain: {0}'.format(self.camera.analog_gain)) logger.info('ISO: {0}'.format(self.camera.iso)) logger.info('SS/ES: {0} {1}'.format(self.camera.shutter_speed, self.camera.exposure_speed)) diff = abs(self.max_ss - self.camera.exposure_speed) if diff > self.max_ss * 0.001: self._increase_ss() else: self._increase_iso() sleep_duration = 1 / self.camera.framerate logger.info('Sleeping for {0} seconds'.format(int(sleep_duration))) time.sleep(sleep_duration) logger.info('Exposure mode: off') self.camera.exposure_mode = 'off' else: # TODO: gradient adjust brightness down pass def _shoot(self): """Capture an image with current camera settings. Returns a PIL Image. """ stream = io.BytesIO() logger.info('Shooting image') self.camera.capture(stream, format='jpeg') stream.seek(0) img = Image.open(stream) return img def _make_ready_image(self): """Capture an image of appropriate brightness. Returns a PIL Image. """ img = self._shoot() while not (self._is_correct_brightness(img) or self._max_settings_reached()): self._adjust_brightness() img = self._shoot() return img def _reset_camera(self): self.camera.exposure_mode = 'auto' self.camera.iso = 0 self.camera.shutter_speed = 0 def take_photo(self): """Capture and save a new image.""" img = self._make_ready_image() reduced_dimensions = tuple(dim / 2 for dim in img.size) img = img.resize(reduced_dimensions, Image.ANTIALIAS) file_name = self._create_file_name() img.save(os.path.join(self.file_path, file_name), quality=95) self._reset_camera() return file_name
{ "repo_name": "mattskone/garage_alarm", "path": "camera.py", "copies": "2", "size": "5699", "license": "mit", "hash": 5265074437494414000, "line_mean": 30.6611111111, "line_max": 83, "alpha_frac": 0.5739603439, "autogenerated": false, "ratio": 3.930344827586207, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00046643000346704045, "num_lines": 180 }
from fractions import Fraction import math import itertools def succ(x): """ takes an element of the Calkin Wilf tree and returns the next element following a breadth first traversal :param x: Fraction :return: Fraction """ x_int = Fraction(math.floor(x)) x_nonint = Fraction(x.numerator - x_int * x.denominator, x.denominator) return Fraction(1 / (x_int + 1 - x_nonint)) def entire_tree(): """ a generator for the entire Calkin Wilf tree :return: generator of Fraction """ x = Fraction(1, 1) yield x while True: x = succ(x) yield x def get_nth(n): """ returns the nth element of the tree following a breadth first traversal :param n: positive int :return: Fraction """ return get_slice(n, n + 1)[0] def get_slice(start, stop): """ return a finite sublist from the infinite generator :param start: positive int :param stop: positive int greater than start :return: tuple """ return tuple(itertools.islice(entire_tree(), start, stop)) def is_power_of_two(number): """ returns true if number is a power of 2 :param number: int :return: Bool """ return (number != 0) and (number & (number - 1) == 0) def new_level(number): """ returns true if number is the sum of all powers of 2 less than some arbitrary number ie following a breadth first traversal this node is the first of a new level :param number: int :return: Bool """ return (number != 0) and (number & (number + 1) == 0) def display_slice(start, stop): """ print a sublist of the tree :param start: positive int :param stop: positive int greater than start :return: string """ display = "" position = 1 for node in get_slice(start, stop): display += str(node) + ", " if new_level(position): display += "\n" position += 1 display += "\n" return display def get_position(node): """ given a rational number, find where it occurs in the tree :param node: Fraction :return: positive int """ position = 1 while node.denominator != 1: node = succ(node) position += 1 position = 2**node.numerator - position - 1 return position
{ "repo_name": "richardmillson/Calkin_Wilf_tree", "path": "tree.py", "copies": "1", "size": "2316", "license": "mit", "hash": 8124205700382237000, "line_mean": 22.3939393939, "line_max": 75, "alpha_frac": 0.6101036269, "autogenerated": false, "ratio": 3.815485996705107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9925589623605107, "avg_score": 0, "num_lines": 99 }
from fractions import Fraction import math """Allow distributions to omit events totalling this probability. This acts as a sanity check, to ensure that other optimisations you set, such as PROB_EVENT_TOLERANCE, or using floats instead of Fractions, don't result in wildly-inaccurate results. """ PROB_SPACE_TOLERANCE = 0 """Ignore events less likely than this probability when doing ProbDist.bind. This improves performance at the expense of accuracy, but the latter may be acceptable for your application. """ PROB_EVENT_TOLERANCE = 0 def add_module_opts(argparser): argparser.add_argument( "--prob-space-tolerance", help="Allow the sum of probabilities in a " "distributions to total anything between (1 - this) and 1. Default: %(default)s", default=0, type=float) argparser.add_argument( "--prob-event-tolerance", help="When applying transformations (i.e. " "using ProbDist.bind), drop events that are less likely than this. If " "you set this and get an AssertionError, you will also need to set " "--prob-space-tolerance. Default: %(default)s", default=0, type=float) old_parse = argparser.parse_args def parse_args(*args, **kwargs): global PROB_SPACE_TOLERANCE, PROB_EVENT_TOLERANCE args = old_parse(*args, **kwargs) PROB_SPACE_TOLERANCE = args.prob_space_tolerance PROB_EVENT_TOLERANCE = args.prob_event_tolerance return args argparser.parse_args = parse_args def probTotal(dist): return sum(v[1] for v in dist) def checkProb(dist): if not all(v[1] >= 0 for v in dist): raise ValueError() total = probTotal(dist) try: assert math.fabs(total - 1.0) <= PROB_SPACE_TOLERANCE except AssertionError, e: print math.fabs(total), dist raise class ProbDist(object): """Monad representing a probability distribution. Supports either fractions.Fraction or float as the probability. See the PROB_*_TOLERANCE variables for tweaks you can apply; in particular PROB_SPACE_TOLERANCE must be set when using floats. """ @classmethod def inject(cls, item): return cls([(item, Fraction(1))]) def __init__(self, dist): checkProb(dist) # merge duplicates in values d = {} for item, p in dist: d[item] = d.get(item, 0) + p self.dist = sorted(d.items()) def bind(self, f): """ @param f: f(item) -> ProbDist([(item, p)]) """ newdist = [] for item, p in self.dist: if p < PROB_EVENT_TOLERANCE: continue dist = f(item).dist checkProb(dist) newdist.extend([(v[0], p*v[1]) for v in dist]) return self.__class__(newdist) def map(self, f): """ @param f: f(item) -> item2 """ # short for self.bind(f compose self.__class__.inject) return self.__class__([(f(item), p) for item, p in self.dist]) def filter(self, f): """ @param f: f(item) -> bool """ return self.given(f)[1] def given(self, f): """ Condition this distribution on the given filter. @param f: f(item) -> bool @return (p, d) where p: proportion of this event space that matched d: child dist, or None if no events exist that matched the filter """ g = [(item, p) for item, p in self.dist if f(item)] t = probTotal(g) return t, self.__class__([(item, p/t) for item, p in g]) if g else None def expect(self, f=id): """ Calculate the expected value of this distribution """ return sum(f(item)*p for item, p in self.dist) def __str__(self): return "\n".join("%.8f %s" % (p, item) for item, p in self.dist) __f = lambda i: ProbDist([(i, 0.5), (i*2, 0.5)]) assert ProbDist.inject(1).bind(__f).bind(__f).bind(__f).dist == [(1, 0.125), (2, 0.375), (4, 0.375), (8, 0.125)]
{ "repo_name": "infinity0/bjsim", "path": "bj/prob.py", "copies": "1", "size": "3571", "license": "bsd-3-clause", "hash": -2492331912072677000, "line_mean": 28.5123966942, "line_max": 112, "alpha_frac": 0.6765611873, "autogenerated": false, "ratio": 2.9512396694214877, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41278008567214874, "avg_score": null, "num_lines": null }
from fractions import Fraction import numpy as np import config import GSM as gsm import struct from ctypes import * class item: def getLen(self): if hasattr(self,"field"): l = 0 for x in self.field: l += x.getLen() return l else: return self.__class__.length @staticmethod def gmsk_mapper( inp, start_point ): inpb = np.array(inp)*2 - 1 o = start_point out = [o] previous_symbol = inpb[0] for current_symbol in inpb[1:]: encoded_symbol = current_symbol * previous_symbol o = complex(0,1)*encoded_symbol*o out.append(o) previous_symbol = current_symbol return np.array(out) @staticmethod def c2bits(cbits): r = [] for x in cbits: r.append(int(x)) return r class TB(item): length = 3 bits = [0,0,0] class ATB(item): length = 8 bits = [0]*length class NGP(item): length = Fraction(33,4) class AGP(item): length = Fraction(273,4) class Burst: length = Fraction(625,4) small_overlap = 25 large_overlap = length mmap = None CHAN_IMP_RESP_LENGTH = 5 osr = config.SampleRate/gsm.SymbolRate fosr = float(osr) chn_len = int(CHAN_IMP_RESP_LENGTH*osr) chnMatchLength = int(chn_len+(CHAN_IMP_RESP_LENGTH+2)/2.*fosr) small_overlap_sample = int(small_overlap*osr) large_overlap_sample = int(large_overlap*osr) log = None def __init__(self): if hasattr(self.__class__,"__field__"): self.field = [ x() for x in self.__class__.__field__] else: self.field = [] self.fn = 0 self.sn = 0 self.ch = None def set(self,fn,sn): self.fn = fn self.sn = sn self.pos = Burst.length*(fn*8+sn) def getLen(self): if hasattr(self,"field"): l = 0 for x in self.field: l += x.getLen() return l else: return self.__class__.length def dump(self): name = [n.__name__ for n in self.__class__.__field__] print name def attach(self,CH): self.ch = CH def deattach(self): self.ch = None def channelEst( self, frame, training): t = np.conj(training) inx = np.floor(np.arange(len(training))*Burst.fosr) last = int(inx[-1]+1) out = np.zeros(len(frame)-last,dtype=complex) for k in range(len(out)): slc = frame[k:] s = slc[inx.astype(int)] r = np.dot(s,t) out[k] = r return out @staticmethod def short2Complex(data): nframes = len(data)/2 frame = np.array([complex(data[2*i],data[2*i+1]) for i in range(nframes)]) return frame def mapRfData(self): if mmap==None: raise NoInstall return s = int(self.pos-Burst.small_overlap) l = int(Burst.length+2*Burst.small_overlap) self.srecv = mmap(s,l) self.recv = Burst.short2Complex(self.srecv) def mapLData(self): if mmap==None: raise NoInstall return s = int(self.pos-Burst.large_overlap) l = int(Burst.length+2*Burst.large_overlap) return Burst.short2Complex(mmap(s,l)) def default_callback(self,fn,state): if Burst.log != None: self.toFile(Burst.log,fn) def toFile(self,f,fn): f.write(self.__class__.__name__) if mmap==None: raise NoInstall return s = int(self.pos-Burst.small_overlap) l = int(Burst.length+2*Burst.small_overlap) r = mmap(s,l) f.write(struct.pack('<hhhq',len(r)/2,self.sn,self.fn,fn)) f.write(string_at(addressof(r),len(r)*2))
{ "repo_name": "RP7/R7-OCM", "path": "src/host/python/gsmlib/Burst.py", "copies": "2", "size": "3192", "license": "apache-2.0", "hash": -7287733684203221000, "line_mean": 20.5675675676, "line_max": 76, "alpha_frac": 0.649122807, "autogenerated": false, "ratio": 2.5659163987138265, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42150392057138264, "avg_score": null, "num_lines": null }
from fractions import Fraction import pytest from typing import List, Tuple from .continued_fractions import convergent_sequence, \ continued_fraction_sqrt, \ convergents_sqrt CONVERGENTS = [ ( [0, 1, 5, 2, 2], [Fraction(0, 1), Fraction(1, 1), Fraction(5, 6), Fraction(11, 13), Fraction(27, 32)] ) ] CONTINUED_FRACTIONS_ROOTS = [ ( 2, ( [1], [2] ) ), ( 3, ( [1], [1, 2], ) ), ( 5, ( [2], [4], ) ), ( 6, ( [2], [2, 4], ) ), ( 7, ( [2], [1, 1, 1, 4], ) ), ( 8, ( [2], [1, 4], ) ), ( 10, ( [3], [6], ) ), ( 11, ( [3], [3, 6], ) ), ( 12, ( [3], [2, 6], ) ), ( 13, ( [3], [1, 1, 1, 1, 6], ) ), ] CONVERGENTS_SQRT = [ ( 2, [ Fraction(1, 1), Fraction(3, 2), Fraction(7, 5), Fraction(17, 12), Fraction(41, 29), Fraction(99, 70), Fraction(239, 169), Fraction(577, 408), Fraction(1393, 985), Fraction(3363, 2378) ] ), ] @pytest.mark.parametrize('a,convergent', CONVERGENTS) def test_convergents(a: List[int], convergent: List[Fraction]) -> None: generator = convergent_sequence(a) for computed, expected in zip(generator, convergent): assert computed == expected @pytest.mark.parametrize('n,expected_output', CONTINUED_FRACTIONS_ROOTS) def test_continued_fraction_sqrt(n: int, expected_output: Tuple[List[int], List[int]])\ -> None: assert continued_fraction_sqrt(n) == expected_output @pytest.mark.parametrize('n,convergent', CONVERGENTS_SQRT) def test_convergents_sqrt(n: int, convergent: List[Fraction])\ -> None: generator = convergents_sqrt(n) for computed, expected in zip(generator, convergent): assert computed == expected
{ "repo_name": "cryvate/project-euler", "path": "project_euler/library/number_theory/test_continued_fractions.py", "copies": "1", "size": "2486", "license": "mit", "hash": -9153207450810181000, "line_mean": 17.0144927536, "line_max": 79, "alpha_frac": 0.391391794, "autogenerated": false, "ratio": 3.7327327327327327, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46241245267327324, "avg_score": null, "num_lines": null }
from fractions import Fraction import re from jsonschema._utils import ( ensure_list, equal, extras_msg, find_additional_properties, types_msg, unbool, uniq, ) from jsonschema.exceptions import FormatError, ValidationError def patternProperties(validator, patternProperties, instance, schema): if not validator.is_type(instance, "object"): return for pattern, subschema in patternProperties.items(): for k, v in instance.items(): if re.search(pattern, k): for error in validator.descend( v, subschema, path=k, schema_path=pattern, ): yield error def propertyNames(validator, propertyNames, instance, schema): if not validator.is_type(instance, "object"): return for property in instance: for error in validator.descend( instance=property, schema=propertyNames, ): yield error def additionalProperties(validator, aP, instance, schema): if not validator.is_type(instance, "object"): return extras = set(find_additional_properties(instance, schema)) if validator.is_type(aP, "object"): for extra in extras: for error in validator.descend(instance[extra], aP, path=extra): yield error elif not aP and extras: if "patternProperties" in schema: patterns = sorted(schema["patternProperties"]) if len(extras) == 1: verb = "does" else: verb = "do" error = "%s %s not match any of the regexes: %s" % ( ", ".join(map(repr, sorted(extras))), verb, ", ".join(map(repr, patterns)), ) yield ValidationError(error) else: error = "Additional properties are not allowed (%s %s unexpected)" yield ValidationError(error % extras_msg(extras)) def items(validator, items, instance, schema): if not validator.is_type(instance, "array"): return if validator.is_type(items, "array"): for (index, item), subschema in zip(enumerate(instance), items): for error in validator.descend( item, subschema, path=index, schema_path=index, ): yield error else: for index, item in enumerate(instance): for error in validator.descend(item, items, path=index): yield error def additionalItems(validator, aI, instance, schema): if ( not validator.is_type(instance, "array") or validator.is_type(schema.get("items", {}), "object") ): return len_items = len(schema.get("items", [])) if validator.is_type(aI, "object"): for index, item in enumerate(instance[len_items:], start=len_items): for error in validator.descend(item, aI, path=index): yield error elif not aI and len(instance) > len(schema.get("items", [])): error = "Additional items are not allowed (%s %s unexpected)" yield ValidationError( error % extras_msg(instance[len(schema.get("items", [])):]) ) def const(validator, const, instance, schema): if not equal(instance, const): yield ValidationError("%r was expected" % (const,)) def contains(validator, contains, instance, schema): if not validator.is_type(instance, "array"): return if not any(validator.is_valid(element, contains) for element in instance): yield ValidationError( "None of %r are valid under the given schema" % (instance,) ) def exclusiveMinimum(validator, minimum, instance, schema): if not validator.is_type(instance, "number"): return if instance <= minimum: yield ValidationError( "%r is less than or equal to the minimum of %r" % ( instance, minimum, ), ) def exclusiveMaximum(validator, maximum, instance, schema): if not validator.is_type(instance, "number"): return if instance >= maximum: yield ValidationError( "%r is greater than or equal to the maximum of %r" % ( instance, maximum, ), ) def minimum(validator, minimum, instance, schema): if not validator.is_type(instance, "number"): return if instance < minimum: yield ValidationError( "%r is less than the minimum of %r" % (instance, minimum) ) def maximum(validator, maximum, instance, schema): if not validator.is_type(instance, "number"): return if instance > maximum: yield ValidationError( "%r is greater than the maximum of %r" % (instance, maximum) ) def multipleOf(validator, dB, instance, schema): if not validator.is_type(instance, "number"): return if isinstance(dB, float): quotient = instance / dB try: failed = int(quotient) != quotient except OverflowError: # When `instance` is large and `dB` is less than one, # quotient can overflow to infinity; and then casting to int # raises an error. # # In this case we fall back to Fraction logic, which is # exact and cannot overflow. The performance is also # acceptable: we try the fast all-float option first, and # we know that fraction(dB) can have at most a few hundred # digits in each part. The worst-case slowdown is therefore # for already-slow enormous integers or Decimals. failed = (Fraction(instance) / Fraction(dB)).denominator != 1 else: failed = instance % dB if failed: yield ValidationError("%r is not a multiple of %r" % (instance, dB)) def minItems(validator, mI, instance, schema): if validator.is_type(instance, "array") and len(instance) < mI: yield ValidationError("%r is too short" % (instance,)) def maxItems(validator, mI, instance, schema): if validator.is_type(instance, "array") and len(instance) > mI: yield ValidationError("%r is too long" % (instance,)) def uniqueItems(validator, uI, instance, schema): if ( uI and validator.is_type(instance, "array") and not uniq(instance) ): yield ValidationError("%r has non-unique elements" % (instance,)) def pattern(validator, patrn, instance, schema): if ( validator.is_type(instance, "string") and not re.search(patrn, instance) ): yield ValidationError("%r does not match %r" % (instance, patrn)) def format(validator, format, instance, schema): if validator.format_checker is not None: try: validator.format_checker.check(instance, format) except FormatError as error: yield ValidationError(error.message, cause=error.cause) def minLength(validator, mL, instance, schema): if validator.is_type(instance, "string") and len(instance) < mL: yield ValidationError("%r is too short" % (instance,)) def maxLength(validator, mL, instance, schema): if validator.is_type(instance, "string") and len(instance) > mL: yield ValidationError("%r is too long" % (instance,)) def dependencies(validator, dependencies, instance, schema): if not validator.is_type(instance, "object"): return for property, dependency in dependencies.items(): if property not in instance: continue if validator.is_type(dependency, "array"): for each in dependency: if each not in instance: message = "%r is a dependency of %r" yield ValidationError(message % (each, property)) else: for error in validator.descend( instance, dependency, schema_path=property, ): yield error def enum(validator, enums, instance, schema): if instance == 0 or instance == 1: unbooled = unbool(instance) if all(unbooled != unbool(each) for each in enums): yield ValidationError("%r is not one of %r" % (instance, enums)) elif instance not in enums: yield ValidationError("%r is not one of %r" % (instance, enums)) def ref(validator, ref, instance, schema): resolve = getattr(validator.resolver, "resolve", None) if resolve is None: with validator.resolver.resolving(ref) as resolved: for error in validator.descend(instance, resolved): yield error else: scope, resolved = validator.resolver.resolve(ref) validator.resolver.push_scope(scope) try: for error in validator.descend(instance, resolved): yield error finally: validator.resolver.pop_scope() def type(validator, types, instance, schema): types = ensure_list(types) if not any(validator.is_type(instance, type) for type in types): yield ValidationError(types_msg(instance, types)) def properties(validator, properties, instance, schema): if not validator.is_type(instance, "object"): return for property, subschema in properties.items(): if property in instance: for error in validator.descend( instance[property], subschema, path=property, schema_path=property, ): yield error def required(validator, required, instance, schema): if not validator.is_type(instance, "object"): return for property in required: if property not in instance: yield ValidationError("%r is a required property" % property) def minProperties(validator, mP, instance, schema): if validator.is_type(instance, "object") and len(instance) < mP: yield ValidationError( "%r does not have enough properties" % (instance,) ) def maxProperties(validator, mP, instance, schema): if not validator.is_type(instance, "object"): return if validator.is_type(instance, "object") and len(instance) > mP: yield ValidationError("%r has too many properties" % (instance,)) def allOf(validator, allOf, instance, schema): for index, subschema in enumerate(allOf): for error in validator.descend(instance, subschema, schema_path=index): yield error def anyOf(validator, anyOf, instance, schema): all_errors = [] for index, subschema in enumerate(anyOf): errs = list(validator.descend(instance, subschema, schema_path=index)) if not errs: break all_errors.extend(errs) else: yield ValidationError( "%r is not valid under any of the given schemas" % (instance,), context=all_errors, ) def oneOf(validator, oneOf, instance, schema): subschemas = enumerate(oneOf) all_errors = [] for index, subschema in subschemas: errs = list(validator.descend(instance, subschema, schema_path=index)) if not errs: first_valid = subschema break all_errors.extend(errs) else: yield ValidationError( "%r is not valid under any of the given schemas" % (instance,), context=all_errors, ) more_valid = [s for i, s in subschemas if validator.is_valid(instance, s)] if more_valid: more_valid.append(first_valid) reprs = ", ".join(repr(schema) for schema in more_valid) yield ValidationError( "%r is valid under each of %s" % (instance, reprs) ) def not_(validator, not_schema, instance, schema): if validator.is_valid(instance, not_schema): yield ValidationError( "%r is not allowed for %r" % (not_schema, instance) ) def if_(validator, if_schema, instance, schema): if validator.is_valid(instance, if_schema): if u"then" in schema: then = schema[u"then"] for error in validator.descend(instance, then, schema_path="then"): yield error elif u"else" in schema: else_ = schema[u"else"] for error in validator.descend(instance, else_, schema_path="else"): yield error
{ "repo_name": "Julian/jsonschema", "path": "jsonschema/_validators.py", "copies": "1", "size": "12397", "license": "mit", "hash": 7216111643228076000, "line_mean": 31.1165803109, "line_max": 79, "alpha_frac": 0.6055497298, "autogenerated": false, "ratio": 4.282210708117444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5387760437917444, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys,math # compare two tessellations of a circular disk # trascendental vs rational coordinates # (aka cos/sin vs integer/integer) # roughly equal density and number of points # which is more compressible in data size? ##### ## result # # when using standard python ASCII output for floats: rationals can be # 1/2 smaller at first. however when numbers grow... then the constant # width python ASCII roundoff of floats comes into play and filesizes # become roughly equal. for example compare a run with ringcount set to # 40 vs ringcount set to 220. for example '2003/23403' is about the same # as '0.03030303' # interestingly, running compression, like 'zip' or 'xz', on the .txt # files shows the ASCII transcendental to be more 'compressible' than # ascii rationals? # in binary, not ASCII: well, rationals are often going to use more # space than 32 bit floats. # First off note that each rational is a ratio of two ints, which means # each x,y coordinate is 'double' the space of the int size. in other words, # 132/403, 4903/2903 is four ints. If the ints being used are 32 bits, that is # a total of 4*32 or 128 bits for integers. you have to double stuff. # now in a lot of cases, say you use 24 bits for integers to store # binary rationals. that means each x is 48 bits and each y is 48 bits. # more than 32. # but note that in some cases rationals will be smaller than 64 bit floats. # for example, if you use 24 bit ints, you have 48 bytes for x, 48 for y, # smaller than 64 for x and 64 for y. # also if you assume there is a mythical utf8-style storage format for # rationals, that allows variable-width numbers (1 byte, 2 bytes, etc) # rationals size can become even smaller. consider 34/230 for example. # that is an 8 bit number divided by a 8 bit number. x could be 16 bits, # and so could y. in this example, this mythical format often produces # byte size smaller than 64 bit floats or fixed-width int rationals. # in conclusion its all quite dependent on the situation. # there is no automatic guarantee of space saving by using rationals.... # on the flip side, there is no automatic space saving by using floats # either. it depends. will your output be ASCII? how much rounding? # does your program have time to use some funky compression? or not? ringcount=90 # how many 'rings' will the circles tessellation have? filenametr='comprtest.transcdntl.txt' filenamerat='comprtest.ratl.txt' # part 1: rational coordinates (integer/integer) # note - blue, red, and green quadrance are from Norman Wildberger's # Chromogeometry def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] xs2,ys2=[],[] layers=[[]] for j in range(0,ringcount): layer=layers[j] layers+=[[]] for i in range(2*j): num = i denom = 2*j layers[j] += [Fraction(num,denom)] layers[j+1]+=[Fraction(1,1)] #for i in layers: # print i,'\n' for layer in layers: for t in layer: if blueq(0,0,1,t)==0: continue x = len(layer)*Fraction(redq(0,0,1,t),blueq(0,0,1,t)) y = len(layer)*Fraction(greenq(0,0,1,t),blueq(0,0,1,t)) xs += [x] ys += [y] xs += [-x] ys += [y] xs += [-x] ys += [-y] xs += [x] ys += [-y] maxv=max(xs+ys) for i in range(0,len(xs)): xs[i] = Fraction(xs[i], maxv ) ys[i] = Fraction(ys[i], maxv ) outs='' for p in range(len(xs)): # print xs[p],ys[p] outs+=str(xs[p])+','+str(ys[p])+'\n' print ' rational coords:',len(xs),'points. output .txt bytes:',len(outs) f=open(filenamerat,'w') f.write(outs) f.close() # transcendental (cos/sin) layers=[] layers=[[]] txs=[] tys=[] for nn in range(1,ringcount): # layers[0:4]: angle = 0 for t in range(0,4*nn+1): #angle += 360/len(layer) angle = (float(t)/float(4*nn))*(math.pi) x = nn*math.cos(angle) y = nn*math.sin(angle) # print t,nn,float(t)/float(nn),angle,angle/math.pi,x,y txs+=[x] tys+=[y] txs+=[x] tys+=[-y] maxv=max(txs+tys) for i in range(0,len(txs)): txs[i] = txs[i] / maxv tys[i] = tys[i] / maxv outs='' for p in range(len(txs)): outs+=str(txs[p])+','+str(tys[p])+'\n' print 'transcendental coords:',len(txs),'points. output .txt bytes:',len(outs) f=open(filenametr,'w') f.write(outs) f.close() print 'files written',filenamerat, filenametr # calc binary size # Rational - assume some format like UTF8 where size is related to data stored # with 3 bits per number being used up as 'control bits' (8-3, 16-3, 32-3, ...) bytecount=0 biggest=0 biggestval=0 for p in xs+ys: for dig in p.numerator,p.denominator: if biggestval<dig: biggestval=dig if dig>2**77: print 'overflow > 2**(77)' elif dig>2**61: if biggest<72: biggest=72 bytecount+=9 elif dig>2**53: if biggest<64: biggest=64 bytecount+=8 elif dig>2**45: if biggest<56: biggest=56 bytecount+=7 elif dig>2**37: if biggest<48: biggest=48 bytecount+=6 elif dig>2**29: if biggest<40: biggest=40 bytecount+=5 elif dig>2**21: if biggest<32: biggest=32 bytecount+=4 elif dig>2**12: if biggest<24: biggest=24 bytecount+=3 elif dig>2**5: if biggest<16: biggest=16 bytecount+=2 elif dig<2**5: bytecount+=1 if biggest<8: biggest=8 floatcount32 = (len(txs)+len(tys))*4 # assume 32bit float x, 32 bit float y floatcount64 = (len(txs)+len(tys))*8 # assume 64bit float x, 64bit float y biggestcount = (len(xs)+len(ys))*(biggest/8)*2 # assume constant width of bytes print 'bytecounts: ratl, transdtl 32bit, transdtl 64bit:', biggestcount, floatcount32,floatcount64 print 'biggest rational numerator or denominator:', biggestval, ',', biggest, 'bits' print 'mythical utf-8ish ratl:', bytecount, 'bytes'
{ "repo_name": "donbright/piliko", "path": "experiment/compression.py", "copies": "1", "size": "5748", "license": "bsd-3-clause", "hash": 4433263777076189700, "line_mean": 28.6288659794, "line_max": 98, "alpha_frac": 0.6838900487, "autogenerated": false, "ratio": 2.7293447293447293, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8652120782139059, "avg_score": 0.052222799181134205, "num_lines": 194 }
from fractions import Fraction import sys # depth-blueq. # alter depth, it wil change the number of 'dots' in the center of the shape def sqr(x): return x*x def greenq_pts(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq_pts(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq_pts(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) def greenq(m,n): return greenq_pts(0,0,m,n) def redq(m,n): return redq_pts(0,0,m,n) def blueq(m,n): return blueq_pts(0,0,m,n) xs,ys=[],[] depth = 20 for m in range(-depth,depth): for n in range(-depth,depth): if depth-blueq(m,n)==0: continue if blueq(m,n)==0: continue x = Fraction(redq(m,n),depth-blueq(m,n)) y = Fraction(greenq(m,n),depth-blueq(m,n)) xs += [x] ys += [y] max=max(xs+ys) i=0 print xs[i]*xs[i]+ys[i]*ys[i] for i in range(0,len(xs)): xs[i] = Fraction( xs[i], max ) ys[i] = Fraction( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/miscpatterns/pattern_alien.py", "copies": "1", "size": "1105", "license": "bsd-3-clause", "hash": 4786485728442121000, "line_mean": 23.0217391304, "line_max": 76, "alpha_frac": 0.636199095, "autogenerated": false, "ratio": 2.0500927643784785, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7884298723765252, "avg_score": 0.0603986271226454, "num_lines": 46 }
from fractions import Fraction import sys layer = [Fraction(0,1),Fraction(1,1)] newlayer = [] depth=4 for i in range(1,depth): for i in range(len(layer)-1): new_numer = layer[i].numerator+layer[i+1].numerator new_denom = layer[i].denominator+layer[i+1].denominator new_number = Fraction( new_numer, new_denom ) newlayer += [layer[i], new_number] newlayer += [1] print newlayer layer=newlayer newlayer=[] xs,ys,zs=[],[],[] for m in layer: for n in layer: for m1 in layer: for n1 in layer: if n+m==0: continue if n1+m1==0: continue l = Fraction( m*m-n*n , m*m+n*n ) z = Fraction( 2*m*n , m*m+n*n ) x = l * Fraction( m1*m1-n1*n1, m1*m1+n1*n1 ) y = l * Fraction( 2*m1*n1 , m1*m1+n1*n1 ) print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [y] xs += [y] ys += [x] zs += [z] zs += [-1*z] print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythsphere2.py", "copies": "1", "size": "1109", "license": "bsd-3-clause", "hash": -9076185396909536000, "line_mean": 21.18, "line_max": 57, "alpha_frac": 0.5879170424, "autogenerated": false, "ratio": 2.187376725838264, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.32752937682382643, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys # rational approximation of a unit circle using farey sequence and a # Chromogeometry - ish paramterization of unit pts on circle. requires # numpy, matplotlib # also this version limits blue quadrance between points... so you get a # sort of rational approximation of a 'regularly divided' circle as # formed by a geographer's latitude lines # but its not actually 'symmetrical' the way a regular polygon would be # there are small discrepancies between the side lengths if you were to # measure them closely def sqr(x): return x*x def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) layer = [Fraction(0,1),Fraction(1,1)] newlayer = [] depth=14 for i in range(1,depth): for i in range(len(layer)-1): new_numer = layer[i].numerator+layer[i+1].numerator new_denom = layer[i].denominator+layer[i+1].denominator new_number = Fraction( new_numer, new_denom ) newlayer += [layer[i], new_number] newlayer += [1] print newlayer[0:2],'...(',len(newlayer),')...',newlayer[-1] layer=newlayer newlayer=[] blueqlimit = Fraction(1,64) print 'blue q limit',blueqlimit xs,ys=[],[] for i in range(0,len(layer)): newnumerator = layer[i].numerator newdenominator = layer[i].denominator n = newnumerator m = newdenominator x = Fraction( m*m-n*n , m*m+n*n ) y = Fraction( 2*m*n , m*m+n*n ) ptOK=True for j in range(len(xs)): if blueq(x,y,xs[j],ys[j])<blueqlimit: ptOK=False if ptOK: print x,y,layer[i] xs += [x] ys += [y] xs += [-x] ys += [y] xs += [-x] ys += [-y] xs += [x] ys += [-y] print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythcirc2.py", "copies": "1", "size": "1825", "license": "bsd-3-clause", "hash": 5449986788195171000, "line_mean": 24.3472222222, "line_max": 73, "alpha_frac": 0.6690410959, "autogenerated": false, "ratio": 2.6034236804564905, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8507710426615565, "avg_score": 0.05295086994818524, "num_lines": 72 }
from fractions import Fraction import sys # rational approximation of a unit circle using # Chromogeometry - ish paramterization of unit pts on circle. requires # numpy, matplotlib # uses 'flat' list of input fractions. not farey sequence as in other # experiments # also this version limits blue quadrance between points... so you get a # sort of rational approximation of a 'regularly divided' circle as # formed by a geographer's latitude lines ( hopefully ) def sqr(x): return x*x def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) layer=[] n=1064 for i in range(0,n+1): layer+=[Fraction(i,n)] print layer[0:2],'...(',len(layer),')...',layer[-1] blueqlimit = Fraction(1,64) xs,ys=[0],[1] print 'blue q limit',blueqlimit for i in range(0,len(layer)): newnumerator = layer[i].numerator newdenominator = layer[i].denominator n = newnumerator m = newdenominator x = Fraction( m*m-n*n , m*m+n*n ) y = Fraction( 2*m*n , m*m+n*n ) ptOK=True for j in range(len(xs)): if blueq(x,y,xs[j],ys[j])<blueqlimit: ptOK=False if blueq(-x,y,x,y)<blueqlimit: ptOK=False if ptOK: print x,y,layer[i] xs += [x] ys += [y] xs += [-x] ys += [y] print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythcirc3.py", "copies": "1", "size": "1423", "license": "bsd-3-clause", "hash": 3141934924668593000, "line_mean": 23.5344827586, "line_max": 73, "alpha_frac": 0.6676036543, "autogenerated": false, "ratio": 2.4790940766550524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.36466977309550525, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys # rational approximation of unit circle... with 'warping' # introduced by playing around with inputs to the quadrance functions # for example, instead of 0,0,m,n use '-n,0,m,n' def sqr(x): return x*x def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) xs,ys=[],[] depth = 15 for m in range(-depth,depth): for n in range(-depth,depth): if blueq(0,0,m,n)==0: continue if blueq(m,0,m,n)==0: continue if blueq(0,n,m,n)==0: continue x = Fraction(redq(0,0,m,n),blueq(0,n,m,n)) y = Fraction(greenq(0,0,m,n),blueq(0,0,m,n)) xs += [x] ys += [y] max=max(xs+ys) for i in range(0,len(xs)): xs[i] = Fraction( xs[i], max ) ys[i] = Fraction( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/warppng/pythwarp4.py", "copies": "1", "size": "1056", "license": "bsd-3-clause", "hash": 2065447238614279400, "line_mean": 24.1428571429, "line_max": 69, "alpha_frac": 0.6373106061, "autogenerated": false, "ratio": 2.1204819277108435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3257792533810844, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys # rational paramterization / approximation of bernoulli's lemniscate # traditional form: ( x^2 + y^2 ) ^2 = 2*a*( x^2 - y^2 ) # (note - this uses terms from Norman Wildberger's rational # trigonometry/chromogeometry. briefly for a vector from 0,0 to x,y: # # blue quadrance (x,y) = x^2 + y^2 # red quadrance (x,y) = x^2 - y^2 # green quadrance (x,y) = 2*x*y # ) # theory: # # to summarize: we have a rational paramterization of the hypebrola, x,y # as x = blueq/redq and y = greenq/redq , with quadrances to rational # point m,n. now, Bernoulli's lemniscate is an inverse of the hyperbola # through the origin, so just find rational x,y for hyperbola, then do # # lamda = constant = 1/blueq(x,y) # x_lemniscate = x_hyperbola*lambda # y_lemniscate = y_hyperbola*lambda # # in more detail:::: # # first, we have a rational paramterization of the hyperbola. # for this, see the 'pythhyp' series of .py files. # # basically, we just use the rational paramterization of a circle: # # x,y = redq/blueq, greenq/blueq for rational points m,n # # written in ordinary algebra: # # x,y = m^2-n^2 / m^2+n^2 , 2mn / m^2+n^2 # # Now we modify it a bit as though the hyperbola is a 'red circle' from # Norman Wildberger's Chromogeometry # # x = blueq/redq, y = greenq/redq for rational points m,n # # written with ordinary algebra: # # x = (m^2 + n^2) / (m^2 - n^2 ) y = 2mn / (m^2 - n^2) # # where m,n are rationals (usually, integers,,, but you can use any rational) # # So there is your rational paramterization of the hyperbola # # Next, following Wildberger's youtube lecture on the Bernoulli # Lemniscate, we note that the lemniscate curve is the inverse of the # hyperbola through the origin... meaning that you can draw a line from # the origin that intersects both the hyperbola and the lemniscate... # and there is a special relationaship between those intersection points. # Their distances from origin, when multiplied, produce a constant! Wow, cool! # Now since we are following Dr Wildberger here, lets just use Blue Quadrance # instead of distance, and save ourselves the trouble of square roots. # So lets square our constant too. # How does this help us? imagine we draw a line from the origin, and # call the hyperbola intersection x,y and the lemniscate intersection # x2,y2. we can imagine two similar right triangles: # # points [0,0] [x,0] [x,y] -> for hyperbola # points [0,0] [x2,0] [x2,y2] -> for lemniscate # # Call the hypoteneuse for the hyperbola point by the name 'oh', and for the # leminscate point use the name 'ol'. Call the blue quadrances of the # hypotenueuses as OH and OL. # # Now, these triangles are similar... so we can use this fact. If we # know x and y, we can find x2,y2 using the proportionality between the # similar triangles. # So since the triangles are similar, OL = some-constant^2 * OH. Lets call # this constant lambda. # # so we have some facts about OL and OH now, so how does it fit together? # # OH * OL = k^2 <- from the fact of inversion # OL = OH * lambda^2 <- from the fact of similar triangles being proportional # # solve for lambda... # lambda^2=OL/OH, OL <= k^2/OH # lambda^2=(k^2/OH)/OH # lambda^2 = k^2/OH^2 # lambda = k/OH # now our goal is to find x2,y2 using the proportionality of 2 similar # triangles. now we found our proportionality, lambda, so we can find x2,y2. # # x2 = x * lambda # y2 = y * lambda # # Now, note that x2 and y2 are both rational, as long as x,y are # rational and lambda is rational. # # But wait, we know how to generate rational x,y... they are rational # points on the hyperbola, and we have a rational paramterization for # that! And obviously lambda will be rational b/c its the result of # rational math # # Thus, we have a rational paramterization for Bernoulli's Lemniscate. # # for a bunch of integers or rationals m,n: # # x = blueq(m,n)/redq(m,n) <-- rational hyperbola # y = greenq(m,n)/redq(m,n) # lambda = k/blueq(x,y) # x2 = x * lambda <-- rational lemniscate # y2 = y * lambda #### wait, couldn't you just use a simple version of the hyperbola? #### x = sequence of rationals #### y = 1/x #### #### yes. but i like the aesthetics of chromogeometry #### def sqr(x): return x*x def greenq_pts(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq_pts(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq_pts(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) def greenq(m,n): return greenq_pts(0,0,m,n) def redq(m,n): return redq_pts(0,0,m,n) def blueq(m,n): return blueq_pts(0,0,m,n) xs,ys=[],[] depth = 13 for m in range(-depth,depth): for n in range(-depth,depth): if redq(m,n)==0: continue x = Fraction(blueq(m,n),redq(m,n)) y = Fraction(greenq(m,n),redq(m,n)) oh = blueq(x,y) lambd = Fraction( 1, oh ) x = x * lambd y = y * lambd xs += [x] ys += [y] max=max(xs+ys) for i in range(0,2): print xs[i],',',ys[i], print '....' for i in range(0,len(xs)): xs[i] = Fraction( xs[i], max ) ys[i] = Fraction( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/bernoulli/pythbernlem.py", "copies": "1", "size": "5304", "license": "bsd-3-clause", "hash": -3807664013547784000, "line_mean": 30.3846153846, "line_max": 79, "alpha_frac": 0.6742081448, "autogenerated": false, "ratio": 2.638805970149254, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.869286855617692, "avg_score": 0.024029111754466637, "num_lines": 169 }
from fractions import Fraction import sys # this is a demonstration of the 'fox head' algorithm for finding # the 'side' of a line that a point is on. # consider two points, p1, and p2. then imagine a line between p1, p2 # lets call it l. the foxhead of p1, p2, p3 will tell you which 'side' # of the line l that p3 is on. or, if p3 is on the line, foxhead will # tell you that as well. # it uses the name 'fox head' because if you draw out the three # parallellograms formed by the three pairs of vectors, in a simple case # like (3,4) (4,3) (5,5), it kind of looks like a fox's head with two # big pointy ears. def wedge( p1, p2 ): x1,y1,x2,y2=p1[0],p1[1],p2[0],p2[1] return x1*y2-x2*y1 def foxhead(p1,p2,p3): w1 = wedge( p1, p2 ) w2 = wedge( p1, p3 ) w3 = wedge( p3, p2 ) print '1,2,3',w1,w2,w3 if w3+w2 > w1: return 1 elif w3+w2 < w1: return -1 elif w3+w2==w1: return 0 xs,ys=[],[] xs2,ys2=[],[] xs3,ys3=[],[] depth = 20 p1 = [-5,-5] p2 = [-13,-15] xs2 += [p1[0]] ys2 += [p1[1]] xs2 += [p2[0]] ys2 += [p2[1]] for m in range(-depth,depth): for n in range(-depth,depth): p3 = [m,n] if foxhead( p1, p2, p3 )<0: xs += [m] ys += [n] if foxhead( p1, p2, p3 )==0: xs2 += [m] ys2 += [n] if foxhead( p1, p2, p3 )>0: xs3 += [m] ys3 += [n] print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-depth,depth]) ax.set_xlim([-depth,depth]) ax.scatter(xs,ys,c="red") ax.scatter(xs2,ys2,c="yellow") ax.scatter(xs3,ys3,c="blue") plt.show() print ax.scatter.__doc__
{ "repo_name": "donbright/piliko", "path": "experiment/foxhead.py", "copies": "1", "size": "1570", "license": "bsd-3-clause", "hash": 7069769607742223000, "line_mean": 23.53125, "line_max": 73, "alpha_frac": 0.6210191083, "autogenerated": false, "ratio": 2.1805555555555554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.33015746638555554, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys # very simple rational paramterization / approximation of blue circle # (x^2+y^2=1) useful as base for building other ideas def sqr(x): return x*x def greenq_pts(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq_pts(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq_pts(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) def greenq(m,n): return greenq_pts(0,0,m,n) def redq(m,n): return redq_pts(0,0,m,n) def blueq(m,n): return blueq_pts(0,0,m,n) xs,ys=[],[] depth = 10 for m in range(-depth,depth): for n in range(-depth,depth): if blueq(m,n)==0: continue x = Fraction(redq(m,n),blueq(m,n)) y = Fraction(greenq(m,n),blueq(m,n)) xs += [x] ys += [y] maxval=max(xs+ys) i=0 print xs[i]*xs[i]+ys[i]*ys[i] for i in range(0,len(xs)): xs[i] = Fraction( xs[i], maxval ) ys[i] = Fraction( ys[i], maxval ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_xlim(-1.2,1.2) ax.set_ylim(-1.2,1.2) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythcircsimple.py", "copies": "1", "size": "1094", "license": "bsd-3-clause", "hash": 4415822418530542000, "line_mean": 23.8636363636, "line_max": 69, "alpha_frac": 0.647166362, "autogenerated": false, "ratio": 2.083809523809524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3230975885809524, "avg_score": null, "num_lines": null }
from fractions import Fraction import sys # very simple rational paramterization / approximation of red hyperbola # (x^2-y^2=1) useful as base for building other ideas def sqr(x): return x*x def greenq_pts(x,y,x2,y2): return 2*(x2-x)*(y2-y) def redq_pts(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y) def blueq_pts(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y) def greenq(m,n): return greenq_pts(0,0,m,n) def redq(m,n): return redq_pts(0,0,m,n) def blueq(m,n): return blueq_pts(0,0,m,n) xs,ys=[],[] depth = 5 for m in range(-depth,depth): for n in range(-depth,depth): if redq(m,n)==0: continue x = Fraction(blueq(m,n),redq(m,n)) y = Fraction(greenq(m,n),redq(m,n)) xs += [x] ys += [y] max=max(xs+ys) i=0 print xs[i]*xs[i]+ys[i]*ys[i] for i in range(0,len(xs)): xs[i] = Fraction( xs[i], max ) ys[i] = Fraction( ys[i], max ) print len(xs), 'points' import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]#+zs[i]/4 ys[i]=ys[i]#+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythhypsimple.py", "copies": "1", "size": "1089", "license": "bsd-3-clause", "hash": -3927679404987441000, "line_mean": 23.75, "line_max": 72, "alpha_frac": 0.6409550046, "autogenerated": false, "ratio": 2.0625, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.32034550046, "avg_score": null, "num_lines": null }
from fractions import Fraction import time def gen_random(): s = 290797 while True: s = (s * s) % 50515093 t = s % 500 yield int(t) # https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection def calc_intersect(line1, line2): x1, y1, x2, y2 = line1 x3, y3, x4, y4 = line2 D = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if D == 0: return False s = (y4 - y3) * (x3 - x1) - (x4 - x3) * (y3 - y1) t = (y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1) if D > 0: if 0 < s and s < D and 0 < t and t < D: s = Fraction(s, D) else: return False else: if 0 < -s and -s < -D and 0 < -t and -t < -D: s = Fraction(s, D) else: return False return (x1 + s * (x2 - x1), y1 + s * (y2 - y1)) if __name__ == "__main__": t0 = time.clock() N = 5000 lines = [] g = gen_random() for k in range(N): x1, y1 = g.next(), g.next() x2, y2 = g.next(), g.next() l = (x1, y1, x2, y2) lines.append(l) intersections = set() for i in xrange(N): if i % 100 == 0: print i for j in xrange(i + 1, N): pt = calc_intersect(lines[i], lines[j]) if pt: intersections.add((pt[0].numerator, pt[0].denominator, pt[1].numerator, pt[1].denominator)) ans = len(intersections) print ans t1 = time.clock() print t1 - t0
{ "repo_name": "zeyuanxy/project-euler", "path": "vol4/165.py", "copies": "2", "size": "1483", "license": "mit", "hash": 3291102074586256400, "line_mean": 23.7166666667, "line_max": 107, "alpha_frac": 0.4585300067, "autogenerated": false, "ratio": 2.736162361623616, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4194692368323616, "avg_score": null, "num_lines": null }
from fractions import Fraction def _e_partial_value_at_idx(idx): return 2 if idx == 0 else 2 * (idx // 3 + 1) if idx % 3 == 2 else 1 class EPartialValueIterator: def __init__(self, start=0, stop=None, step=1): self._index = start or 0 self._stop = stop self._step = step or 1 def _should_stop(self): if self._step < 0: if self._index < 0: return True if self._stop is not None: return self._index <= self._stop elif self._stop is not None: return self._index >= self._stop def __iter__(self): while not self._should_stop(): yield _e_partial_value_at_idx(self._index) self._index += self._step class MetaEPartialValues(type): def __iter__(self): yield from EPartialValueIterator() def __getitem__(self, val): if type(val) == int: return _e_partial_value_at_idx(val) return EPartialValueIterator(val.start, val.stop, val.step) class EPartialValues(metaclass=MetaEPartialValues): pass # Get the sum of the digits in the 100th convergent of e (100 terms of # continued fraction) def solve(): answer = Fraction(EPartialValues[99]) for pv in EPartialValues[98::-1]: answer = pv + (1 / answer) return sum(map(int, str(answer.numerator))) if __name__ == '__main__': print('The answer is {}'.format(solve()))
{ "repo_name": "WalrusCow/euler", "path": "Solutions/problem65.py", "copies": "1", "size": "1445", "license": "mit", "hash": -5888098057353828000, "line_mean": 25.2727272727, "line_max": 71, "alpha_frac": 0.584083045, "autogenerated": false, "ratio": 3.686224489795918, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9757758196878934, "avg_score": 0.0025098675833969955, "num_lines": 55 }
from fractions import Fraction def IsCancellingDigitFraction(numerator, denominator): #Do they share a digit in both numerator and denominator? f = Fraction(numerator, denominator) numeratorStr = str(numerator) denominatorStr = str(denominator) for nd in str(numeratorStr): if nd in denominatorStr: if denominatorStr.replace(nd,'',1) == '0': continue reducedFraction = Fraction(int(numeratorStr.replace(nd,'',1)), \ int(denominatorStr.replace(nd,'',1))) if reducedFraction == f: return True return False product = Fraction(1) for numerator in range(10,100): for denominator in range(numerator+1, 100): if (numerator % 10 == 0 and denominator % 10 == 0): continue if(IsCancellingDigitFraction(numerator, denominator)): print ("%d / %d" % (numerator,denominator)) product *= Fraction(numerator,denominator) print(product.denominator)
{ "repo_name": "danroberts728/Project-Euler-Answers", "path": "python/Problem33.py", "copies": "1", "size": "1052", "license": "mit", "hash": -6673479327114582000, "line_mean": 35.275862069, "line_max": 76, "alpha_frac": 0.6064638783, "autogenerated": false, "ratio": 4.515021459227468, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.015663599624945564, "num_lines": 29 }
from fractions import Fraction def spread(start, end, count, mode=1): """spread(start, end, count [, mode]) -> generator Yield a sequence of evenly-spaced numbers between start and end. The range start...end is divided into count evenly-spaced (or as close to evenly-spaced as possible) intervals. The end-points of each interval are then yielded, optionally including or excluding start and end themselves. By default, start is included and end is excluded. For example, with start=0, end=2.1 and count=3, the range is divided into three intervals: (0.0)-----(0.7)-----(1.4)-----(2.1) resulting in: >>> list(spread(0.0, 2.1, 3)) [0.0, 0.7, 1.4] Optional argument mode controls whether spread() includes the start and end values. mode must be an int. Bit zero of mode controls whether start is included (on) or excluded (off); bit one does the same for end. Hence: 0 -> open interval (start and end both excluded) 1 -> half-open (start included, end excluded) 2 -> half open (start excluded, end included) 3 -> closed (start and end both included) By default, mode=1 and only start is included in the output. (Note: depending on mode, the number of values returned can be count, count-1 or count+1.) """ if not isinstance(mode, int): raise TypeError('mode must be an int') if count != int(count): raise ValueError('count must be an integer') if count <= 0: raise ValueError('count must be positive') if mode & 1: yield start width = Fraction(end-start) start = Fraction(start) for i in range(1, count): yield float(start + i*width/count) if mode & 2: yield end
{ "repo_name": "ActiveState/code", "path": "recipes/Python/577878_Generate_equallyspaced_floats/recipe-577878.py", "copies": "1", "size": "1772", "license": "mit", "hash": -7987312560855622000, "line_mean": 34.44, "line_max": 77, "alpha_frac": 0.6439051919, "autogenerated": false, "ratio": 3.8945054945054944, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005128205128205128, "num_lines": 50 }
from fractions import Fraction from function.generic_univariate_pitch_function import GenericUnivariatePitchFunction from function.piecewise_linear_function import PiecewiseLinearFunction from function.scalar_range_interpreter import ScalarRangeInterpreter from function.chromatic_range_interpreter import ChromaticRangeInterpreter from instruments.instrument_catalog import InstrumentCatalog from melody.constraints.chordal_pitch_constraint import ChordalPitchConstraint from melody.constraints.pitch_range_constraint import PitchRangeConstraint from melody.constraints.step_sequence_constraint import StepSequenceConstraint from melody.structure.melodic_form import MelodicForm from melody.structure.motif import Motif from structure.LineGrammar.core.line_grammar_executor import LineGrammarExecutor from structure.lite_score import LiteScore from structure.tempo import Tempo from structure.time_signature import TimeSignature from timemodel.duration import Duration from timemodel.event_sequence import EventSequence from timemodel.position import Position from timemodel.tempo_event import TempoEvent from timemodel.tempo_event_sequence import TempoEventSequence from timemodel.time_signature_event import TimeSignatureEvent from tonalmodel.diatonic_pitch import DiatonicPitch import math from tonalmodel.pitch_range import PitchRange from tonalmodel.range import Range from transformation.reshape.min_curve_fit_filter import MinCurveFitFilter from transformation.reshape.t_reshape import TReshape BASE = DiatonicPitch.parse('C:4').chromatic_distance def create_score(grammar_str, instrument, ts): lge = LineGrammarExecutor() target_line, target_hct = lge.parse(grammar_str) tempo_seq = TempoEventSequence() ts_seq = EventSequence() tempo_seq.add(TempoEvent(Tempo(60, Duration(1, 4)), Position(0))) ts_seq.add(TimeSignatureEvent(TimeSignature(ts[0], Duration(1, ts[1]), ts[2]), Position(0))) c = InstrumentCatalog.instance() violin = c.get_instrument(instrument) return LiteScore(target_line, target_hct, violin, tempo_seq, ts_seq) def duration_ltr(duration): if duration.duration == Fraction(1, 16): return 's' elif duration.duration == Fraction(3, 16): return 'i@' elif duration.duration == Fraction(1, 8): return 'i' elif duration.duration == Fraction(3, 8): return 'q@' elif duration.duration == Fraction(1, 4): return 'q' elif duration.duration == Fraction(1, 2): return 'h' elif duration.duration == Fraction(1): return 'w' return '>' def str_line(line): notes = line.get_all_notes() prior_octave = None prior_duration = None note_annotations = list() for note in notes: annotation = '' d = duration_ltr(note.duration) if d != prior_duration: annotation += d prior_duration = d annotation += str(note.diatonic_pitch.diatonic_tone.diatonic_symbol) if note.diatonic_pitch is not None else 'R' o = note.diatonic_pitch.octave if note.diatonic_pitch is not None else prior_octave if o != prior_octave: annotation += ":" + str(o) prior_octave = o note_annotations.append(annotation) s = ' '.join(annotation for annotation in note_annotations) return s def print_line(line): print(str_line(line)) def sinasoidal(v): """ Maps v to a chromatic distance. :param v: :return: [0..1] -->[0..2*PI]-->[0..19] with value added to C:4 absolute chromatic distance. """ return BASE + 19 * math.sin(2 * math.pi * v/3) def three_sin(v): return math.sin(2 * math.pi * v/3) def simple_reshape_cpf(): print('----- test_simple_reshape_cpf -----') line_str = '{<C-Major: I> iE:4 E E E E E E E <:IV> qE ie e <:V> qe ie e <:VI> qE E iE E E E}' score = create_score(line_str, 'violin', (3, 4, 'sww')) all_notes = score.line.get_all_notes() # 11 scalar notes to C:4 (0) to G:5 (1) with pitch unit 1/19 interpreter = ChromaticRangeInterpreter(DiatonicPitch.parse('C:4'), 0, Fraction(1, 19)) pitch_function = GenericUnivariatePitchFunction(three_sin, Position(0), Position(3), interp=interpreter) # The first note should have one of 3 values, C:4, E:4, G:4 constraints = { ChordalPitchConstraint(all_notes[0]), ChordalPitchConstraint(all_notes[8]), ChordalPitchConstraint(all_notes[11]), ChordalPitchConstraint(all_notes[14]), PitchRangeConstraint([all_notes[0]], PitchRange.create('C:4', 'E:4')), } motif = Motif(score.line, constraints, 'A') melodic_form = MelodicForm([motif]) t_reshape = TReshape(score, pitch_function, Range(0, 3), melodic_form, True) results = t_reshape.apply() filter = MinCurveFitFilter(pitch_function, results) print('{0} filtered results'.format(len(filter.scored_results))) for index in range(0, min(5, len(filter.scored_results))): result = filter.scored_results[index] print('[{0}] {1} ({2})'.format(index, str_line(result[0].line), result[1])) print('Chords: {0}'.format(','.join([str(c) for c in score.hct.hc_list()]))) def reshape_with_spf(): print('----- test_reshape_with_spf -----') line_str = '{<C-Major: I> iE:4 E E E E q@E <:IV> qE ie e <:V> qe ie e <:VI> qE E iE E E E}' score = create_score(line_str, 'piano', (3, 4, 'sww')) tonality = score.hct.get_hc_by_position(0).tonality all_notes = score.line.get_all_notes() # 11 scalar notes to C:4 (0) to G:5 (11) with pitch unit 1/11 interpreter = ScalarRangeInterpreter(tonality, DiatonicPitch.parse('C:4'), 0, Fraction(1, 11)) pitch_function = GenericUnivariatePitchFunction(three_sin, Position(0), Position(3), False, interpreter) # The first note should have one of 3 values, C:4, E:4, G:4 constraints = { ChordalPitchConstraint(all_notes[0]), ChordalPitchConstraint(all_notes[8]), ChordalPitchConstraint(all_notes[11]), ChordalPitchConstraint(all_notes[14]), PitchRangeConstraint([all_notes[0]], PitchRange.create('C:4', 'E:4')), } motif = Motif(score.line, constraints, 'A') melodic_form = MelodicForm([motif]) t_reshape = TReshape(score, pitch_function, Range(0, 3), melodic_form, True) results = t_reshape.apply() filter = MinCurveFitFilter(pitch_function, results) print('{0} filtered results'.format(len(filter.scored_results))) for index in range(0, min(5, len(filter.scored_results))): result = filter.scored_results[index] print('[{0}] {1} ({2})'.format(index, str_line(result[0].line), result[1])) constraints = { ChordalPitchConstraint(all_notes[0]), ChordalPitchConstraint(all_notes[4]), ChordalPitchConstraint(all_notes[6]), ChordalPitchConstraint(all_notes[8]), ChordalPitchConstraint(all_notes[12]), ChordalPitchConstraint(all_notes[14]), PitchRangeConstraint([all_notes[0]], PitchRange.create('C:4', 'G:4')), #PitchRangeConstraint([all_notes[4]], PitchRange.create('E:5', 'G:5')), #PitchRangeConstraint([all_notes[6]], PitchRange.create('C:5', 'G:5')), #PitchRangeConstraint([all_notes[8]], PitchRange.create('C:4', 'G:4')), #PitchRangeConstraint([all_notes[12]], PitchRange.create('E:2', 'A:2')), #PitchRangeConstraint([all_notes[14]], PitchRange.create('E:2', 'G:2')), } motif = Motif(score.line, constraints, 'A') melodic_form = MelodicForm([motif]) t_reshape = TReshape(score, pitch_function, Range(0, 3), melodic_form, True) results = t_reshape.apply() filter = MinCurveFitFilter(pitch_function, results) print('{0} filtered results'.format(len(filter.scored_results))) for index in range(0, min(5, len(filter.scored_results))): result = filter.scored_results[index] print('[{0}] {1} ({2})'.format(index, str_line(result[0].line), result[1])) def reshape_to_scale(): print('----- test_reshape_to_scale -----') line_str = '{<C-Major: I> iE:4 E E E E E E E E E E E E E E E E E E E E E E E wE}' score = create_score(line_str, 'violin', (4, 4, 'swww')) tonality = score.hct.get_hc_by_position(0).tonality all_notes = score.line.get_all_notes() plf = PiecewiseLinearFunction([(0, 0), (1, 8), (Fraction(3, 2), 4), (2, 8), (3, 0)]) for i in range(0, 17): x = Fraction(1, 8) * i y = plf(x) print('({0}, {1})'.format(x, y)) time_range = Range(0, 3) interpreter = ScalarRangeInterpreter(tonality, DiatonicPitch.parse('C:4'), 0, 1) pitch_function = GenericUnivariatePitchFunction(plf, Position(0), Position(3), False, interpreter) constraints = { ChordalPitchConstraint(all_notes[0]), PitchRangeConstraint([all_notes[0]], PitchRange.create('C:4', 'G:4')), } motif = Motif(score.line, constraints, 'A') melodic_form = MelodicForm([motif]) t_reshape = TReshape(score, pitch_function, time_range, melodic_form, False) results = t_reshape.apply() filter = MinCurveFitFilter(pitch_function, results) print('{0} filtered results'.format(len(filter.scored_results))) for index in range(0, min(5, len(filter.scored_results))): result = filter.scored_results[index] print('[{0}] {1} ({2})'.format(index, str_line(result[0].line), result[1])) def motif_example(): print('----- motif_example -----') line_str = '{<C-Major: I> iC:4 D E D E E E E C D E D E E E E C D E D E E E E wE}' score = create_score(line_str, 'piano', (4, 4, 'swww')) tonality = score.hct.get_hc_by_position(0).tonality all_notes = score.line.get_all_notes() constraints = { StepSequenceConstraint([all_notes[0], all_notes[1], all_notes[2], all_notes[3]], [1, 1, -1]) } motif = Motif([all_notes[0], all_notes[1], all_notes[2], all_notes[3]], constraints) motif1 = motif.copy_to(all_notes[8]) motif2 = motif.copy_to(all_notes[16]) form = MelodicForm([motif, motif1, motif2]) # 11 scalar notes to C:4 (0) to G:5 (11) with pitch unit 1/11 interpreter = ScalarRangeInterpreter(tonality, DiatonicPitch.parse('C:4'), 0, Fraction(1, 11)) pitch_function = GenericUnivariatePitchFunction(three_sin, Position(0), Position(3), False, interpreter) t_reshape = TReshape(score, pitch_function, Range(0, 3), form, True) results = t_reshape.apply() filter = MinCurveFitFilter(pitch_function, results) print('{0} filtered results'.format(len(filter.scored_results))) for index in range(0, min(5, len(filter.scored_results))): result = filter.scored_results[index] print('[{0}] {1} ({2})'.format(index, str_line(result[0].line), result[1])) #simple_reshape_cpf() #reshape_with_spf() #reshape_to_scale() motif_example()
{ "repo_name": "dpazel/music_rep", "path": "transformation/reshape/t_reshape_book_examples.py", "copies": "1", "size": "10839", "license": "mit", "hash": 6108142017910697000, "line_mean": 37.0315789474, "line_max": 120, "alpha_frac": 0.6651905157, "autogenerated": false, "ratio": 3.1609798775153104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.432617039321531, "avg_score": null, "num_lines": null }
from fractions import Fraction from ..library.base import number_to_list from ..library.sqrt import is_square from ..library.number_theory.continued_fractions import convergents_sqrt def solve(bound: int=100, digits: int=100, base: int=10): sufficient = base ** digits accumulate = 0 for n in range(bound + 1): if is_square(n): continue for convergent in convergents_sqrt(n): if convergent.denominator > sufficient: break while convergent > 1: convergent *= Fraction(1, base) remainder = Fraction(0, 1) power = Fraction(1, 1) for digit in range(1, digits + 1): power *= Fraction(1, base) while convergent - power >= 0: remainder += power convergent -= power accumulate += sum(number_to_list(remainder.numerator * (sufficient // remainder.denominator), base)) return accumulate
{ "repo_name": "cryvate/project-euler", "path": "project_euler/solutions/problem_80.py", "copies": "1", "size": "1051", "license": "mit", "hash": -4858770439012118000, "line_mean": 26.6578947368, "line_max": 79, "alpha_frac": 0.555661275, "autogenerated": false, "ratio": 4.54978354978355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0027223230490018148, "num_lines": 38 }
from fractions import Fraction from raiden.constants import DAI_TOKEN_ADDRESS, WETH_TOKEN_ADDRESS from raiden.settings import DEFAULT_DAI_FLAT_FEE, DEFAULT_WETH_FLAT_FEE, MediationFeeConfig from raiden.utils.typing import Dict, FeeAmount, ProportionalFeeAmount, TokenAddress, Tuple def ppm_fee_per_channel(per_hop_fee: ProportionalFeeAmount) -> ProportionalFeeAmount: """ Converts proportional-fee-per-mediation into proportional-fee-per-channel Input and output are given in parts-per-million (ppm). See https://raiden-network-specification.readthedocs.io/en/latest/mediation_fees.html #converting-per-hop-proportional-fees-in-per-channel-proportional-fees for how to get to this formula. """ per_hop_ratio = Fraction(per_hop_fee, 10 ** 6) return ProportionalFeeAmount(round(per_hop_ratio / (per_hop_ratio + 2) * 10 ** 6)) def prepare_mediation_fee_config( cli_token_to_flat_fee: Tuple[Tuple[TokenAddress, FeeAmount], ...], cli_token_to_proportional_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount], ...], cli_token_to_proportional_imbalance_fee: Tuple[ Tuple[TokenAddress, ProportionalFeeAmount], ... ], cli_cap_mediation_fees: bool, ) -> MediationFeeConfig: """Converts the mediation fee CLI args to proper per-channel mediation fees.""" tn_to_flat_fee: Dict[TokenAddress, FeeAmount] = { # Add the defaults for flat fees for DAI/WETH WETH_TOKEN_ADDRESS: FeeAmount(DEFAULT_WETH_FLAT_FEE // 2), DAI_TOKEN_ADDRESS: FeeAmount(DEFAULT_DAI_FLAT_FEE // 2), } # Store the flat fee settings for the given token addresses # The given flat fee is for the whole mediation, but that includes two channels. # Therefore divide by 2 here. for address, fee in cli_token_to_flat_fee: tn_to_flat_fee[address] = FeeAmount(fee // 2) tn_to_proportional_fee: Dict[TokenAddress, ProportionalFeeAmount] = { address: ppm_fee_per_channel(prop_fee) for address, prop_fee in cli_token_to_proportional_fee } tn_to_proportional_imbalance_fee: Dict[TokenAddress, ProportionalFeeAmount] = { address: prop_fee for address, prop_fee in cli_token_to_proportional_imbalance_fee } return MediationFeeConfig( token_to_flat_fee=tn_to_flat_fee, token_to_proportional_fee=tn_to_proportional_fee, token_to_proportional_imbalance_fee=tn_to_proportional_imbalance_fee, cap_meditation_fees=cli_cap_mediation_fees, )
{ "repo_name": "raiden-network/raiden", "path": "raiden/utils/mediation_fees.py", "copies": "1", "size": "2497", "license": "mit", "hash": 8149381115258195000, "line_mean": 42.0517241379, "line_max": 91, "alpha_frac": 0.7136563877, "autogenerated": false, "ratio": 3.148802017654477, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4362458405354477, "avg_score": null, "num_lines": null }
from fractions import Fraction from typing import Tuple from .base import list_to_number Representation = Tuple[Tuple[int, int], Tuple[int, int]] def unit_fraction_to_representation(denominator: int, base: int=10) -> Representation: return fraction_to_representation(Fraction(1, denominator), base) def fraction_to_representation(fraction: Fraction, base: int=10) -> Representation: """Returns fraction representation of 1 / denominator as 0.abcd(efgh) as ((abcd, 4), (efgh, 4)).""" if fraction < 0 or fraction >= 1: raise ValueError(f'Cannot find decimal expansion of {fraction}, ' f' require 0 <= x < 1.') numerator = fraction.numerator denominator = fraction.denominator block_size = 1 block_length = 0 while block_size < denominator: block_size *= base block_length += 1 remainders = [] blocks = [] remainder = block_size * numerator while (remainder not in remainders) and remainder != 0: remainders.append(remainder) block, remainder = divmod(remainder, denominator) blocks.append(block) remainder *= block_size if remainder == 0: # terminating index = len(remainders) else: # repeating index = remainders.index(remainder) prefix = list_to_number(blocks[:index], block_size), \ index * block_length repeat = list_to_number(blocks[index:], block_size), \ (len(blocks) - index) * block_length return prefix, repeat def representation_to_fraction(representation: Representation, base: int=10) -> Fraction: prefix_factor = base ** representation[0][1] if representation[1][1] == 0: return Fraction(representation[0][0], prefix_factor) geometric = base ** representation[1][1] - 1 numerator = representation[0][0] * geometric + representation[1][0] return Fraction(numerator, prefix_factor * geometric)
{ "repo_name": "cryvate/project-euler", "path": "project_euler/library/fraction_representation.py", "copies": "1", "size": "2055", "license": "mit", "hash": -6591926126896780000, "line_mean": 26.4, "line_max": 73, "alpha_frac": 0.6199513382, "autogenerated": false, "ratio": 4.237113402061856, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012629102115608863, "num_lines": 75 }
from fractions import Fraction if __name__ == "__main__": n = input() y = map(int, raw_input().split()) used = set() for i in xrange(1, n): if i in used: continue k = Fraction(y[i] - y[0], i) in_line = set() in_line.add(0) in_line.add(i) for j in xrange(i + 1, n): k_j = Fraction(y[j] - y[0], j) if k_j == k: in_line.add(j) used.add(j) out_line = [] find = True for j in xrange(1, n): if j not in in_line: if len(out_line) > 0: k_j = Fraction(y[j] - out_line[-1][1], j - out_line[-1][0]) if k_j != k: find = False break out_line.append((j, y[j])) if len(out_line) == 0: find = False if find: break if not find: if n == 2: find = True else: k = y[2] - y[1] if y[1] - y[0] != k: find = True for j in xrange(2, n): if y[j] - y[j - 1] != k: find = False break if find: print 'Yes' else: print 'No'
{ "repo_name": "EdisonAlgorithms/CodeForces", "path": "contest/849/B.py", "copies": "3", "size": "1318", "license": "mit", "hash": -5042312554069364000, "line_mean": 21.724137931, "line_max": 79, "alpha_frac": 0.3474962064, "autogenerated": false, "ratio": 3.5912806539509536, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.020689655172413793, "num_lines": 58 }
from fractions import Fraction import math class Probability(Fraction, object): def probability(self): return 1 - self.relative_probability() def relative_probability(self): return self.numerator / self.denominator def combination(objects, selections): return math.factorial(objects) / (math.factorial(objects - selections) * math.factorial(selections)) def expected_value(cost=0.0, prize=0.0, success=0.0): failure = 1.0 - success failureCost = cost * failure netProfit = prize - cost successCost = netProfit * success return failureCost + successCost def independent_probability(chance, trials): currentChance = chance for i in range(trials - 1): currentChance = currentChance * chance return currentChance def mean(): pass def probability(success, total): return Probability(success, total).probability() def permutation(objects, selections): return math.factorial(objects) / math.factorial(objects - selections) def relative_probability(success, total): return Probability(success, total).relative_probability() def standard_deviation(): pass
{ "repo_name": "Chronotron/chaos-beast", "path": "MA120/probability/probality_functions.py", "copies": "1", "size": "1155", "license": "mit", "hash": 2561127477094951400, "line_mean": 22.5714285714, "line_max": 104, "alpha_frac": 0.7177489177, "autogenerated": false, "ratio": 3.9827586206896552, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5200507538389655, "avg_score": null, "num_lines": null }
from fractions import Fraction import numpy as np def normalize(v): """ Normalize a vector v. """ return np.array(v) / np.sqrt(abs(np.dot(v, v))) def make_symmetry_matrix(upper_triangle): """ Given three or six integers/rationals, fill them into a 3x3 (or 4x4) symmetric matrix. Always return a numpy 2d array of int type. """ if len(upper_triangle) == 3: a12, a13, a23 = upper_triangle M = [[1, a12, a13], [a12, 1, a23], [a13, a23, 1]] elif len(upper_triangle) == 6: a12, a13, a14, a23, a24, a34 = upper_triangle M = [ [1, a12, a13, a14], [a12, 1, a23, a24], [a13, a23, 1, a34], [a14, a24, a34, 1], ] else: raise ValueError("Three or six inputs are expected.") return np.array(M) def get_point_from_distance(M, d, normalized=True): """ Given the normal vectors of the mirrors stored as row vectors in `M` and a tuple of non-negative floats `d`, compute the vector `v` whose distance vector to the mirrors is `d` and choose whether to return its normalized version. """ p = np.linalg.solve(M, d) if normalized: p = normalize(p) return p def get_coxeter_matrix(coxeter_diagram): """ Get the Coxeter matrix from a given coxeter_diagram. The Coxeter matrix is square and entries are all integers, it describes the relations between the generators of the symmetry group. Here is the math: suppose two mirrors m_i, m_j form an angle p/q where p,q are coprime integers, then the two generator reflections about these two mirrors r_i, r_j satisfy (r_ir_j)^p = 1. Example: >>> coxeter_diagram = (3, 2, Fraction(5, 2)) >>> get_coxeter_matrix(coxeter_diagram) >>> [[1, 3, 2], [3, 1, 5], [2, 5, 1]] Note that in general one cannot recover the Coxeter diagram from the Coxeter matrix since a star polytope may have the same Coxeter matrix with a convex one. """ upper_triangle = [x.numerator for x in coxeter_diagram] return make_symmetry_matrix(upper_triangle).astype(np.int) def get_spherical_mirrors(coxeter_diagram): """ Given three or six integers/rationals that represent the angles between the mirrors (a rational p means the angle is π/p), return a 3x3 or 4x4 matrix whose rows are the normal vectors of the mirrors. Here the tiling determined by `coxeter_diagram` must be spherical. """ coxeter_matrix = make_symmetry_matrix(coxeter_diagram).astype(np.float) C = -np.cos(np.pi / coxeter_matrix) M = np.zeros_like(C) M[0, 0] = 1 M[1, 0] = C[0, 1] M[1, 1] = np.sqrt(1 - M[1, 0] * M[1, 0]) M[2, 0] = C[0, 2] M[2, 1] = (C[1, 2] - M[1, 0] * M[2, 0]) / M[1, 1] M[2, 2] = np.sqrt(abs(1 - M[2, 0] * M[2, 0] - M[2, 1] * M[2, 1])) if len(coxeter_matrix) == 4: M[3, 0] = C[0, 3] M[3, 1] = (C[1, 3] - M[1, 0] * M[3, 0]) / M[1, 1] M[3, 2] = (C[2, 3] - M[2, 0] * M[3, 0] - M[2, 1] * M[3, 1]) / M[2, 2] M[3, 3] = np.sqrt( abs(1 - M[3, 0] * M[3, 0] - M[3, 1] * M[3, 1] - M[3, 2] * M[3, 2]) ) return M def get_euclidean_mirrors(coxeter_diagram): """ Given three or six integers that represent the angles between the mirrors, return a 3x3 or 4x4 matrix whose rows are the normal vectors of the mirrors. Here the tiling determined by `coxeter_diagram` must be Euclidean. """ coxeter_matrix = make_symmetry_matrix(coxeter_diagram).astype(np.float) C = -np.cos(np.pi / coxeter_matrix) M = np.zeros_like(C) M[0, 0] = 1 M[1, 0] = C[0, 1] M[1, 1] = np.sqrt(1 - M[1, 0] * M[1, 0]) M[2, 0] = C[0, 2] M[2, 1] = (C[1, 2] - M[1, 0] * M[2, 0]) / M[1, 1] if len(coxeter_matrix) == 3: M[2, 2] = 1 else: M[2, 2] = np.sqrt(abs(1 - M[2, 0] * M[2, 0] - M[2, 1] * M[2, 1])) M[3, 0] = C[0, 3] M[3, 1] = (C[1, 3] - M[1, 0] * M[3, 0]) / M[1, 1] M[3, 2] = (C[2, 3] - M[2, 0] * M[3, 0] - M[2, 1] * M[3, 1]) / M[2, 2] M[3, 3] = 1 return M def get_hyperbolic_mirrors(coxeter_diagram): """ Get reflection mirrors for the 2D hyperbolic case. """ C = -np.cos(np.pi / make_symmetry_matrix(coxeter_diagram).astype(np.float)) M = np.zeros_like(C).astype(np.complex) M[0, 0] = 1 M[1, 0] = C[1, 0] M[1, 1] = np.sqrt(1 - M[1, 0] * M[1, 0]) M[2, 0] = C[2, 0] M[2, 1] = (C[2, 1] - M[2, 0] * M[1, 0]) / M[1, 1] M[2, 2] = np.sqrt(abs(M[2, 0] * M[2, 0] + M[2, 1] * M[2, 1] - 1)) * 1j return M def get_hyperbolic_honeycomb_mirrors(coxeter_diagram): """ Get reflection mirrors for the 3D hyperbolic honeycomb case. """ C = -np.cos(np.pi / make_symmetry_matrix(coxeter_diagram).astype(np.float)) M = np.zeros_like(C).astype(np.complex) M[0, 0] = 1 M[1, 0] = C[1, 0] M[1, 1] = np.sqrt(1 - M[1, 0] * M[1, 0]) M[2, 0] = C[2, 0] M[2, 1] = (C[2, 1] - M[2, 0] * M[1, 0]) / M[1, 1] M[2, 2] = np.sqrt(abs(1 - M[2, 0] * M[2, 0] - M[2, 1] * M[2, 1])) M[3, 0] = C[3, 0] M[3, 1] = (C[3, 1] - M[3, 0] * M[1, 0]) / M[1, 1] M[3, 2] = (C[3, 2] - M[3, 0] * M[2, 0] - M[3, 1] * M[2, 1]) / M[2, 2] M[3, 3] = ( np.sqrt(abs(1 - M[3, 0] * M[3, 0] - M[3, 1] * M[3, 1] - M[3, 2] * M[3, 2])) * 1j ) return M def project_affine(v): """ Project a point in R^3 to a z=1 plane. We assume the z-component of v is already 1. """ return v[:-1] def project_poincare(v): """ Project a point in H^n to H^{n-1}. It's the projection from hyperboloid to Poincare's disk. """ return np.array([x.real for x in v[:-1]]) / (1 + v[-1].imag) def get_geometry_type(pqr): """ Get the geometry type. """ s = sum(Fraction(1, x) if x != -1 else 0 for x in pqr) if s > 1: return "spherical" if s == 1: return "euclidean" return "hyperbolic" def is_degenerate(cox_mat, active): """ Check if a 3d tiling defined by a triangle group (p, q, r) is degenerate. """ p, q, r = cox_mat[0, 1], cox_mat[0, 2], cox_mat[1, 2] m0, m1, m2 = active # if no mirrors are active then it's degenerate if not any(active): return True # if p, q, r are all equal to 2 they must be all active if p == 2 and q == 2 and r == 2: return not all(active) # so at least one of p, q, r is > 2 and at least one mirror is active else: # if at least two of p, q, r are > 2 then it's not degenerate if (p > 2 and q > 2) or (p > 2 and r > 2) or (q > 2 and r > 2): return False # so exactly two of p, q, r are equal to 2 elif p == 2 and q == 2: if not m0: return True else: return not any([m1, m2]) elif p == 2 and r == 2: if not m1: return True else: return not any([m0, m2]) else: if not m2: return True else: return not any([m0, m1]) # ------------------------------- # LaTeX formatting functions def export_latex_array(self, words, symbol=r"s", cols=4): r""" Export a list words to latex array format. `cols` is the number of columns of the output latex array. Example: words = [(0, 1), (1, 2, 3) ...] Return: \begin{array} &s_0s_1 & s_1s_2s_3 & ... &\\ ... \end{array} """ def to_latex(word): return "".join(symbol + "_{{{}}}".format(i) for i in word) latex = "" for i, word in enumerate(words): if i > 0 and i % cols == 0: latex += r"\\" + "\n" latex += to_latex(word) if i % cols != cols - 1: latex += "&" return r"\begin{{array}}\n{{{}}}{}\n\end{{array}}".format("l" * cols, latex) def pov_vector(v): """ Convert a vector to POV-Ray format. e.g. (x, y, z) --> <x, y, z>. """ return "<{}>".format(", ".join(str(x) for x in v)) def pov_vector_list(vectors): """ Convert a list of vectors to POV-Ray format, e.g. [(x, y, z), (a, b, c), ...] --> <x, y, z>, <a, b, c>, ... """ return ", ".join(pov_vector(v) for v in vectors)
{ "repo_name": "neozhaoliang/pywonderland", "path": "src/uniform-tilings/helpers.py", "copies": "1", "size": "8300", "license": "mit", "hash": 1224635133088532500, "line_mean": 29.737037037, "line_max": 88, "alpha_frac": 0.519219183, "autogenerated": false, "ratio": 2.6901134521880063, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8708215643392019, "avg_score": 0.000223398359197445, "num_lines": 270 }
from fractions import Fraction import pytest from mugen.mixins.Weightable import Weightable, WeightableList @pytest.fixture def weightable_list_a() -> WeightableList: return WeightableList([Weightable(weight=1), Weightable(weight=1), Weightable(weight=1), Weightable(weight=1)]) @pytest.fixture def weightable_list_b() -> WeightableList: return WeightableList([Weightable(weight=1), Weightable(weight=1), Weightable(weight=2), Weightable(weight=4)]) @pytest.fixture def weightable_list_c() -> WeightableList: return WeightableList([Weightable(weight=1/2), Weightable(weight=1/2), Weightable(weight=1), Weightable(weight=1)]) @pytest.fixture def weightable_list_d() -> WeightableList: return WeightableList([Weightable(weight=1), Weightable(weight=3), Weightable(weight=6), Weightable(weight=0)]) @pytest.fixture def weightables_regular(weight: float = 1) -> WeightableList: return WeightableList([Weightable(weight=2), Weightable(weight=2), Weightable(weight=2)], weight=weight) @pytest.fixture def weightables_nested(weight: float = 1) -> WeightableList: return WeightableList([Weightable(weight=3), weightables_regular(weight=3)], weight=weight) @pytest.fixture def weightables_double_nested(weight: float = 1) -> WeightableList: return WeightableList([Weightable(weight=3), weightables_nested(weight=3)], weight=weight) @pytest.mark.parametrize("weightables, expected_weights", [ (weightable_list_a(), [1 / 4, 1 / 4, 1 / 4, 1 / 4]), (weightable_list_b(), [1 / 8, 1 / 8, 2 / 8, 4 / 8]), (weightable_list_c(), [.5 / 3, .5 / 3, 1 / 3, 1 / 3]), (weightable_list_d(), [1 / 10, 3 / 10, 6 / 10, 0]), ]) def test_normalized_weights(weightables, expected_weights): assert weightables.normalized_weights == expected_weights @pytest.mark.parametrize("weightables, expected_percentages", [ (weightable_list_a(), [25, 25, 25, 25]), (weightable_list_b(), [12.5, 12.5, 25, 50]), (weightable_list_c(), [.5 / 3 * 100, .5 / 3 * 100, 1 / 3 * 100, 1 / 3 * 100]), (weightable_list_d(), [10, 30, 60, 0]), ]) def test_weight_percentages(weightables, expected_percentages): assert weightables.weight_percentages == expected_percentages @pytest.mark.parametrize("weightables, expected_fractions", [ (weightable_list_a(), [Fraction("1/4"), Fraction("1/4"), Fraction("1/4"), Fraction("1/4")]), (weightable_list_b(), [Fraction("1/8"), Fraction("1/8"), Fraction("1/4"), Fraction("1/2")]), (weightable_list_c(), [Fraction("1/6"), Fraction("1/6"), Fraction("1/3"), Fraction("1/3")]), (weightable_list_d(), [Fraction("1/10"), Fraction("3/10"), Fraction("6/10"), Fraction("0")]), ]) def test_weight_fractions(weightables, expected_fractions): assert weightables.weight_fractions == expected_fractions @pytest.mark.parametrize("weightables, expected_weights", [ (weightables_regular(), [pytest.approx(1/3), pytest.approx(1/3), pytest.approx(1/3)]), (weightables_nested(), [pytest.approx(1/2), pytest.approx(1/6), pytest.approx(1/6), pytest.approx(1/6)]), (weightables_double_nested(), [pytest.approx(1/2), pytest.approx(1/4), pytest.approx(1/12), pytest.approx(1/12), pytest.approx(1/12)]), ]) def test_weightable_list(weightables, expected_weights): flat_weightables = weightables.flatten() assert flat_weightables.weights == expected_weights
{ "repo_name": "scherroman/mugen", "path": "tests/unit/mixins/test_Weightable.py", "copies": "1", "size": "3380", "license": "mit", "hash": 1986731233781931500, "line_mean": 40.7283950617, "line_max": 119, "alpha_frac": 0.6846153846, "autogenerated": false, "ratio": 3.0783242258652095, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42629396104652095, "avg_score": null, "num_lines": null }
from fractions import Fraction class Vertex: def __init__(self, x, y, z): self.coordinates = (x, y, z) def __eq__(self, other): return ( isinstance(other, Vertex) and self.coordinates == other.coordinates ) def quadrance(vertex_1, vertex_2): return sum( (c1 - c2) ** 2 for c1, c2 in zip(vertex_1.coordinates, vertex_2.coordinates) ) def collinear(vertex_1, vertex_2, vertex_3): q12 = quadrance(vertex_1, vertex_2) q13 = quadrance(vertex_1, vertex_3) q23 = quadrance(vertex_2, vertex_3) cayley_menger_det = ( q12 * q12 + q13 * q13 + q23 * q23 - 2 * q12 * q13 - 2 * q12 * q23 - 2 * q13 * q23 ) return cayley_menger_det == 0 class Edge: def __init__(self, vertex_1, vertex_2): self.vertex_1 = vertex_1 self.vertex_2 = vertex_2 def __eq__(self, other): return ( isinstance(other, Edge) and self.vertex_1 == other.vertex_1 and self.vertex_2 == other.vertex_2 ) def quadrance(self): return quadrance(self.vertex_1, self.vertex_2) def foot_of_altitude(vertex, edge): x1, y1, z1 = edge.vertex_1.coordinates x2, y2, z2 = edge.vertex_2.coordinates x3, y3, z3 = vertex.coordinates t = Fraction( (x1 - x2) * (x1 - x3) + (y1 - y2) * (y1 - y3) + (z1 - z2) * (z1 - z3), (x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2 ) return Vertex(x1 + (x2 - x1) * t, y1 + (y2 - y1) * t, z1 + (z2 - z1) * t)
{ "repo_name": "jtauber/folds", "path": "folds.py", "copies": "1", "size": "1545", "license": "mit", "hash": 3773064388715422700, "line_mean": 24.3278688525, "line_max": 78, "alpha_frac": 0.5313915858, "autogenerated": false, "ratio": 2.803992740471869, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3835384326271869, "avg_score": null, "num_lines": null }
from fractions import Fraction def parse_sexp(string): """ Parses an S-Expression into a list-based tree. parse_sexp("(+ 5 (+ 3 5))") results in [['+', '5', ['+', '3', '5']]] """ sexp = [[]] word = '' in_str = False for c in string: if c == '(' and not in_str: sexp.append([]) elif c == ')' and not in_str: if word: sexp[-1].append(word) word = '' temp = sexp.pop() sexp[-1].append(temp) elif c in (' ', '\n', '\t') and not in_str: if word != '': sexp[-1].append(word) word = '' elif c == '\"': in_str = not in_str else: word += c return sexp[0] def make_str(ppddl_tree, level=0): """ Creates a string representation of a PPDDL tree. """ if not ppddl_tree: return '' # Make sure the resulting string has the correct indentation. indent = (' ' * (2*level)) ppddlstr = indent + '(' indent += ' ' # Appending subelements of the PPDDL tree. for i, element in enumerate(ppddl_tree): if isinstance(element, list): ppddlstr += '\n' + make_str(element, level + 1) else: if element.startswith(':') and i != 0: ppddlstr += '\n' + indent ppddlstr += element if i != len(ppddl_tree) - 1: ppddlstr += ' ' if element == ':parameters' and ppddl_tree[i + 1] == []: ppddlstr += '()' ppddlstr += ') ' return ppddlstr def get_all_probabilistic_effects(ppddl_tree, all_prob_effects_list, action = None): """ Adds all probabilistic effects in this PPDDL tree to the given list. The effects are added in pre-order traversal. We assume no nesting of probabilistic effect. A probabilistic effect is represented as a tuple (action, ppddl_tree) where "action" is the name of the action to which the effect belongs and "ppddl_tree" is the tree representation of the effect. """ if not isinstance(ppddl_tree, list) or not ppddl_tree: return if ppddl_tree[0] == ':action': action = ppddl_tree[1].rstrip('\r') if ppddl_tree[0] == 'probabilistic': all_prob_effects_list.append( (action, ppddl_tree) ) else: for element in ppddl_tree: get_all_probabilistic_effects(element, all_prob_effects_list, action) def get_all_determinizations_effect(probabilistic_effect_info): """ Generates all possible determinizations of the given probabilistic effect. A determinization is stored as a tuple (index, effect), where index represents the effect's order in the list of outcomes of the probabilistic effect, and effect represents the specific outcome. The method returns a tuple (action_name, all_determinizations) where "action_name" is the name of the action to which the probabilistic effect belongs, and "all_determinizations" is a list with all the determinizations of the effect. """ all_determinizations = [] total_explicit_prob = Fraction(0) idx = 0 probabilistic_effect = probabilistic_effect_info[1] for i in range(2, len(probabilistic_effect), 2): total_explicit_prob += Fraction(probabilistic_effect[i - 1]) # The first element is the index of the deterministic effect, the second # is the effect itself. all_determinizations.append( (idx, probabilistic_effect[i]) ) idx += 1 if total_explicit_prob != Fraction(1): all_determinizations.append( (idx, ['and']) ) # No-op effect return (probabilistic_effect_info[0], all_determinizations) def get_mlo_determinization_effect(probabilistic_effect_info): """ Generates the most likely outcome determinization of the given probabilistic effect. A determinization is stored as a tuple (index, effect), where index represents the effect's order in the list of outcomes of the probabilistic effect, and effect represents the specific outcome. The method returns a tuple (action_name, mlo_determinization) where "action_name" is the name of the action to which the probabilistic effect belongs, and "mlo_determinization" is the most likely effect. """ probability_mlo = Fraction(-1) total_non_explicit_prob = Fraction(1) idx = 0 probabilistic_effect = probabilistic_effect_info[1] mlo_determinization = [] for i in range(2, len(probabilistic_effect), 2): probability_effect = Fraction(probabilistic_effect[i - 1]) total_non_explicit_prob -= probability_effect if Fraction(probabilistic_effect[i - 1]) > probability_mlo: probability_mlo = probability_effect mlo_determinization = (idx, probabilistic_effect[i]) idx += 1 if total_non_explicit_prob > probability_mlo: # No-op effect is the most likely outcome mlo_determinization = (idx, ['and']) return (probabilistic_effect_info[0], mlo_determinization) def get_all_determinizations_comb(determinizations_of_all_effects): """ Generates all possible combinations of the given list of lists of probabilistic effects determinizations. Each element of the input variable is a tuple with all the determinizations of a given probabilistic effect, as returned by function "get_all_determinizations_effect". The method returns a list with all the possible combinations of these determinizations, in the same order they are given. So, for example, if the input is: ((action_0, (0, det_0_0), ..., (k_0, det_0_2)), (action_1, (0, det_1_0), ..., (k_0, det_1_1))) The method will return the following list of 6 combinations: ( ((action_0, (0, det_0_0)), (action_1, (0, det_1_0))), ((action_0, (0, det_0_0)), (action_1, (0, det_1_1))), ..., ((action_0, (2, det_0_2)), (action_1, (0, det_1_0))), ((action_0, (2, det_0_2)), (action_1, (0, det_1_1))) ) """ # Base case for the recursion, only determinizations for one effect. all_determinizations = [] if len(determinizations_of_all_effects) == 1: # Note that determinizations_of_all_effects[0] is a tuple: # (action_name, all_determinizations_of_the_actions_effect) for determinization in determinizations_of_all_effects[0][1]: all_determinizations.append([(determinizations_of_all_effects[0][0], determinization)]) return all_determinizations # We do this recursively by generating all combinations of effects from the # second effect onwards, then generating all combinations of the first # effect's determinization with the resulting list. remaining_determinizations_comb = ( get_all_determinizations_comb(determinizations_of_all_effects[1:])) for effect_determinization in determinizations_of_all_effects[0][1]: for remaining_effects_determinization in remaining_determinizations_comb: determinization = [(determinizations_of_all_effects[0][0], effect_determinization)] determinization.extend(remaining_effects_determinization) all_determinizations.append(determinization) return all_determinizations def determinize_tree(determinization, ppddl_tree, index = 0): """ Replaces all probabilistic effects with the given determinization. Variable "determinization" is a list of determinizations, as created by "get_all_determinizations_effect". This function will visit the PPDDL tree in pre-order traversal and each time it encounters a probabilistic effect, it will replace it with the effect at "determinizaton[index][1][1]", then increment variable "index" and return its new value. Therefore, the user of this function must ensure that the each effect in the given determinization corresponds to the proper probabilistic effect in the PPDDL tree. """ if not isinstance(ppddl_tree, list) or not ppddl_tree: return index if ppddl_tree[0] == 'probabilistic': ppddl_tree[:] = [] ppddl_tree.extend(determinization[index][1][1]) return index + 1 else: for element in ppddl_tree: index = determinize_tree(determinization, element, index) return index def clean_up_tree(ppddl_tree): """ Removes from the tree all effects that affect fluents (increase, decrease) as well as void effects generated by the determinization. """ # Ignore fluent-related effects and requirements list. if not ppddl_tree: return if (ppddl_tree[0] == 'increase' or ppddl_tree[0] == 'decrease' or ppddl_tree[0] == ':requirements'): ppddl_tree[:] = [] return for sub_tree in ppddl_tree: if isinstance(sub_tree, list): clean_up_tree(sub_tree) # Cleaning up empty conjuctions. if sub_tree and sub_tree[0] == 'and' and len(sub_tree) > 1: valid = [x for x in sub_tree[1:] if x != ['and'] and x != []] if not valid: sub_tree[:] = [] sub_tree.append('and')
{ "repo_name": "luisenp/mdp-lib", "path": "scripts/reduced/ppddl_util.py", "copies": "1", "size": "8867", "license": "mit", "hash": -5750514457806868000, "line_mean": 35.1959183673, "line_max": 81, "alpha_frac": 0.6605390775, "autogenerated": false, "ratio": 3.572522159548751, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9481741272331109, "avg_score": 0.0502639929435285, "num_lines": 245 }
from fractions import Fraction def rectangle_dot_count(vertices): """ Count rectangle dot count include edge """ assert len(vertices) == 2 width = abs(vertices[0][0] - vertices[1][0]) height = abs(vertices[0][1] - vertices[1][1]) dot_count = (width + 1) * (height + 1) return dot_count def diagonal_dot_count(vertices): assert len(vertices) == 2 width = abs(vertices[0][0] - vertices[1][0]) height = abs(vertices[0][1] - vertices[1][1]) assert width > 0 and height > 0 slope = Fraction(height, width) dot_count = width / slope.denominator + 1 return dot_count def right_triangle_dot_count(vertices): """ count right triangle dot count include edge """ diagonal_point = None for i in xrange(len(vertices)): v_1 = vertices[i] v_2 = vertices[(i + 1)% len(vertices)] if v_1[0] - v_2[0] != 0 and v_1[1] - v_2[1] != 0: diagonal_point = [v_1, v_2] break rect_count = rectangle_dot_count(diagonal_point) diagonal_count = diagonal_dot_count(diagonal_point) dot_count = (rect_count - diagonal_count) / 2 + diagonal_count return dot_count def get_surrounding_rectangle(vertices): xs = [v[0] for v in vertices] ys = [v[1] for v in vertices] x_min = min(xs) x_max = max(xs) y_min = min(ys) y_max = max(ys) return x_min, x_max, y_min, y_max def two_diagonal_down_right_triangle_dot_count(rect_coord, rect_point, diagonal_point, general_point): large_triangle_dots = \ right_triangle_dot_count(diagonal_point + [rect_point[2]]) intersect_point_1 = [general_point[0][0], rect_coord[2]] intersect_point_2 = [rect_coord[1], general_point[0][1]] small_triangle_dots_1 = \ right_triangle_dot_count([rect_point[0], general_point[0], intersect_point_1]) small_triangle_dots_2 = \ right_triangle_dot_count([rect_point[3], general_point[0], intersect_point_2]) rectangle_dots = rectangle_dot_count([[general_point[0][0]+1, general_point[0][1]-1], rect_point[2]]) diagonal_line_dots = diagonal_dot_count(diagonal_point) triangle_dots = large_triangle_dots - small_triangle_dots_1 - \ small_triangle_dots_2 - rectangle_dots - \ diagonal_line_dots + 3 return triangle_dots def two_diagonal_vertical_or_horizontal_dot_count(rect_coord, rect_point, diagonal_point, general_point): large_rectangle_dots = right_triangle_dot_count(rect_point[::3]) if rect_coord[0] == general_point[0][0] or \ rect_coord[1] == general_point[0][0]: small_triangle_dots_1 = \ right_triangle_dot_count([rect_point[1], rect_point[3], general_point[0]]) small_triangle_dots_2 = \ right_triangle_dot_count([rect_point[0], rect_point[2], general_point[0]]) vertical_line_dots = rect_coord[3] - rect_coord[2] + 1 triangle_dots = large_rectangle_dots - small_triangle_dots_1 - \ small_triangle_dots_2 - vertical_line_dots + 3 else: small_triangle_dots_1 = \ right_triangle_dot_count([rect_point[0], rect_point[1], general_point[0]]) small_triangle_dots_2 = \ right_triangle_dot_count([rect_point[2], rect_point[3], general_point[0]]) horizontal_line_dots = rect_coord[1] - rect_coord[0] + 1 triangle_dots = large_rectangle_dots - small_triangle_dots_1 - \ small_triangle_dots_2 - horizontal_line_dots + 3 return triangle_dots def two_diagonal_touch_edge_down_right_triangle_dot_count(rect_coord, rect_point, diagonal_point, general_point): large_triangle_dots = right_triangle_dot_count(diagonal_point + [rect_point[2]]) small_triangle_dots = right_triangle_dot_count([general_point[0], rect_point[2], rect_point[3]]) line_dots_1 = general_point[0][0] - rect_coord[0] + 1 line_dots_2 = diagonal_dot_count(diagonal_point) triangle_dots = large_triangle_dots - small_triangle_dots - \ line_dots_1 - line_dots_2 + 3 return triangle_dots def two_diagonal_touch_edge_up_right_triangle_dot_count(rect_coord, rect_point, diagonal_point, general_point): large_triangle_dots = right_triangle_dot_count(diagonal_point + [rect_point[2]]) small_triangle_dots = right_triangle_dot_count([general_point[0], rect_point[0], rect_point[2]]) line_dots_1 = rect_coord[3] - general_point[0][1] + 1 line_dots_2 = diagonal_dot_count(diagonal_point) triangle_dots = large_triangle_dots - small_triangle_dots - \ line_dots_1 - line_dots_2 + 3 return triangle_dots def one_diagonal_down_left_triangle_dot_count(rect_coord, rect_point, diagonal_point, general_point): general_point = sorted(general_point, cmp=lambda x,y: x[0] - y[0]) large_rectangle_dots = rectangle_dot_count(rect_point[::3]) small_triangle_dots_1 = right_triangle_dot_count([rect_point[0], rect_point[1], general_point[0]]) small_triangle_dots_2 = right_triangle_dot_count([rect_point[0], rect_point[2], general_point[1]]) small_triangle_dots_3 = right_triangle_dot_count([general_point[0], general_point[1], rect_point[3]]) triangle_dots = large_rectangle_dots - small_triangle_dots_1 - \ small_triangle_dots_2 - small_triangle_dots_3 + 3 return triangle_dots def answer(vertices): # classify triangle types according to the rectangle surrounding # the triangle rect_coord = get_surrounding_rectangle(vertices) rect_point = [[rect_coord[0], rect_coord[2]], # down-left [rect_coord[0], rect_coord[3]], # up-left [rect_coord[1], rect_coord[2]], # down-right [rect_coord[1], rect_coord[3]], # up-right ] x_sum = rect_coord[0] + rect_coord[1] y_sum = rect_coord[2] + rect_coord[3] diagonal_point = [] general_point = [] for v in vertices: if v[0] in rect_coord and v[1] in rect_coord: diagonal_point.append(v) else: general_point.append(v) if len(diagonal_point) == 1: if rect_point[0] in vertices: dot_num = one_diagonal_down_left_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif rect_point[1] in vertices: for p in general_point: p[1] = y_sum - p[1] diagonal_point[0][1] = y_sum - diagonal_point[0][1] dot_num = one_diagonal_down_left_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif rect_point[2] in vertices: for p in general_point: p[0] = x_sum - p[0] diagonal_point[0][0] = x_sum - diagonal_point[0][0] dot_num = one_diagonal_down_left_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif rect_point[3] in vertices: for p in general_point: p[0] = x_sum - p[0] p[1] = y_sum - p[1] diagonal_point[0][0] = x_sum - diagonal_point[0][0] diagonal_point[0][1] = y_sum - diagonal_point[0][1] dot_num = one_diagonal_down_left_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: raise Exception('Something went wrong!') elif len(diagonal_point) == 2: if diagonal_point[0][0] - diagonal_point[1][0] == 0 or \ diagonal_point[0][1] - diagonal_point[1][1] == 0: dot_num = two_diagonal_vertical_or_horizontal_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][0] not in rect_coord and \ general_point[0][1] not in rect_coord: # Two diagonal point triangle case y_line = Fraction(diagonal_point[0][1] - diagonal_point[1][1], diagonal_point[0][0] - diagonal_point[1][0]) * \ (general_point[0][0] - diagonal_point[0][0]) + \ diagonal_point[0][1] y_general = general_point[0][1] diagonal_point = [rect_point[0], rect_point[3]] if y_general > y_line: # general point is above the diagonal line if rect_point[1] not in vertices: general_point[0][0] = x_sum - general_point[0][0] general_point[0][1] = y_sum - general_point[0][1] dot_num = two_diagonal_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: general_point[0][1] = y_sum - general_point[0][1] dot_num = two_diagonal_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: if rect_point[2] not in vertices: dot_num = two_diagonal_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: general_point[0][0] = x_sum - general_point[0][0] dot_num = two_diagonal_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: diagonal_point = [rect_point[0], rect_point[3]] if rect_point[0] in vertices: if general_point[0][1] == rect_coord[2]: dot_num = \ two_diagonal_touch_edge_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][1] == rect_coord[3]: for p in general_point: p[0] = x_sum - p[0] p[1] = y_sum - p[1] dot_num = \ two_diagonal_touch_edge_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][0] == rect_coord[1]: dot_num = \ two_diagonal_touch_edge_up_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][0] == rect_coord[0]: for p in general_point: p[0] = x_sum - p[0] p[1] = y_sum - p[1] dot_num = \ two_diagonal_touch_edge_up_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) else: if general_point[0][1] == rect_coord[2]: # y_min for p in general_point: p[0] = x_sum - p[0] dot_num = \ two_diagonal_touch_edge_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][1] == rect_coord[3]: # y_max for p in general_point: p[1] = y_sum - p[1] dot_num = \ two_diagonal_touch_edge_down_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][0] == rect_coord[1]: # x_max for p in general_point: p[1] = y_sum - p[1] dot_num = \ two_diagonal_touch_edge_up_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif general_point[0][0] == rect_coord[0]: # x_min for p in general_point: p[0] = x_sum - p[0] dot_num = \ two_diagonal_touch_edge_up_right_triangle_dot_count( rect_coord, rect_point, diagonal_point, general_point) elif len(diagonal_point) == 3: diagonal_point = None for i in xrange(len(vertices)): v_1 = vertices[i] v_2 = vertices[(i + 1)% len(vertices)] if v_1[0] - v_2[0] != 0 and v_1[1] - v_2[1] != 0: diagonal_point = [v_1, v_2] break horizontal_line_dots = rect_coord[1] - rect_coord[0] + 1 vertical_line_dots = rect_coord[3] - rect_coord[2] + 1 diagonal_line_dots = diagonal_dot_count(diagonal_point) triangle_dots = right_triangle_dot_count(vertices) dot_num = triangle_dots - horizontal_line_dots -vertical_line_dots - \ diagonal_line_dots + 3 else: raise Exception('Something went wrong!') return dot_num
{ "repo_name": "gongbudaizhe/bilib", "path": "demos/carrot_land/solution.py", "copies": "1", "size": "14673", "license": "mit", "hash": -999249502180946200, "line_mean": 46.954248366, "line_max": 78, "alpha_frac": 0.4898793703, "autogenerated": false, "ratio": 3.9507269789983845, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9935121748814616, "avg_score": 0.0010969200967537135, "num_lines": 306 }
from fractions import Fraction ########## ########## # # rational parameterization of a hyperbolic 3 dimensional sheet thing. # # equation: # # x^2 + y^2 - z^2 = 1 # ######### ######### # this is the same theory used to make the paramterization of the unit sphere # using four integers, m,n,m1,n1. ## consider a basic unit hyperbolic sheet thing # # x^2 + y^2 - z^2 = radius^2 = 1^2 # # x^2 + y^2 = l^2 # l^2 - z^2 = radius^2 # radius = 1, radius^2=1 # # example: begin with very simple pythagorean triple numbers:, 3,4,5 # now, assume x=3, y=4, l=5, z=3, radius=4. divide all by 4 # # x=3/4, y=4/4, l=5/4, z=3/4, radius=4/4=1 # # to verify: , 3^2=9 4^2=16, 5^2=25, 3^2=9 # (3/4)^2+(4/4)^2-(3/4)^2 = (4/4)^2 [ qx+qy-qz=r=1 ] # (3/4)^2+(4/4)^2 = (5/4)^2 [ qx+qy = ql ] # (5/4)^2-(3/4)^2 = (4/4)^2 [ ql-qz = qr=1 ] # qn = blue quadrance(n) = n^2 # # therefore the given point, with x,y,z coordinates [ 3/4, 4/4, 5/4 ] is # a rational point on the unit hyperbolic sheet thing. # theory # # step 0. We use Chromogeometry here for the sake of aesthetics. # # Blue Quadrance(x,y) = QBlue(x,y) = x^2 + y^2 # Red Quadrance(x,y) = QRed(x,y) = x^2 - y^2 # Green Quadrance(x,y) = QGreen(x,y) = 2xy # # step 1. find a rational paramterization of the hyperbola! # # well, there are many, but lets use one based on Chromogeometry: # # first, review the unit sphere paramterization # x = QRed(m,n) / QBlue(m,n) y = QGreen(m, n) / QBlue(m,n) # # it turns out if you expand these, you can kind of see a nice hyperbolic # paramterization: # # x = QBlue(m,n) / QRed(m,n) y = QGreen(m, n) / QRed(m, n) # # you can verify that x^2 - y^2 = 1 by some very simply algebra. # # # Step 3: expand the paramterization to 3 dimensions for the eqn' x^2+y^2-z^2=1 # Well, first, lets say that x^2+y^2 = l. # # Use the rational paramterization of the hyperbola to find l and z in terms of # two integers, m and n. # # l = m^2+n^2 / m^2-n^2 z = 2*m*n / m^2-n^2 # l = QBlue/QRed z = QGreen/QRed # ok great. We have l and z. What about x and y? # # # Well, recall that x^2 + y^2 = l^2. # divide this equation by l^2, you get this: # (x/l)^2 + (y/l)^2 = 1 # # We can use the rational paramterization of a unit circle but # our "x" will actually be x/l and "y" will be y/l. We are using different # m and n as well, call them "m1" and "n1" here. # # x/l = m1^2-n1^2 / m1^2+n1^2 y/l = 2*m1*n1 / m1^2+n1^2 # # x/l = QRed/QBlue y/l = QGreen/QBlue for Q(m1,n1) # # Now. That is quite interesting. You can choose m1, n1 as integers and get # values for x/l and y/l. But what if you want just x or y by itself? # # # Ahh, remember, we calculated l up above, based on two other integers, m and n # you can multiple the equations above by l to get your sol'n for x and y. # # x = l * ( m1^2-n1^2 / m1^2+n1^2 ) y = l * ( 2*m1*n1 / m1^2+n1^2 ) # # x = l * QRed/QBlue y = l * QGreen/QBlue # # you can use Algebra to rearrange all this, but basically, in the end, # we have x, y, and z as functions of m, n, m1, and n1, four separate integers. # # l = QBlue/QRed z = QGreen/QRed Q(m,n) # # x = QBlue(m,n)/QRed(m,n) * QRed(m1,n1)/QBlue(m1,n1) # y = QBlue(m,n)/QRed(m,n) * QGreen(m1,n1)/QBlue(m1,n1) # z = QGreen(m,n)/QRed(m,n) # # # possible problem: i have no idea if this works. # # and others have probably found better. xs,ys,zs=[],[],[] def sqr(x): return x*x def qblue(x,y): return sqr(x)+sqr(y) def qred(x,y): return sqr(x)-sqr(y) def qgreen(x,y): return 2*x*y depth=8 for m in range(0,depth): for n in range(0,depth): for m1 in range(0,depth): for n1 in range(0,depth): if qred(m,n)==0: continue if qblue(m,n)==0: continue if qblue(m1,n1)==0: continue l = Fraction( qblue(m,n), qred(m,n) ) x = l * Fraction( qred(m1,n1), qblue(m1,n1) ) y = l * Fraction( qgreen(m1,n1), qblue(m1,n1) ) z = Fraction( qgreen(m,n), qred(m,n) ) print x,y,z,' sq sum: ',x*x+y*y-z*z xs += [x] ys += [y] zs += [z] xs += [x] ys += [-y] zs += [z] print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-5.2,5.2]) ax.set_xlim([-5.2,5.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/ratparam3d/pythhypsheet.py", "copies": "1", "size": "4344", "license": "bsd-3-clause", "hash": 6216953964854711000, "line_mean": 27.2077922078, "line_max": 79, "alpha_frac": 0.5877071823, "autogenerated": false, "ratio": 2.242643262777491, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8157082750090112, "avg_score": 0.03465353899747576, "num_lines": 154 }
from fractions import Fraction ########## ########## # # rational parameterization of a hyperbolic 3 dimensional sheet thing. # take 2. # # equation: # # x^2 - y^2 - z^2 = 1 # ######### ######### # this is the same theory used to make the paramterization of the unit sphere # using four integers, m,n,m1,n1. # Chromogeometry is used for the sake of aesthetics. # q is short for 'quadrance' # # qblue(x,y)=x^2+y^2 qred(x,y)=x^2-y^2 qgreen(x,y)=2xy # # please see pthhypsheet.py for the full theory and derivation. # basically, consider a simple hyperbola. # x^2 - y^2 = 1 # # it has has a paramteriztaion like this: # # x=qblue(m,n)/qred(m.n) y=qgreen(m,n)/qred(m,n) # # so. x^2-y^2=l^2, and l^2-z^2=1 # # so l = qblue(m,n)/qred(m,n), z=qgreen(m,n)/qred(m,n), for integers m,n # # also # # x^2/l^2 - y^2/l^2 = 1, so use a new set of m,n, call them m1,n1 # # x/l = qblue(m1,n1)/qred(m1,n1) y/l = qgreen(m1,n1)/qred(m1,n1) # # so put l back in, solve for x or y: # # x = l * qblue/qred(m,n) # y = l * qblue/qred(m,n) # z = qgreen/qred(m,n) # # now x^2+y^2-z^2=1 # xs,ys,zs=[],[],[] def sqr(x): return x*x def qblue(x,y): return sqr(x)+sqr(y) def qred(x,y): return sqr(x)-sqr(y) def qgreen(x,y): return 2*x*y depth=8 for m in range(0,depth): for n in range(0,depth): for m1 in range(0,depth): for n1 in range(0,depth): if qred(m,n)==0: continue if qblue(m,n)==0: continue if qred(m1,n1)==0: continue l = Fraction( qblue(m,n), qred(m,n) ) x = l * Fraction( qblue(m1,n1), qred(m1,n1) ) y = l * Fraction( qgreen(m1,n1), qred(m1,n1) ) z = Fraction( qgreen(m,n), qred(m,n) ) print x,y,z,' sq rq(rq(x,y),z): ',x*x-y*y-z*z xs += [x] ys += [y] zs += [z] xs += [x] ys += [-y] zs += [z] print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-5.2,5.2]) ax.set_xlim([-5.2,5.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/ratparam3d/pythhypsheet2.py", "copies": "1", "size": "2004", "license": "bsd-3-clause", "hash": -8296609661365315000, "line_mean": 20.3191489362, "line_max": 77, "alpha_frac": 0.5818363273, "autogenerated": false, "ratio": 2.049079754601227, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3130916081901227, "avg_score": null, "num_lines": null }
from fractions import Fraction ########## ########## # # rational parameterization of the unit sphere # ######### ######### # consider a basic unit sphere # # x^2 + y^2 + z^2 = radius = 1^2 # # x^2 + y^2 = l^2 # l^2 + z^2 = radius^2 # radius = 1, radius^2=1 # # example: begin with very simple pythagorean triple numbers:, 3,4,5 and 5,12,13 # now, assume x=3, y=4, l=5, z=12, radius=13. divide all by 13 # # x=3/13, y=4/13, l=5/13, z=12/13, radius=13/13=1 # # to verify: , 3^2=9 4^2=16, 5^2=25, 12^2=144, 13^2=169 # (3/13)^2+(4/13)^2+(12/13)^2 = (13/13)^2 [ qx+qy+qz=r=1 ] # (3/13)^2+(4/13)^2 = (5/13)^2 [ qx+qy = ql ] # (5/13)^2+(12/13)^2 = (13/13)^2 [ ql+qz = qr=1 ] # qn = quadrance(n) = n^2 # # therefore the given point, with x,y,z coordinates [ 3/13, 4/13, 12/13 ] is # a rational point on the unit sphere. # theory # # Use the rational paramterization of the unit circle to find l and z. # # l = m^2-n^2 / m^2+n^2 z = 2*m*n / m^2+n^2 # # now, note that x^2 + y^2 = l^2. # divide this equation by l^2, you get this: # (x/l)^2 + (y/l)^2 = 1 # # we can again use the rational paramterization of a unit circle but # our "x" will actually be x/l and "y" will be y/l. We are using different # m and n as well, call them "m1" and "n1" here. # # x/l = m1^2-n1^2 / m1^2+n1^2 y/l = 2*m1*n1 / m1^2+n1^2 # # Now. That is quite interesting. You can choose m1, n1 as integers and get # values for x/l and y/l. But what if you want just x or y by itself? # # Ahh, remember, we calculated l up above, based on two other integers, m and n # you can multiple the equations above by l to get your sol'n for x and y. # # x = l * ( m1^2-n1^2 / m1^2+n1^2 ) y = l * ( 2*m1*n1 / m1^2+n1^2 ) # # you can use Algebra to rearrange all this, but basically, in the end, # we have x, y, and z as functions of m, n, m1, and n1, four separate integers. # # # possible problem: i have no idea if this works. # # and others have probably found better. xs,ys,zs=[],[],[] def sqr(x): return x*x def blueq(x,y): return sqr(x)+sqr(y) def redq(x,y): return sqr(x)-sqr(y) def greenq(x,y): return 2*x*y depth=8 for m in range(0,depth): for n in range(0,depth): for m1 in range(0,depth): for n1 in range(0,depth): if m+n==0: continue if m1+n1==0: continue blue,red,green=blueq(m,n),redq(m,n),greenq(m,n) blue1,red1,green1=blueq(m,n),redq(m,n),greenq(m,n) l = Fraction( red , blue ) z = Fraction( green , blue ) x = l * Fraction( red1, blue1 ) y = l * Fraction( green1, blue1 ) print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [y] xs += [y] ys += [x] zs += [z] zs += [-z] print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythknotmaybe.py", "copies": "1", "size": "2989", "license": "bsd-3-clause", "hash": -1462187678143397000, "line_mean": 28.0194174757, "line_max": 80, "alpha_frac": 0.5707594513, "autogenerated": false, "ratio": 2.2974634896233668, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3368222940923367, "avg_score": null, "num_lines": null }
from fractions import Fraction ########## ########## # # rational parameterization of the unit sphere # ######### ######### # for basic theory see pythsphere and pythsphere2.py # # this version differs in that it limits distance between points to a minimum def sqr(x): return x*x def blueq(p1,p2): return sqr(p2[0]-p1[0])+sqr(p2[1]-p1[1])+sqr(p2[2]-p1[2]) xs,ys,zs=[],[],[] blueqlimit=Fraction(1,8*8*8) depth=6 for m in range(0,depth): for n in range(0,depth): for m1 in range(0,depth): for n1 in range(0,depth): if m+n==0: continue if m1+n1==0: continue l = Fraction( m*m-n*n , m*m+n*n ) z = Fraction( 2*m*n , m*m+n*n ) x = l * Fraction( m1*m1-n1*n1, m1*m1+n1*n1 ) y = l * Fraction( 2*m1*n1 , m1*m1+n1*n1 ) ptOK=True for j in range(len(xs)): p1=x,y,z p2=xs[j],ys[j],zs[j] if blueq(p1,p2)<blueqlimit: ptOK=False if ptOK: print x,y,z,' sq sum: ',x*x+y*y+z*z xs += [x] ys += [y] xs += [x] ys += [y] zs += [z] zs += [-z] print len(xs) import numpy as np import matplotlib.pylab as plt fig,ax = plt.subplots(figsize=(8,8)) ax.set_ylim([-1.2,1.2]) ax.set_xlim([-1.2,1.2]) for i in range(0,len(xs)): xs[i]=xs[i]+zs[i]/4 ys[i]=ys[i]+zs[i]/4 ax.scatter(xs,ys) plt.show()
{ "repo_name": "donbright/piliko", "path": "experiment/pythsphere3.py", "copies": "1", "size": "1274", "license": "bsd-3-clause", "hash": -8968094350315552000, "line_mean": 20.593220339, "line_max": 77, "alpha_frac": 0.5635792779, "autogenerated": false, "ratio": 2.159322033898305, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7850639114937745, "avg_score": 0.07445243937211193, "num_lines": 59 }
from fractions import Fraction """ We want to determine the optimum polynomial OP(k,n) for a given degree k-1: OP(k,n) = a(0) + a(1) * n + a(2) * n^2 + ... + a(k-1) * n^(k-1) Plugging values n = 1...k into OP(k, n) must generate the series u(n): OP(k, 1) = u(1) OP(k, 2) = u(2) OP(k, 3) = u(3) ... OP(k, k) = u(k) Expanding OP we get: a(0) + a(1) * 1 + a(2) * 1^2 + ... + a(k-1) * 1^(k-1) = u(1) a(0) + a(1) * 2 + a(2) * 2^2 + ... + a(k-1) * 2^(k-1) = u(2) a(0) + a(1) * 3 + a(2) * 2^2 + ... + a(k-1) * 2^(k-1) = u(2) ... a(0) + a(1) * k + a(2) * k^2 + ... + a(k-1) * k^(k-1) = u(k) Rewriting this in matrix form, we have to solve the following matrix equation for a: M * a = u where M, a, and u are as follows: [ 1 1 1 ... 1 ] [ a(0) ] [ u(1) ] [ 1 2 4 ... 2^(k-1) ] [ a(1) ] [ u(2) ] [ 1 3 27 ... 3^(k-1) ] [ a(2) ] = [ u(3) ] ... ... [ k k^2 k^3 ... k^(k-1) ] [ a(k-1) ] [ u(k) ] Note that indexing is it bit akward because of the choice of indexing in the Euler problem: in the above equation we sometimes start with index 0 and sometimes with index 1. We solve this matrix equation by constructing the following augmented matrix of dimensions k * k+1 and then applying Gaussian elimination. For exact precision we store all numbers are fractions. Once we have OP(k,n) it is trivial to find the FIT for values n. """ def u_example(n): return n**3 def u_problem(n): return 1 - n + n**2 - n**3 + n**4 - n**5 + n**6 - n**7 + n**8 - n**9 + n**10 def make_augmented_matrix(u_function, k): matrix = [] for r in range(0, k): row = [] for c in range(0, k): row.append(Fraction((r+1) ** c)) row.append(Fraction(u_function(r+1))) matrix.append(row) return matrix def sweep_row(matrix, target_row_index, adjust_row_index, factor): nr_columns = len(matrix[0]) for c in range(0, nr_columns): matrix[target_row_index][c] -= factor * matrix[adjust_row_index][c] def gaussian_elimination(matrix): nr_rows = len(matrix) nr_columns = len(matrix[0]) # Sweep down for ari in range(0, nr_rows): for tri in range(ari+1, nr_rows): factor = Fraction(matrix[tri][ari], matrix[ari][ari]) sweep_row(matrix, tri, ari, factor) # Sweep up for ari in reversed(range(1, nr_rows)): for tri in reversed(range(0, ari)): factor = Fraction(matrix[tri][ari], matrix[ari][ari]) sweep_row(matrix, tri, ari, factor) # Normalize for ri in range(0, nr_rows): matrix[ri][nr_rows] /= matrix[ri][ri] matrix[ri][ri] = Fraction(1, 1) # Return solution solution = [] for ri in range(0, nr_rows): solution.append(matrix[ri][nr_columns-1]) return solution def compute_optimum_polynomial_coeficients(u_function, k): matrix = make_augmented_matrix(u_function, k) coeficients = gaussian_elimination(matrix) return coeficients def optimum_polynomial(coeficients, n): k = len(coeficients) fn = Fraction(n) result = Fraction(0) for i in range(0, k): fi = Fraction(i) result += coeficients[i] * (fn ** fi) return result def first_incorrect_term(u_function, k): coeficients = compute_optimum_polynomial_coeficients(u_function, k) n = k + 1 while True: potentially_incorrect_term = optimum_polynomial(coeficients, n) if potentially_incorrect_term != u_function(n): return potentially_incorrect_term n += 1 def sum_of_first_incorrect_terms(u_function, u_degree): sum = 0 for k in range(1, u_degree+1): sum += first_incorrect_term(u_function, k) return sum assert(sum_of_first_incorrect_terms(u_example, 3) == 74) print(sum_of_first_incorrect_terms(u_problem, 10))
{ "repo_name": "brunorijsman/euler-problems-python", "path": "euler/problem101.py", "copies": "1", "size": "4006", "license": "bsd-2-clause", "hash": -7481112862446540000, "line_mean": 31.048, "line_max": 86, "alpha_frac": 0.5539191213, "autogenerated": false, "ratio": 2.793584379358438, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8829292893604557, "avg_score": 0.0036421214107761183, "num_lines": 125 }
from fractions import Fraction ''' Some builtin functions for bach's runtime bach_add/bach_sub etc correspond to +/-... see bach_ast for mapping(bach converts all those labels into valid python labels) Most of those implementations don't feel pythonic, and that's intentional Those functions would be used frequently, so we try to write them more efficiently without too much magic ''' def symbol(): class BachSymbol(object): def __init__(self, value): self.value = value def __repr__(self): return "'%s" % self.value def __str__(self): return repr(self) def car(list): return list[0] def cdr(list): return list[1:] def cons(head, tail): return [head] + tail def bach_add(*values): return sum(values) def bach_sub(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for -") elif len(values) == 1: return -values[0] else: value = values[0] for n in values[1:]: value -= n return value def display(value): print(value) def string(*values): result = '' for value in values: result += value return result def bach_eq(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for =") first = values[0] for value in values[1:]: if value != first: return False return True def bach_neq(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for !=") first = values[0] for value in values[1:]: if value != first: return True return False def bach_gt(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for >") current = values[0] for value in values[1:]: if current <= value: return False current = value return True def bach_lt(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for =") current = values[0] for value in values[1:]: if current >= value: return False current = value return True def bach_mult(*values): value = 1 for n in values: value *= n return value def bach_div(*values): if len(values) == 0: raise BachArgumentError("expected 1 or more got 0 args for /") elif len(values) == 1: if isinstance(values[0], (int, Fraction)): return Fraction(1, values[0]) else: return 1 / values[0] else: value = values[0] for d in values[1:]: if isinstance(value, (int, Fraction)) and isinstance(d, (int, Fraction)): return Fraction(value, d) else: return value / d return BachSymbol __all__ = ['car', 'cdr', 'cons', 'bach_add', 'bach_sub', 'bach_mult', 'bach_div', 'display', 'symbol'] # e? -> is_e # + bach_add # - bach_sub # * bach_mult # / bach_div # > bach_gt # < bach_lt # = bach_eq # >= bach_gte # != bach_ne # <= bach_lte # and bach_and
{ "repo_name": "alehander42/bach", "path": "bach/bach_stl/functions.py", "copies": "1", "size": "3457", "license": "mit", "hash": -1112258121155309400, "line_mean": 24.992481203, "line_max": 102, "alpha_frac": 0.5253109633, "autogenerated": false, "ratio": 4.019767441860465, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5045078405160466, "avg_score": null, "num_lines": null }
from fractions import Fraction # polygon intersection.. doesnt work. # assume - input polys are clockwise-ordered set of 3 or more points # assume - points are using rational numbers for coordinates (Fractions) # assume - polygons are simple # design - dont use angles # point = [x,y] # line = [a,b,c] where ax+by+c = 0 # vector = [x,y] # triangle = [point,point,point] # polygon = [point,point,...] # notes # http://math.stackexchange.com/questions/74307/two-2d-vector-angle-clockwise-predicate # http://stackoverflow.com/questions/243945/calculating-a-2d-vectors-cross-product # https://www.youtube.com/watch?v=6XghF70fqkY&list=PL01A21B9E302D50C1 import sys # -> determinant of 2x2 matrix of 2 2-d vectors # -> also cross product if you add a z=0 and return magnitude # -> also area of paralellogram formed by v1, v2 # -> also is the 'multiple' by which all Grossman bi-vectors are related def determinant( v1, v2 ): x1,y1,x2,y2 = v1[0],v1[1],v2[0],v2[1] return x1*y2-x2*y1 def vector( p0, p1 ): return [ p1[0] - p0[0], p1[1] - p0[1] ] def line( p0, p1 ): v = vector( p0, p1 ) a,b,c = v[1], v[0], crosshack( p0, p1 ) return [a,b,c] def meet( l0, l1 ): a,b,c=[l0[0],l1[0]], [l0[1],l1[1]], [l0[2],l1[2]] x = Fraction( crosshack(b,c), crosshack(a,b) ) y = Fraction( crosshack(a,c), crosshack(b,a) ) return x,y def triangle_intersection( t1, t2 ): for p1 in t1: for p2 in t2: lines += line( p1, p2 ) vectors += vector( p1, p2 ) for line1 in lines: for line2 in lines: meets += meet( line1, line2 ) for point in meets: ok = True for v in vectors: if not is_right_turn( v[0],v[1],point ): ok = False if ok: newpoints += [point] if not is_right_turn(newpoints[0],newpoints[1],newpoints[2]): newpoints = [newpoints[1],newpoints[0],newpoints[2]] return newpoints def is_inside_triangle( tri, point ): p0,p1,p2 = tri[0],tri[1],tri[2] if not is_right_turn( p0, p1, point ): return False if not is_right_turn( p1, p2, point ): return False if not is_right_turn( p2, p0, point ): return False return True def is_right_turn( p0, p1, p2 ): v1,v2=vector(p0,p1),vector(p1,p2) return crosshack( v1, v2 ) < 0 def triangle_inside_pgon( tri, pgon ): for point in pgon: if is_inside_triangle(tri,point) and not point in tri: return False return True def find_ear( pgon ): n = len(pgon) for i in range( n ): p0,p1,p2 = pgon[i%n],pgon[(i+1)%n],pgon[(i+2)%n] print 'find ear test',p0,p1,p2 if is_right_turn( p0, p1, p2 ): ok = True for point in pgon: #print 'subtest',point if is_inside_triangle( [p0,p1,p2], point ): ok=False else: print 'not right turn' ok=False if ok: return [p0,p1,p2] def chop_ear( ear_tri, pgon ): newpgon = [] for p in pgon: if p==ear_tri[1]: pass else: newpgon += [p] return newpgon def tessellate( pgon, triangles ): print 'tess. pgon: ' ,pgon, 'triangles:', triangles p0,p1,p2 = pgon[0],pgon[1],pgon[2] if len(pgon)>3: ear_tri = find_ear( pgon ) print 'found ear',ear_tri newpgon = chop_ear( ear_tri, pgon ) print 'choppd pgon: ',newpgon triangles += [ ear_tri ] return tessellate( newpgon, triangles ) else: print 'at final triangle. recursion ending' return [[p0,p1,p2]] + triangles def detessellate( triangles ): pgon = [] for t1 in triangles: for t2 in triangles: if t1!=t2: print 'neq' return pgon def pgon_intersection( pgon1, pgon2 ): global f triangles = [] triangles1 = tessellate( pgon1, [] ) #triangles2 = tessellate( pgon2, [] ) sys.exit() print 'tessellated' print 'group1:', triangles1 print 'group2:', triangles2 for t1 in triangles1: for t2 in triangles2: triangles += triangle_intersection( t1, t2 ) return detessellate( triangles ) def svg(pointlist): picsize,margin,maxcoord=400,20,float(max(max(pointlist))) def trans( coord ): return str( (coord / maxcoord) * (picsize * 0.90) + margin ) s= '<svg xmlns="http://www.w3.org/2000/svg" width="%i" height="%i">\n' % ( picsize, picsize ) s+= '<path d="M ' + trans( pointlist[0][0] ) + ' ' + trans( pointlist[0][1] ) for p in pointlist: s+= 'L ' + trans( p[0] ) + ' ' + trans( p[1] ) s+= ' Z " stroke="black" fill="none"/>\n </svg>\n' return s pgon1=[[0,0],[0,4],[3,4],[5,10],[10,10],[3,0]] pgon2=[[1,1],[0,5],[4,0]] newpgon = pgon_intersection( pgon1, pgon2 ) print pgon1, '\n', pgon2, '\n', newpgon
{ "repo_name": "donbright/piliko", "path": "pmeet.py", "copies": "1", "size": "4347", "license": "bsd-3-clause", "hash": 6458302575557407000, "line_mean": 27.4117647059, "line_max": 94, "alpha_frac": 0.6461927766, "autogenerated": false, "ratio": 2.3637846655791193, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8146000338877883, "avg_score": 0.07279542066024726, "num_lines": 153 }