repo_name
stringlengths
7
65
path
stringlengths
5
185
copies
stringlengths
1
4
size
stringlengths
4
6
content
stringlengths
977
990k
license
stringclasses
14 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.4
line_max
int64
31
999
alpha_frac
float64
0.25
0.95
ratio
float64
1.5
7.84
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
roxma/nvim-completion-manager
pythonx/cm_sources/cm_bufkeyword.py
1
2552
#!/usr/bin/env python # -*- coding: utf-8 -*- # For debugging # NVIM_PYTHON_LOG_FILE=nvim.log NVIM_PYTHON_LOG_LEVEL=INFO nvim from cm import register_source, getLogger, Base register_source(name='cm-bufkeyword', priority=5, abbreviation='Key', events=['InsertEnter', 'BufEnter'],) import re import cm_default logger = getLogger(__name__) class Source(Base): def __init__(self,nvim): super(Source,self).__init__(nvim) self._words = set() self._last_ctx = None self.refresh_keyword(nvim.eval('cm#context()')) def cm_event(self,event,ctx,*args): if self._last_ctx and (self._last_ctx['changedtick'] == ctx['changedtick']): return self._last_ctx = ctx self.refresh_keyword(ctx) def refresh_keyword(self,ctx,all=True,expand=50): word_pattern = cm_default.word_pattern(ctx) compiled = re.compile(word_pattern) logger.info('refreshing_keyword, word_pattern [%s]', word_pattern) buffer = self.nvim.current.buffer if all: self._words = set() begin = 0 end = len(buffer) else: begin = max(ctx['lnum']-50,0) end = min(ctx['lnum']+50,len(buffer)) logger.info('keyword refresh begin, current count: %s', len(self._words)) cur_lnum = ctx['lnum'] cur_col = ctx['col'] step = 1000 for num in range(begin,end,step): lines = buffer[num:num+step] # convert 0 base to 1 base lnum = num+1 for line in lines: if lnum == cur_lnum: for word in compiled.finditer(line): span = word.span() # filter-out the word at current cursor if (cur_col>=span[0]+1) and (cur_col-1<=span[1]+1): continue self._words.add(word.group()) else: for word in compiled.finditer(line): self._words.add(word.group()) lnum += 1 logger.info('keyword refresh complete, count: %s', len(self._words)) def cm_refresh(self,info,ctx): # incremental refresh self.refresh_keyword(ctx,False) matches = (dict(word=word,icase=1) for word in self._words) matches = self.matcher.process(info, ctx, ctx['startcol'], matches) self.complete(info, ctx, ctx['startcol'], matches)
mit
cb023207f1a1d964347be4a473eec1ba
30.506173
84
0.534875
3.872534
false
false
false
false
roxma/nvim-completion-manager
pythonx/cm_sources/cm_gocode.py
1
4649
# -*- coding: utf-8 -*- # For debugging, use this command to start neovim: # # NVIM_PYTHON_LOG_FILE=nvim.log NVIM_PYTHON_LOG_LEVEL=INFO nvim # # # Please register source before executing any other code, this allow cm_core to # read basic information about the source without loading the whole module, and # modules required by this module from cm import register_source, getLogger, Base register_source(name='cm-gocode', priority=9, abbreviation='Go', word_pattern=r'[\w/]+', early_cache=1, scoping=True, scopes=['go'], cm_refresh_patterns=[r'\.'],) import re import subprocess import json logger = getLogger(__name__) class Source(Base): def __init__(self,nvim): super(Source,self).__init__(nvim) self._checked = False try: from distutils.spawn import find_executable # echoe does not work here if not find_executable("gocode"): self.message('error', "Can't find [gocode] binary. Please install gocode http://github.com/nsf/gocode") except: pass def get_pos(self, lnum , col, src): lines = src.split(b'\n') pos = 0 for i in range(lnum-1): pos += len(lines[i])+1 pos += col-1 return pos def cm_refresh(self,info,ctx,*args): # Note: # # If you'r implementing you own source, and you want to get the content # of the file, Please use `cm.get_src()` instead of # `"\n".join(self._nvim.current.buffer[:])` src = self.get_src(ctx).encode('utf-8') filepath = ctx['filepath'] # convert lnum, col to offset offset = self.get_pos(ctx['lnum'],ctx['col'],src) # invoke gocode proc = subprocess.Popen(args=['gocode','-f','json','autocomplete', filepath,'%s' % offset], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) result, errs = proc.communicate(src,timeout=30) # result: [1, [{"class": "func", "name": "Print", "type": "func(a ...interface{}) (n int, err error)"}, ...]] result = json.loads(result.decode('utf-8')) logger.info("result %s", result) if not result: return completions = result[1] startcol = ctx['col'] - result[0] if startcol==ctx['col'] and re.match(r'\w', ctx['typed'][-1]): # workaround gocode bug when completion is triggered in a golang # string return if not completions: return matches = [] for complete in completions: # { # "class": "func", # "name": "Fprintln", # "type": "func(w !io!io.Writer, a ...interface{}) (n int, err error)" # }, item = dict(word=complete['name'], icase=1, dup=1, menu=complete.get('type',''), # info=complete.get('doc',''), ) matches.append(item) # snippet support if 'class' in complete and complete['class']=='func' and 'type' in complete: m = re.search(r'func\((.*?)\)',complete['type']) if not m: continue params = m.group(1) params = params.split(',') logger.info('snippet params: %s',params) snip_params = [] num = 1 optional = '' for param in params: param = param.strip() if not param: logger.error("failed to process snippet for item: %s, param: %s", item, param) break name = param.split(' ')[0] if param.find('...')>=0: # optional args if num>1: optional += '${%s:, %s...}' % (num, name) else: optional += '${%s:%s...}' % (num, name) break snip_params.append("${%s:%s}" % (num,name)) num += 1 item['snippet'] = item['word'] + '(' + ", ".join(snip_params) + optional + ')${0}' logger.info('startcol %s, matches %s', startcol, matches) self.complete(info, ctx, startcol, matches)
mit
b9617f908cb3946b6f5e21c232ab81d9
32.446043
119
0.473435
4.214869
false
false
false
false
openatx/uiautomator2
uiautomator2/version.py
1
4900
# coding: utf-8 # import pkg_resources try: __version__ = pkg_resources.get_distribution("uiautomator2").version except pkg_resources.DistributionNotFound: __version__ = "unknown" # See ChangeLog for details __apk_version__ = '2.3.3' # 2.3.3 make float windows smaller # 2.3.2 merge pull requests # require atx-agent>=0.10.0 # 2.3.1 support minicapagent, rotationagent, minitouchagent # 2.2.1 fix click bottom(infinitly display) not working bug # 2.2.0 add MinitouchAgent instead of /data/local/tmp/minitouch # 2.1.1 add show floatWindow support(pm grant, still have no idea), add TC_TREND analysis # 2.0.5 add ToastActivity to show toast or just launch and quit # 2.0.4 fix floatingWindow crash on Sumsung Android 9 # 2.0.3 use android.app.Service instead of android.app.intentService to simpfy logic # 2.0.2 fix error: AndroidQ Service must be explicit # 2.0.1 fix AndroidQ support # 2.0.0 remove runWatchersOnWndowsChange, add setToastListener(bool), add floatWindow # 1.1.7 fix dumpHierarchy XML charactor error # 1.1.6 fix android P support # 1.1.5 waitForExists use UiObject2 method first then fallback to UiObject.waitForExists # 1.1.4 add ADB_EDITOR_CODE broadcast support, fix bug (toast捕获导致app闪退) # 1.1.3 use thread to make watchers.watched faster, try to fix input method type multi # 1.1.2 fix count error when have child && sync watched, to prevent watchers.remove error # 1.1.1 support toast capture # 1.1.0 update uiautomator-v18:2.1.2 -> uiautomator-v18:2.1.3 (This version fixed setWaitIdleTimeout not working bug) # 1.0.14 catch NullException, add gps mock support # 1.0.13 whatsinput suppoort, but not very well # 1.0.12 add toast support # 1.0.11 add auto install support # 1.0.10 fix service not started bug # 1.0.9 fix apk version code and version name # ERR: 1.0.8 bad version number. show ip on notification # ERR: 1.0.7 bad version number. new input method, some bug fix __jar_version__ = 'v0.1.6' # no useless for now. # v0.1.6 first release version __atx_agent_version__ = '0.10.0' # 0.10.0 remove tunnel code, use androidx.test.runner # 0.9.6 fix security reason for remote control device # 0.9.5 log support rotate, prevent log too large # 0.9.4 test travis push to qiniu-cdn # 0.9.3 fix atx-agent version output too many output # 0.9.2 fix when /sdcard/atx-agent.log can't create, atx-agent can't start error # 0.9.1 update /minicap to use apkagent and minicap # 0.9.0 add /minicap/broadcast api, add service("apkagent") # 0.8.4 use minicap when sdk less than Android Q # 0.8.3 use minitouchagent instead of /data/local/tmp/minitouch # 0.8.2 change am instrument maxRetry from 3 to 1 # 0.8.1 fix --stop can not stop atx-agent error, fix --help format error # 0.8.0 add /newCommandTimeout api, ref: appium-newCommandTimeout # 0.7.4 add /finfo/{filepath:.*} api # 0.7.3 add uiautomator-1.0 support # 0.7.2 fix stop already stopped uiautomator return status 500 error # 0.7.1 fix UIAutomation not connected error. # 0.7.0 add webview support, kill uiautomator if no activity in 3 minutes # 0.6.2 fix app_info fd leak error, update androidbinary to fix parse apk manifest err # 0.6.1 make dump_hierarchy more robust, add cpu,mem collect # 0.6.0 add /dump/hierarchy (works fine even if uiautomator is down) # 0.5.5 add minitouch reset, /screenshot support download param, fix dns error # 0.5.4 upgrade atx-agent to fix apk parse mainActivity of com.tmall.wireless # 0.5.3 try to fix panic in heartbeat # 0.5.2 fix /session/${pkgname} launch timeout too short error(before was 10s) # 0.5.1 bad tag, deprecated # 0.5.0 add /packages/${pkgname}/<info|icon> api # 0.4.9 update for go1.11 # 0.4.8 add /wlan/ip and /packages REST API for package install # 0.4.6 fix download dns resolve error (sometimes) # 0.4.5 add http log, change atx-agent -d into atx-agent server -d # 0.4.4 this version is gone # 0.4.3 ignore sigint to prevent atx-agent quit # 0.4.2 hot fix, close upgrade-self # 0.4.1 fix app-download time.Timer panic error, use safe-time.Timer instead. # 0.4.0 add go-daemon lib. use safe-time.Timer to prevent panic error. this will make it run longer # 0.3.6 support upload zip and unzip, fix minicap rotation error when atx-agent is killed -9 # 0.3.5 hot fix for session # 0.3.4 fix session() sometimes can not get mainActivity error # 0.3.3 /shell support timeout # 0.3.2 fix dns resolve error when network changes # 0.3.0 use github.com/codeskyblue/heartbeat library instead of websocket, add /whatsinput # 0.2.1 support occupy /minicap connection # 0.2.0 add session support # 0.1.8 fix screenshot always the same image. (BUG in 0.1.7), add /shell/stream add timeout for /shell # 0.1.7 fix dns resolve error in /install # 0.1.6 change download logic. auto fix orientation # 0.1.5 add singlefight for minicap and minitouch, proxy dial-timeout change 30 to 10 # 0.1.4 phone remote control # 0.1.2 /download support # 0.1.1 minicap buildin
mit
b94c4cccaf7169d71a210b54d38d39c8
49.895833
117
0.744781
2.955838
false
false
false
false
tilezen/tilequeue
tilequeue/metro_extract.py
2
1509
from json import load class MetroExtractCity(object): def __init__(self, region, city, bounds): self.region = region self.city = city self.bounds = bounds def __repr__(self): return 'MetroExtractCity(%s, %s, %s)' % \ (self.region, self.city, self.bounds) class MetroExtractParseError(Exception): def __init__(self, cause): self.cause = cause def __repr__(self): return 'MetroExtractParseError(%s: %s)' % ( self.cause.__class__.__name__, str(self.cause)) def parse_metro_extract(metro_extract_fp): json_data = load(metro_extract_fp) metros = [] try: regions = json_data[u'regions'] for region_name, region_data in regions.iteritems(): cities = region_data[u'cities'] for city_name, city_data in cities.iteritems(): city_json_bounds = city_data[u'bbox'] minx = float(city_json_bounds[u'left']) miny = float(city_json_bounds[u'bottom']) maxx = float(city_json_bounds[u'right']) maxy = float(city_json_bounds[u'top']) city_bounds = (minx, miny, maxx, maxy) metro = MetroExtractCity(region_name, city_name, city_bounds) metros.append(metro) except (KeyError, ValueError), e: raise MetroExtractParseError(e) return metros def city_bounds(metro_extract_cities): return [city.bounds for city in metro_extract_cities]
mit
862a7ba0a4300ab95cd1257a325e5c15
30.4375
77
0.58383
3.584323
false
false
false
false
tilezen/tilequeue
tests/test_store.py
1
8377
""" Tests for `tilequeue.store`. """ import unittest class TestTileDirectory(unittest.TestCase): def setUp(self): import tempfile self.dir_path = tempfile.mkdtemp() def tearDown(self): import shutil shutil.rmtree(self.dir_path) def test_write_tile(self): from ModestMaps.Core import Coordinate from tilequeue import format from tilequeue import store import os # Verify that the `TileDirectory` directory gets created. tile_dir = store.TileDirectory(self.dir_path) self.assertTrue( os.path.isdir(self.dir_path), 'The directory path passed to `TileDirectory()` wasn\'t created ' 'during initialization') # Verify that tile data is written to the right files. tiles_to_write = [ ('tile1', (1, 2, 3), 'json'), ('tile2', (8, 4, 9), 'mvt'), ('tile3', (2, 6, 0), 'vtm'), ('tile4', (2, 6, 1), 'topojson'), ] for tile_data, (z, c, r), fmt in tiles_to_write: coords_obj = Coordinate(row=r, column=c, zoom=z) format_obj = format.OutputFormat(fmt, fmt, None, None, None, False) tile_dir.write_tile(tile_data, coords_obj, format_obj) expected_filename = '{0}/{1}/{2}.{3}'.format( coords_obj.zoom, coords_obj.column, coords_obj.row, fmt) expected_path = os.path.join(self.dir_path, expected_filename) self.assertTrue( os.path.isfile(expected_path), 'Tile data must not have been written to the right location, ' 'because the expected file path does not exist') with open(expected_path) as tile_fp: self.assertEqual( tile_fp.read(), tile_data, 'Tile data written to file does not match the input data') os.remove(expected_path) class TestStoreKey(unittest.TestCase): def test_example_coord(self): from tilequeue.tile import deserialize_coord from tilequeue.format import json_format from tilequeue.store import KeyFormatType from tilequeue.store import S3TileKeyGenerator coord = deserialize_coord('8/72/105') prefix = '20160121' tile_key_gen = S3TileKeyGenerator( key_format_type=KeyFormatType.hash_prefix) tile_key = tile_key_gen(prefix, coord, json_format.extension) self.assertEqual(tile_key, 'b57e9/20160121/8/72/105.json') class WriteTileIfChangedTest(unittest.TestCase): def setUp(self): self._in = None self._out = None self.store = type( 'test-store', (), dict(read_tile=self._read_tile, write_tile=self._write_tile) ) def _read_tile(self, coord, format): return self._in def _write_tile(self, tile_data, coord, format): self._out = tile_data def _call_fut(self, tile_data): from tilequeue.store import write_tile_if_changed coord = format = None result = write_tile_if_changed(self.store, tile_data, coord, format) return result def test_no_data(self): did_write = self._call_fut('data') self.assertTrue(did_write) self.assertEquals('data', self._out) def test_diff_data(self): self._in = 'different data' did_write = self._call_fut('data') self.assertTrue(did_write) self.assertEquals('data', self._out) def test_same_data(self): self._in = 'data' did_write = self._call_fut('data') self.assertFalse(did_write) self.assertIsNone(self._out) class S3Test(unittest.TestCase): def _make_stub_s3_client(self): class stub_s3_client(object): def put_object(self, **props): self.put_props = props return stub_s3_client() def test_tags(self): from tilequeue.store import KeyFormatType from tilequeue.store import S3 from tilequeue.store import S3TileKeyGenerator s3_client = self._make_stub_s3_client() tags = None tile_key_gen = S3TileKeyGenerator( key_format_type=KeyFormatType.hash_prefix) store = S3(s3_client, 'bucket', 'prefix', False, 60, None, 'public-read', tags, tile_key_gen) tile_data = 'data' from tilequeue.tile import deserialize_coord coord = deserialize_coord('14/1/2') from tilequeue.format import mvt_format store.write_tile(tile_data, coord, mvt_format) self.assertIsNone(store.s3_client.put_props.get('Tagging')) store.tags = dict(prefix='foo', run_id='bar') store.write_tile(tile_data, coord, mvt_format) self.assertEquals('prefix=foo&run_id=bar', store.s3_client.put_props.get('Tagging')) class _LogicalLog(object): """ A logical time description of when things happened. Used for recording that one write to S3 happened before or after another. """ def __init__(self): self.time = 0 self.items = [] def __call__(self, *args): self.items.append((self.time,) + args) self.time += 1 class _LoggingStore(object): """ A mock store which doesn't store tiles, only logs calls to a logical log. """ def __init__(self, name, log): self.name = name self.log = log def write_tile(self, tile_data, coord, format): self.log(self.name, 'write_tile', tile_data, coord, format) def read_tile(self, coord, format): self.log(self.name, 'read_tile', coord, format) return '' def delete_tiles(self, coords, format): self.log(self.name, 'delete_tiles', coords, format) return 0 def list_tiles(self, format): self.log(self.name, 'list_tiles', format) return iter(()) class MultiStoreTest(unittest.TestCase): def test_multi_write(self): from tilequeue.format import json_format from tilequeue.store import MultiStore from ModestMaps.Core import Coordinate coord = Coordinate(zoom=0, column=0, row=0) log = _LogicalLog() s0 = _LoggingStore('s0', log) s1 = _LoggingStore('s1', log) m = MultiStore([s0, s1]) m.write_tile('foo', coord, json_format) # multi store should write to both stores. self.assertEqual( log.items, [ (0, 's0', 'write_tile', 'foo', coord, json_format), (1, 's1', 'write_tile', 'foo', coord, json_format), ]) def test_multi_read(self): from tilequeue.format import json_format from tilequeue.store import MultiStore from ModestMaps.Core import Coordinate coord = Coordinate(zoom=0, column=0, row=0) log = _LogicalLog() s0 = _LoggingStore('s0', log) s1 = _LoggingStore('s1', log) m = MultiStore([s0, s1]) m.read_tile(coord, json_format) # multi store should only read from final store. self.assertEqual( log.items, [ (0, 's1', 'read_tile', coord, json_format), ]) def test_multi_cfg_list(self): from tilequeue.store import _make_s3_store calls = [] def _construct(name): calls.append(name) # check that a list results in multiple calls to construct a store. _make_s3_store(['foo', 'bar', 'baz'], _construct) self.assertEqual(calls, ['foo', 'bar', 'baz']) def test_multi_cfg_singleton(self): from tilequeue.store import _make_s3_store calls = [] def _construct(name): calls.append(name) # check that a single-item list results in a single call to construct # a store. _make_s3_store(['foo'], _construct) self.assertEqual(calls, ['foo']) def test_multi_cfg_string(self): from tilequeue.store import _make_s3_store calls = [] def _construct(name): calls.append(name) # check that a single string results in a single call to construct, # and isn't iterated over as single characters. _make_s3_store('foo', _construct) self.assertEqual(calls, ['foo'])
mit
d3e821c9706c915bf7ceb998c566c626
30.257463
79
0.584338
3.775124
false
true
false
false
fcurella/django-recommends
recommends/tasks.py
2
2122
from celery.task import task, periodic_task from celery.schedules import crontab from .utils import filelock from .settings import RECOMMENDS_TASK_RUN, RECOMMENDS_TASK_CRONTAB, RECOMMENDS_TASK_EXPIRES def recommends_precompute(): results = [] from .providers import recommendation_registry # I know this is weird, but it's faster (tested on CPyhton 2.6.5) def _precompute(provider_instance): results.append(provider_instance.precompute()) if recommendation_registry.storage.can_lock: locked = recommendation_registry.storage.get_lock() if locked: try: [_precompute(provider_instance) for provider_instance in recommendation_registry.get_vote_providers()] finally: recommendation_registry.storage.release_lock() else: with filelock('recommends_precompute.lock'): [_precompute(provider_instance) for provider_instance in recommendation_registry.get_vote_providers()] return results if RECOMMENDS_TASK_RUN: @periodic_task(name='recommends_precompute', run_every=crontab(**RECOMMENDS_TASK_CRONTAB), expires=RECOMMENDS_TASK_EXPIRES) def _recommends_precompute(): recommends_precompute() @task(name='remove_suggestions') def remove_suggestions(rated_model, object_id): from django.apps import apps from recommends.providers import recommendation_registry ObjectClass = apps.get_model(*rated_model.split('.')) provider_instance = recommendation_registry.get_provider_for_content( ObjectClass) obj = ObjectClass.objects.get(pk=object_id) provider_instance.storage.remove_recommendations(obj) @task(name='remove_similarities') def remove_similarities(rated_model, object_id): from django.apps import apps from recommends.providers import recommendation_registry ObjectClass = apps.get_model(*rated_model.split('.')) provider_instance = recommendation_registry.get_provider_for_content( ObjectClass) obj = ObjectClass.objects.get(pk=object_id) provider_instance.storage.remove_similarities(obj)
mit
8836d78882245a77c067602a3b7508f7
34.366667
127
0.720547
3.837251
false
false
false
false
jsvine/pdfplumber
pdfplumber/utils.py
1
28534
import itertools import re import string from collections.abc import Hashable, Sequence from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Callable, Dict, Generator, Iterable, List, Match, Optional, Pattern, Tuple, TypeVar, Union, ) from pdfminer.pdftypes import PDFObjRef from pdfminer.psparser import PSLiteral from pdfminer.utils import PDFDocEncoding from ._typing import T_bbox, T_num, T_obj, T_obj_iter, T_obj_list, T_seq if TYPE_CHECKING: # pragma: nocover from pandas.core.frame import DataFrame DEFAULT_X_TOLERANCE = 3 DEFAULT_Y_TOLERANCE = 3 DEFAULT_X_DENSITY = 7.25 DEFAULT_Y_DENSITY = 13 def cluster_list(xs: List[T_num], tolerance: T_num = 0) -> List[List[T_num]]: if tolerance == 0: return [[x] for x in sorted(xs)] if len(xs) < 2: return [[x] for x in sorted(xs)] groups = [] xs = list(sorted(xs)) current_group = [xs[0]] last = xs[0] for x in xs[1:]: if x <= (last + tolerance): current_group.append(x) else: groups.append(current_group) current_group = [x] last = x groups.append(current_group) return groups def make_cluster_dict(values: Iterable[T_num], tolerance: T_num) -> Dict[T_num, int]: clusters = cluster_list(list(set(values)), tolerance) nested_tuples = [ [(val, i) for val in value_cluster] for i, value_cluster in enumerate(clusters) ] return dict(itertools.chain(*nested_tuples)) R = TypeVar("R") def cluster_objects( xs: List[R], key_fn: Union[Hashable, Callable[[R], T_num]], tolerance: T_num ) -> List[List[R]]: if not callable(key_fn): key_fn = itemgetter(key_fn) values = map(key_fn, xs) cluster_dict = make_cluster_dict(values, tolerance) get_0, get_1 = itemgetter(0), itemgetter(1) cluster_tuples = sorted(((x, cluster_dict.get(key_fn(x))) for x in xs), key=get_1) grouped = itertools.groupby(cluster_tuples, key=get_1) return [list(map(get_0, v)) for k, v in grouped] def decode_text(s: Union[bytes, str]) -> str: """ Decodes a PDFDocEncoding string to Unicode. Adds py3 compatibility to pdfminer's version. """ if isinstance(s, bytes) and s.startswith(b"\xfe\xff"): return str(s[2:], "utf-16be", "ignore") ords = (ord(c) if isinstance(c, str) else c for c in s) return "".join(PDFDocEncoding[o] for o in ords) def resolve_and_decode(obj: Any) -> Any: """Recursively resolve the metadata values.""" if hasattr(obj, "resolve"): obj = obj.resolve() if isinstance(obj, list): return list(map(resolve_and_decode, obj)) elif isinstance(obj, PSLiteral): return decode_text(obj.name) elif isinstance(obj, (str, bytes)): return decode_text(obj) elif isinstance(obj, dict): for k, v in obj.items(): obj[k] = resolve_and_decode(v) return obj return obj def decode_psl_list(_list: List[Union[PSLiteral, str]]) -> List[str]: return [ decode_text(value.name) if isinstance(value, PSLiteral) else value for value in _list ] def resolve(x: Any) -> Any: if isinstance(x, PDFObjRef): return x.resolve() else: return x def get_dict_type(d: Any) -> Optional[str]: if not isinstance(d, dict): return None t = d.get("Type") if isinstance(t, PSLiteral): return decode_text(t.name) else: return t def resolve_all(x: Any) -> Any: """ Recursively resolves the given object and all the internals. """ if isinstance(x, PDFObjRef): resolved = x.resolve() # Avoid infinite recursion if get_dict_type(resolved) == "Page": return x return resolve_all(resolved) elif isinstance(x, (list, tuple)): return type(x)(resolve_all(v) for v in x) elif isinstance(x, dict): exceptions = ["Parent"] if get_dict_type(x) == "Annot" else [] return {k: v if k in exceptions else resolve_all(v) for k, v in x.items()} else: return x def to_list(collection: Union[T_seq[Any], "DataFrame"]) -> List[Any]: if isinstance(collection, list): return collection elif isinstance(collection, Sequence): return list(collection) elif hasattr(collection, "to_dict"): res: List[Dict[Union[str, int], Any]] = collection.to_dict( "records" ) # pragma: nocover return res else: return list(collection) def dedupe_chars(chars: T_obj_list, tolerance: T_num = 1) -> T_obj_list: """ Removes duplicate chars — those sharing the same text, fontname, size, and positioning (within `tolerance`) as other characters in the set. """ key = itemgetter("fontname", "size", "upright", "text") pos_key = itemgetter("doctop", "x0") def yield_unique_chars(chars: T_obj_list) -> Generator[T_obj, None, None]: sorted_chars = sorted(chars, key=key) for grp, grp_chars in itertools.groupby(sorted_chars, key=key): for y_cluster in cluster_objects( list(grp_chars), itemgetter("doctop"), tolerance ): for x_cluster in cluster_objects( y_cluster, itemgetter("x0"), tolerance ): yield sorted(x_cluster, key=pos_key)[0] deduped = yield_unique_chars(chars) return sorted(deduped, key=chars.index) def objects_to_rect(objects: T_obj_list) -> Dict[str, T_num]: return { "x0": min(map(itemgetter("x0"), objects)), "x1": max(map(itemgetter("x1"), objects)), "top": min(map(itemgetter("top"), objects)), "bottom": max(map(itemgetter("bottom"), objects)), } def objects_to_bbox(objects: T_obj_list) -> T_bbox: return ( min(map(itemgetter("x0"), objects)), min(map(itemgetter("top"), objects)), max(map(itemgetter("x1"), objects)), max(map(itemgetter("bottom"), objects)), ) bbox_getter = itemgetter("x0", "top", "x1", "bottom") def obj_to_bbox(obj: T_obj) -> T_bbox: return bbox_getter(obj) def bbox_to_rect(bbox: T_bbox) -> Dict[str, T_num]: return {"x0": bbox[0], "top": bbox[1], "x1": bbox[2], "bottom": bbox[3]} def merge_bboxes(bboxes: List[T_bbox]) -> T_bbox: """ Given a set of bounding boxes, return the smallest bounding box that contains them all. """ return ( min(map(itemgetter(0), bboxes)), min(map(itemgetter(1), bboxes)), max(map(itemgetter(2), bboxes)), max(map(itemgetter(3), bboxes)), ) class WordExtractor: def __init__( self, x_tolerance: T_num = DEFAULT_X_TOLERANCE, y_tolerance: T_num = DEFAULT_Y_TOLERANCE, keep_blank_chars: bool = False, use_text_flow: bool = False, horizontal_ltr: bool = True, # Should words be read left-to-right? vertical_ttb: bool = True, # Should vertical words be read top-to-bottom? extra_attrs: Optional[List[str]] = None, split_at_punctuation: Union[bool, str] = False, ): self.x_tolerance = x_tolerance self.y_tolerance = y_tolerance self.keep_blank_chars = keep_blank_chars self.use_text_flow = use_text_flow self.horizontal_ltr = horizontal_ltr self.vertical_ttb = vertical_ttb self.extra_attrs = [] if extra_attrs is None else extra_attrs # Note: string.punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' self.split_at_punctuation = ( string.punctuation if split_at_punctuation is True else (split_at_punctuation or "") ) def merge_chars(self, ordered_chars: T_obj_list) -> T_obj: x0, top, x1, bottom = objects_to_bbox(ordered_chars) doctop_adj = ordered_chars[0]["doctop"] - ordered_chars[0]["top"] upright = ordered_chars[0]["upright"] direction = 1 if (self.horizontal_ltr if upright else self.vertical_ttb) else -1 word = { "text": "".join(map(itemgetter("text"), ordered_chars)), "x0": x0, "x1": x1, "top": top, "doctop": top + doctop_adj, "bottom": bottom, "upright": upright, "direction": direction, } for key in self.extra_attrs: word[key] = ordered_chars[0][key] return word def char_begins_new_word( self, current_chars: T_obj_list, current_bbox: T_bbox, next_char: T_obj, ) -> bool: upright = current_chars[0]["upright"] intraline_tol = self.x_tolerance if upright else self.y_tolerance interline_tol = self.y_tolerance if upright else self.x_tolerance word_x0, word_top, word_x1, word_bottom = current_bbox return bool( (next_char["x0"] > word_x1 + intraline_tol) or (next_char["x1"] < word_x0 - intraline_tol) or (next_char["top"] > word_bottom + interline_tol) or (next_char["bottom"] < word_top - interline_tol) ) def iter_chars_to_words( self, chars: T_obj_iter ) -> Generator[T_obj_list, None, None]: current_word: T_obj_list = [] current_bbox: Optional[T_bbox] = None def start_next_word( new_char: Optional[T_obj], ) -> Generator[T_obj_list, None, None]: nonlocal current_word nonlocal current_bbox if current_word: yield current_word current_word = [] if new_char is None else [new_char] current_bbox = None if new_char is None else obj_to_bbox(new_char) for char in chars: text = char["text"] if not self.keep_blank_chars and text.isspace(): yield from start_next_word(None) elif text in self.split_at_punctuation: yield from start_next_word(char) yield from start_next_word(None) elif ( current_word and current_bbox and self.char_begins_new_word(current_word, current_bbox, char) ): yield from start_next_word(char) else: current_word.append(char) if current_bbox is None: current_bbox = obj_to_bbox(char) else: current_bbox = merge_bboxes([current_bbox, obj_to_bbox(char)]) # Finally, after all chars processed if current_word: yield current_word def iter_sort_chars(self, chars: T_obj_iter) -> Generator[T_obj, None, None]: def upright_key(x: T_obj) -> int: return -int(x["upright"]) for upright_cluster in cluster_objects(list(chars), upright_key, 0): upright = upright_cluster[0]["upright"] cluster_key = "doctop" if upright else "x0" # Cluster by line subclusters = cluster_objects( upright_cluster, itemgetter(cluster_key), self.y_tolerance ) for sc in subclusters: # Sort within line sort_key = "x0" if upright else "doctop" to_yield = sorted(sc, key=itemgetter(sort_key)) # Reverse order if necessary if not (self.horizontal_ltr if upright else self.vertical_ttb): yield from reversed(to_yield) else: yield from to_yield def iter_extract_tuples( self, chars: T_obj_iter ) -> Generator[Tuple[T_obj, T_obj_list], None, None]: if not self.use_text_flow: chars = self.iter_sort_chars(chars) grouping_key = itemgetter("upright", *self.extra_attrs) grouped = itertools.groupby(chars, grouping_key) for keyvals, char_group in grouped: for word_chars in self.iter_chars_to_words(char_group): yield (self.merge_chars(word_chars), word_chars) def extract(self, chars: T_obj_list) -> T_obj_list: return list(word for word, word_chars in self.iter_extract_tuples(chars)) class LayoutEngine: def __init__( self, x_density: T_num = DEFAULT_X_DENSITY, y_density: T_num = DEFAULT_Y_DENSITY, x_shift: T_num = 0, y_shift: T_num = 0, y_tolerance: T_num = DEFAULT_Y_TOLERANCE, presorted: bool = False, ): self.x_density = x_density self.y_density = y_density self.x_shift = x_shift self.y_shift = y_shift self.y_tolerance = y_tolerance self.presorted = presorted def calculate( self, word_tuples: List[Tuple[T_obj, T_obj_list]] ) -> List[Tuple[str, Optional[T_obj]]]: """ Given a list of (word, chars) tuples, return a list of (char-text, char) tuples that can be used to mimic the structural layout of the text on the page(s), using the following approach: - Sort the words by (doctop, x0) if not already sorted. - Calculate the initial doctop for the starting page. - Cluster the words by doctop (taking `y_tolerance` into account), and iterate through them. - For each cluster, calculate the distance between that doctop and the initial doctop, in points, minus `y_shift`. Divide that distance by `y_density` to calculate the minimum number of newlines that should come before this cluster. Append that number of newlines *minus* the number of newlines already appended, with a minimum of one. - Then for each cluster, iterate through each word in it. Divide each word's x0, minus `x_shift`, by `x_density` to calculate the minimum number of characters that should come before this cluster. Append that number of spaces *minus* the number of characters and spaces already appended, with a minimum of one. Then append the word's text. Note: This approach currently works best for horizontal, left-to-right text, but will display all words regardless of orientation. There is room for improvement in better supporting right-to-left text, as well as vertical text. """ rendered: List[Tuple[str, Optional[T_obj]]] = [] if not len(word_tuples): return rendered num_newlines = 0 words_sorted = ( word_tuples if self.presorted else sorted(word_tuples, key=lambda x: (x[0]["doctop"], x[0]["x0"])) ) first_word = words_sorted[0][0] doctop_start = first_word["doctop"] - first_word["top"] for ws in cluster_objects( words_sorted, lambda x: float(x[0]["doctop"]), self.y_tolerance ): y_dist = ( ws[0][0]["doctop"] - (doctop_start + self.y_shift) ) / self.y_density num_newlines_prepend = max( min(1, num_newlines), round(y_dist) - num_newlines ) rendered += [("\n", None)] * num_newlines_prepend num_newlines += num_newlines_prepend line_len = 0 for word, chars in sorted(ws, key=lambda x: float(x[0]["x0"])): x_dist = (word["x0"] - self.x_shift) / self.x_density num_spaces_prepend = max(min(1, line_len), round(x_dist) - line_len) rendered += [(" ", None)] * num_spaces_prepend for c in chars: for letter in c["text"]: rendered.append((letter, c)) line_len += num_spaces_prepend + len(word["text"]) return rendered def extract_words( chars: T_obj_list, x_tolerance: T_num = DEFAULT_X_TOLERANCE, y_tolerance: T_num = DEFAULT_Y_TOLERANCE, keep_blank_chars: bool = False, use_text_flow: bool = False, horizontal_ltr: bool = True, # Should words be read left-to-right? vertical_ttb: bool = True, # Should vertical words be read top-to-bottom? extra_attrs: Optional[List[str]] = None, split_at_punctuation: Union[bool, str] = False, ) -> T_obj_list: return WordExtractor( x_tolerance=x_tolerance, y_tolerance=y_tolerance, keep_blank_chars=keep_blank_chars, use_text_flow=use_text_flow, horizontal_ltr=horizontal_ltr, vertical_ttb=vertical_ttb, extra_attrs=extra_attrs, split_at_punctuation=split_at_punctuation, ).extract(chars) class TextLayout: def __init__( self, chars: T_obj_list, extractor: WordExtractor, engine: LayoutEngine ): self.chars = chars self.extractor = extractor self.engine = engine self.word_tuples = list(extractor.iter_extract_tuples(chars)) self.layout_tuples = engine.calculate(self.word_tuples) self.as_string = "".join(map(itemgetter(0), self.layout_tuples)) def to_string(self) -> str: return self.as_string def search( self, pattern: Union[str, Pattern[str]], regex: bool = True, case: bool = True ) -> List[Dict[str, Any]]: def match_to_dict(m: Match[str]) -> Dict[str, Any]: subset = self.layout_tuples[m.start() : m.end()] chars = [c for (text, c) in subset if c is not None] x0, top, x1, bottom = objects_to_bbox(chars) return { "text": m.group(0), "groups": m.groups(), "x0": x0, "top": top, "x1": x1, "bottom": bottom, "chars": chars, } if isinstance(pattern, Pattern): if regex is False: raise ValueError( "Cannot pass a compiled search pattern *and* regex=False together." ) if case is False: raise ValueError( "Cannot pass a compiled search pattern *and* case=False together." ) compiled = pattern else: if regex is False: pattern = re.escape(pattern) flags = re.I if case is False else 0 compiled = re.compile(pattern, flags) gen = re.finditer(compiled, self.as_string) return list(map(match_to_dict, gen)) def collate_line( line_chars: T_obj_list, tolerance: T_num = DEFAULT_X_TOLERANCE, layout: bool = False ) -> str: coll = "" last_x1 = None for char in sorted(line_chars, key=itemgetter("x0")): if (last_x1 is not None) and (char["x0"] > (last_x1 + tolerance)): coll += " " last_x1 = char["x1"] coll += char["text"] return coll def chars_to_layout( chars: T_obj_list, x_density: T_num = DEFAULT_X_DENSITY, y_density: T_num = DEFAULT_Y_DENSITY, x_shift: T_num = 0, y_shift: T_num = 0, x_tolerance: T_num = DEFAULT_X_TOLERANCE, y_tolerance: T_num = DEFAULT_Y_TOLERANCE, keep_blank_chars: bool = False, use_text_flow: bool = False, horizontal_ltr: bool = True, # Should words be read left-to-right? vertical_ttb: bool = True, # Should vertical words be read top-to-bottom? extra_attrs: Optional[List[str]] = None, split_at_punctuation: Union[bool, str] = False, ) -> TextLayout: extractor = WordExtractor( x_tolerance=x_tolerance, y_tolerance=y_tolerance, keep_blank_chars=keep_blank_chars, use_text_flow=use_text_flow, horizontal_ltr=horizontal_ltr, vertical_ttb=vertical_ttb, extra_attrs=extra_attrs, split_at_punctuation=split_at_punctuation, ) engine = LayoutEngine( x_density=x_density, y_density=y_density, x_shift=x_shift, y_shift=y_shift, y_tolerance=y_tolerance, presorted=True, ) return TextLayout(chars, extractor, engine) def extract_text( chars: T_obj_list, layout: bool = False, x_density: T_num = DEFAULT_X_DENSITY, y_density: T_num = DEFAULT_Y_DENSITY, x_shift: T_num = 0, y_shift: T_num = 0, x_tolerance: T_num = DEFAULT_X_TOLERANCE, y_tolerance: T_num = DEFAULT_Y_TOLERANCE, keep_blank_chars: bool = False, use_text_flow: bool = False, horizontal_ltr: bool = True, # Should words be read left-to-right? vertical_ttb: bool = True, # Should vertical words be read top-to-bottom? extra_attrs: Optional[List[str]] = None, split_at_punctuation: Union[bool, str] = False, ) -> str: chars = to_list(chars) if len(chars) == 0: return "" if layout: calculated_layout = chars_to_layout( chars, x_tolerance=x_tolerance, y_tolerance=y_tolerance, keep_blank_chars=keep_blank_chars, use_text_flow=use_text_flow, horizontal_ltr=horizontal_ltr, vertical_ttb=vertical_ttb, extra_attrs=extra_attrs, split_at_punctuation=split_at_punctuation, x_density=x_density, y_density=y_density, x_shift=x_shift, y_shift=y_shift, ) return calculated_layout.to_string() else: doctop_clusters = cluster_objects(chars, itemgetter("doctop"), y_tolerance) lines = ( collate_line(line_chars, x_tolerance) for line_chars in doctop_clusters ) return "\n".join(lines) def get_bbox_overlap(a: T_bbox, b: T_bbox) -> Optional[T_bbox]: a_left, a_top, a_right, a_bottom = a b_left, b_top, b_right, b_bottom = b o_left = max(a_left, b_left) o_right = min(a_right, b_right) o_bottom = min(a_bottom, b_bottom) o_top = max(a_top, b_top) o_width = o_right - o_left o_height = o_bottom - o_top if o_height >= 0 and o_width >= 0 and o_height + o_width > 0: return (o_left, o_top, o_right, o_bottom) else: return None def calculate_area(bbox: T_bbox) -> T_num: left, top, right, bottom = bbox if left > right or top > bottom: raise ValueError(f"{bbox} has a negative width or height.") return (right - left) * (bottom - top) def clip_obj(obj: T_obj, bbox: T_bbox) -> Optional[T_obj]: overlap = get_bbox_overlap(obj_to_bbox(obj), bbox) if overlap is None: return None dims = bbox_to_rect(overlap) copy = dict(obj) for attr in ["x0", "top", "x1", "bottom"]: copy[attr] = dims[attr] diff = dims["top"] - obj["top"] copy["doctop"] = obj["doctop"] + diff copy["width"] = copy["x1"] - copy["x0"] copy["height"] = copy["bottom"] - copy["top"] return copy def intersects_bbox(objs: T_obj_list, bbox: T_bbox) -> T_obj_list: """ Filters objs to only those intersecting the bbox """ initial_type = type(objs) objs = to_list(objs) matching = [ obj for obj in objs if get_bbox_overlap(obj_to_bbox(obj), bbox) is not None ] return initial_type(matching) def within_bbox(objs: T_obj_list, bbox: T_bbox) -> T_obj_list: """ Filters objs to only those fully within the bbox """ return [ obj for obj in objs if get_bbox_overlap(obj_to_bbox(obj), bbox) == obj_to_bbox(obj) ] def outside_bbox(objs: T_obj_list, bbox: T_bbox) -> T_obj_list: """ Filters objs to only those fully outside the bbox """ return [obj for obj in objs if get_bbox_overlap(obj_to_bbox(obj), bbox) is None] def crop_to_bbox(objs: T_obj_list, bbox: T_bbox) -> T_obj_list: """ Filters objs to only those intersecting the bbox, and crops the extent of the objects to the bbox. """ return list(filter(None, (clip_obj(obj, bbox) for obj in objs))) def move_object(obj: T_obj, axis: str, value: T_num) -> T_obj: assert axis in ("h", "v") if axis == "h": new_items = [ ("x0", obj["x0"] + value), ("x1", obj["x1"] + value), ] if axis == "v": new_items = [ ("top", obj["top"] + value), ("bottom", obj["bottom"] + value), ] if "doctop" in obj: new_items += [("doctop", obj["doctop"] + value)] if "y0" in obj: new_items += [ ("y0", obj["y0"] - value), ("y1", obj["y1"] - value), ] return obj.__class__(tuple(obj.items()) + tuple(new_items)) def snap_objects(objs: T_obj_list, attr: str, tolerance: T_num) -> T_obj_list: axis = {"x0": "h", "x1": "h", "top": "v", "bottom": "v"}[attr] clusters = cluster_objects(objs, itemgetter(attr), tolerance) avgs = [sum(map(itemgetter(attr), objs)) / len(objs) for objs in clusters] snapped_clusters = [ [move_object(obj, axis, avg - obj[attr]) for obj in cluster] for cluster, avg in zip(clusters, avgs) ] return list(itertools.chain(*snapped_clusters)) def resize_object(obj: T_obj, key: str, value: T_num) -> T_obj: assert key in ("x0", "x1", "top", "bottom") old_value = obj[key] diff = value - old_value new_items = [ (key, value), ] if key == "x0": assert value <= obj["x1"] new_items.append(("width", obj["x1"] - value)) elif key == "x1": assert value >= obj["x0"] new_items.append(("width", value - obj["x0"])) elif key == "top": assert value <= obj["bottom"] new_items.append(("doctop", obj["doctop"] + diff)) new_items.append(("height", obj["height"] - diff)) if "y1" in obj: new_items.append(("y1", obj["y1"] - diff)) elif key == "bottom": assert value >= obj["top"] new_items.append(("height", obj["height"] + diff)) if "y0" in obj: new_items.append(("y0", obj["y0"] - diff)) return obj.__class__(tuple(obj.items()) + tuple(new_items)) def curve_to_edges(curve: T_obj) -> T_obj_list: point_pairs = zip(curve["points"], curve["points"][1:]) return [ { "x0": min(p0[0], p1[0]), "x1": max(p0[0], p1[0]), "top": min(p0[1], p1[1]), "doctop": min(p0[1], p1[1]) + (curve["doctop"] - curve["top"]), "bottom": max(p0[1], p1[1]), "width": abs(p0[0] - p1[0]), "height": abs(p0[1] - p1[1]), "orientation": "v" if p0[0] == p1[0] else ("h" if p0[1] == p1[1] else None), } for p0, p1 in point_pairs ] def rect_to_edges(rect: T_obj) -> T_obj_list: top, bottom, left, right = [dict(rect) for x in range(4)] top.update( { "object_type": "rect_edge", "height": 0, "y0": rect["y1"], "bottom": rect["top"], "orientation": "h", } ) bottom.update( { "object_type": "rect_edge", "height": 0, "y1": rect["y0"], "top": rect["top"] + rect["height"], "doctop": rect["doctop"] + rect["height"], "orientation": "h", } ) left.update( { "object_type": "rect_edge", "width": 0, "x1": rect["x0"], "orientation": "v", } ) right.update( { "object_type": "rect_edge", "width": 0, "x0": rect["x1"], "orientation": "v", } ) return [top, bottom, left, right] def line_to_edge(line: T_obj) -> T_obj: edge = dict(line) edge["orientation"] = "h" if (line["top"] == line["bottom"]) else "v" return edge def obj_to_edges(obj: T_obj) -> T_obj_list: return { "line": lambda x: [line_to_edge(x)], "rect": rect_to_edges, "rect_edge": rect_to_edges, "curve": curve_to_edges, }[obj["object_type"]](obj) def filter_edges( edges: T_obj_list, orientation: Optional[str] = None, edge_type: Optional[str] = None, min_length: T_num = 1, ) -> T_obj_list: if orientation not in ("v", "h", None): raise ValueError("Orientation must be 'v' or 'h'") def test(e: T_obj) -> bool: dim = "height" if e["orientation"] == "v" else "width" et_correct = e["object_type"] == edge_type if edge_type is not None else True orient_correct = orientation is None or e["orientation"] == orientation return bool(et_correct and orient_correct and (e[dim] >= min_length)) return list(filter(test, edges))
mit
9690bd688fed73282f622bd66c610227
31.165727
88
0.564298
3.435814
false
false
false
false
sqlalchemy/sqlalchemy
lib/sqlalchemy/pool/events.py
2
13424
# sqlalchemy/pool/events.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php from __future__ import annotations import typing from typing import Any from typing import Optional from typing import Type from typing import Union from .base import ConnectionPoolEntry from .base import Pool from .base import PoolProxiedConnection from .base import PoolResetState from .. import event from .. import util if typing.TYPE_CHECKING: from ..engine import Engine from ..engine.interfaces import DBAPIConnection class PoolEvents(event.Events[Pool]): """Available events for :class:`_pool.Pool`. The methods here define the name of an event as well as the names of members that are passed to listener functions. e.g.:: from sqlalchemy import event def my_on_checkout(dbapi_conn, connection_rec, connection_proxy): "handle an on checkout event" event.listen(Pool, 'checkout', my_on_checkout) In addition to accepting the :class:`_pool.Pool` class and :class:`_pool.Pool` instances, :class:`_events.PoolEvents` also accepts :class:`_engine.Engine` objects and the :class:`_engine.Engine` class as targets, which will be resolved to the ``.pool`` attribute of the given engine or the :class:`_pool.Pool` class:: engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test") # will associate with engine.pool event.listen(engine, 'checkout', my_on_checkout) """ # noqa: E501 _target_class_doc = "SomeEngineOrPool" _dispatch_target = Pool @util.preload_module("sqlalchemy.engine") @classmethod def _accept_with( cls, target: Union[Pool, Type[Pool], Engine, Type[Engine]], identifier: str, ) -> Optional[Union[Pool, Type[Pool]]]: if not typing.TYPE_CHECKING: Engine = util.preloaded.engine.Engine if isinstance(target, type): if issubclass(target, Engine): return Pool else: assert issubclass(target, Pool) return target elif isinstance(target, Engine): return target.pool elif isinstance(target, Pool): return target elif hasattr(target, "_no_async_engine_events"): target._no_async_engine_events() else: return None @classmethod def _listen( # type: ignore[override] # would rather keep **kw cls, event_key: event._EventKey[Pool], **kw: Any, ) -> None: target = event_key.dispatch_target kw.setdefault("asyncio", target._is_asyncio) event_key.base_listen(**kw) def connect( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, ) -> None: """Called at the moment a particular DBAPI connection is first created for a given :class:`_pool.Pool`. This event allows one to capture the point directly after which the DBAPI module-level ``.connect()`` method has been used in order to produce a new DBAPI connection. :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. """ def first_connect( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, ) -> None: """Called exactly once for the first time a DBAPI connection is checked out from a particular :class:`_pool.Pool`. The rationale for :meth:`_events.PoolEvents.first_connect` is to determine information about a particular series of database connections based on the settings used for all connections. Since a particular :class:`_pool.Pool` refers to a single "creator" function (which in terms of a :class:`_engine.Engine` refers to the URL and connection options used), it is typically valid to make observations about a single connection that can be safely assumed to be valid about all subsequent connections, such as the database version, the server and client encoding settings, collation settings, and many others. :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. """ def checkout( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, connection_proxy: PoolProxiedConnection, ) -> None: """Called when a connection is retrieved from the Pool. :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. :param connection_proxy: the :class:`.PoolProxiedConnection` object which will proxy the public interface of the DBAPI connection for the lifespan of the checkout. If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection. .. seealso:: :meth:`_events.ConnectionEvents.engine_connect` - a similar event which occurs upon creation of a new :class:`_engine.Connection`. """ def checkin( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, ) -> None: """Called when a connection returns to the pool. Note that the connection may be closed, and may be None if the connection has been invalidated. ``checkin`` will not be called for detached connections. (They do not return to the pool.) :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. """ @event._legacy_signature( "2.0", ["dbapi_connection", "connection_record"], lambda dbapi_connection, connection_record, reset_state: ( dbapi_connection, connection_record, ), ) def reset( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, reset_state: PoolResetState, ) -> None: """Called before the "reset" action occurs for a pooled connection. This event represents when the ``rollback()`` method is called on the DBAPI connection before it is returned to the pool or discarded. A custom "reset" strategy may be implemented using this event hook, which may also be combined with disabling the default "reset" behavior using the :paramref:`_pool.Pool.reset_on_return` parameter. The primary difference between the :meth:`_events.PoolEvents.reset` and :meth:`_events.PoolEvents.checkin` events are that :meth:`_events.PoolEvents.reset` is called not just for pooled connections that are being returned to the pool, but also for connections that were detached using the :meth:`_engine.Connection.detach` method as well as asyncio connections that are being discarded due to garbage collection taking place on connections before the connection was checked in. Note that the event **is not** invoked for connections that were invalidated using :meth:`_engine.Connection.invalidate`. These events may be intercepted using the :meth:`.PoolEvents.soft_invalidate` and :meth:`.PoolEvents.invalidate` event hooks, and all "connection close" events may be intercepted using :meth:`.PoolEvents.close`. The :meth:`_events.PoolEvents.reset` event is usually followed by the :meth:`_events.PoolEvents.checkin` event, except in those cases where the connection is discarded immediately after reset. :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. :param reset_state: :class:`.PoolResetState` instance which provides information about the circumstances under which the connection is being reset. .. versionadded:: 2.0 .. seealso:: :ref:`pool_reset_on_return` :meth:`_events.ConnectionEvents.rollback` :meth:`_events.ConnectionEvents.commit` """ def invalidate( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, exception: Optional[BaseException], ) -> None: """Called when a DBAPI connection is to be "invalidated". This event is called any time the :meth:`.ConnectionPoolEntry.invalidate` method is invoked, either from API usage or via "auto-invalidation", without the ``soft`` flag. The event occurs before a final attempt to call ``.close()`` on the connection occurs. :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. :param exception: the exception object corresponding to the reason for this invalidation, if any. May be ``None``. .. versionadded:: 0.9.2 Added support for connection invalidation listening. .. seealso:: :ref:`pool_connection_invalidation` """ def soft_invalidate( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, exception: Optional[BaseException], ) -> None: """Called when a DBAPI connection is to be "soft invalidated". This event is called any time the :meth:`.ConnectionPoolEntry.invalidate` method is invoked with the ``soft`` flag. Soft invalidation refers to when the connection record that tracks this connection will force a reconnect after the current connection is checked in. It does not actively close the dbapi_connection at the point at which it is called. .. versionadded:: 1.0.3 :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. :param exception: the exception object corresponding to the reason for this invalidation, if any. May be ``None``. """ def close( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, ) -> None: """Called when a DBAPI connection is closed. The event is emitted before the close occurs. The close of a connection can fail; typically this is because the connection is already closed. If the close operation fails, the connection is discarded. The :meth:`.close` event corresponds to a connection that's still associated with the pool. To intercept close events for detached connections use :meth:`.close_detached`. .. versionadded:: 1.1 :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. """ def detach( self, dbapi_connection: DBAPIConnection, connection_record: ConnectionPoolEntry, ) -> None: """Called when a DBAPI connection is "detached" from a pool. This event is emitted after the detach occurs. The connection is no longer associated with the given connection record. .. versionadded:: 1.1 :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. :param connection_record: the :class:`.ConnectionPoolEntry` managing the DBAPI connection. """ def close_detached(self, dbapi_connection: DBAPIConnection) -> None: """Called when a detached DBAPI connection is closed. The event is emitted before the close occurs. The close of a connection can fail; typically this is because the connection is already closed. If the close operation fails, the connection is discarded. .. versionadded:: 1.1 :param dbapi_connection: a DBAPI connection. The :attr:`.ConnectionPoolEntry.dbapi_connection` attribute. """
mit
34547e39de894f9ef48f67be6a1a531f
34.233596
82
0.657032
4.820108
false
false
false
false
sqlalchemy/sqlalchemy
lib/sqlalchemy/engine/events.py
2
36475
# sqlalchemy/engine/events.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php from __future__ import annotations import typing from typing import Any from typing import Dict from typing import Optional from typing import Tuple from typing import Type from typing import Union from .base import Connection from .base import Engine from .interfaces import ConnectionEventsTarget from .interfaces import DBAPIConnection from .interfaces import DBAPICursor from .interfaces import Dialect from .. import event from .. import exc from ..util.typing import Literal if typing.TYPE_CHECKING: from .interfaces import _CoreMultiExecuteParams from .interfaces import _CoreSingleExecuteParams from .interfaces import _DBAPIAnyExecuteParams from .interfaces import _DBAPIMultiExecuteParams from .interfaces import _DBAPISingleExecuteParams from .interfaces import _ExecuteOptions from .interfaces import ExceptionContext from .interfaces import ExecutionContext from .result import Result from ..pool import ConnectionPoolEntry from ..sql import Executable from ..sql.elements import BindParameter class ConnectionEvents(event.Events[ConnectionEventsTarget]): """Available events for :class:`_engine.Connection` and :class:`_engine.Engine`. The methods here define the name of an event as well as the names of members that are passed to listener functions. An event listener can be associated with any :class:`_engine.Connection` or :class:`_engine.Engine` class or instance, such as an :class:`_engine.Engine`, e.g.:: from sqlalchemy import event, create_engine def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): log.info("Received statement: %s", statement) engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/test') event.listen(engine, "before_cursor_execute", before_cursor_execute) or with a specific :class:`_engine.Connection`:: with engine.begin() as conn: @event.listens_for(conn, 'before_cursor_execute') def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): log.info("Received statement: %s", statement) When the methods are called with a `statement` parameter, such as in :meth:`.after_cursor_execute` or :meth:`.before_cursor_execute`, the statement is the exact SQL string that was prepared for transmission to the DBAPI ``cursor`` in the connection's :class:`.Dialect`. The :meth:`.before_execute` and :meth:`.before_cursor_execute` events can also be established with the ``retval=True`` flag, which allows modification of the statement and parameters to be sent to the database. The :meth:`.before_cursor_execute` event is particularly useful here to add ad-hoc string transformations, such as comments, to all executions:: from sqlalchemy.engine import Engine from sqlalchemy import event @event.listens_for(Engine, "before_cursor_execute", retval=True) def comment_sql_calls(conn, cursor, statement, parameters, context, executemany): statement = statement + " -- some comment" return statement, parameters .. note:: :class:`_events.ConnectionEvents` can be established on any combination of :class:`_engine.Engine`, :class:`_engine.Connection`, as well as instances of each of those classes. Events across all four scopes will fire off for a given instance of :class:`_engine.Connection`. However, for performance reasons, the :class:`_engine.Connection` object determines at instantiation time whether or not its parent :class:`_engine.Engine` has event listeners established. Event listeners added to the :class:`_engine.Engine` class or to an instance of :class:`_engine.Engine` *after* the instantiation of a dependent :class:`_engine.Connection` instance will usually *not* be available on that :class:`_engine.Connection` instance. The newly added listeners will instead take effect for :class:`_engine.Connection` instances created subsequent to those event listeners being established on the parent :class:`_engine.Engine` class or instance. :param retval=False: Applies to the :meth:`.before_execute` and :meth:`.before_cursor_execute` events only. When True, the user-defined event function must have a return value, which is a tuple of parameters that replace the given statement and parameters. See those methods for a description of specific return arguments. """ # noqa _target_class_doc = "SomeEngine" _dispatch_target = ConnectionEventsTarget @classmethod def _accept_with( cls, target: Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]], identifier: str, ) -> Optional[Union[ConnectionEventsTarget, Type[ConnectionEventsTarget]]]: default_dispatch = super()._accept_with(target, identifier) if default_dispatch is None and hasattr( target, "_no_async_engine_events" ): target._no_async_engine_events() # type: ignore return default_dispatch @classmethod def _listen( cls, event_key: event._EventKey[ConnectionEventsTarget], *, retval: bool = False, **kw: Any, ) -> None: target, identifier, fn = ( event_key.dispatch_target, event_key.identifier, event_key._listen_fn, ) target._has_events = True if not retval: if identifier == "before_execute": orig_fn = fn def wrap_before_execute( # type: ignore conn, clauseelement, multiparams, params, execution_options ): orig_fn( conn, clauseelement, multiparams, params, execution_options, ) return clauseelement, multiparams, params fn = wrap_before_execute elif identifier == "before_cursor_execute": orig_fn = fn def wrap_before_cursor_execute( # type: ignore conn, cursor, statement, parameters, context, executemany ): orig_fn( conn, cursor, statement, parameters, context, executemany, ) return statement, parameters fn = wrap_before_cursor_execute elif retval and identifier not in ( "before_execute", "before_cursor_execute", ): raise exc.ArgumentError( "Only the 'before_execute', " "'before_cursor_execute' and 'handle_error' engine " "event listeners accept the 'retval=True' " "argument." ) event_key.with_wrapper(fn).base_listen() @event._legacy_signature( "1.4", ["conn", "clauseelement", "multiparams", "params"], lambda conn, clauseelement, multiparams, params, execution_options: ( conn, clauseelement, multiparams, params, ), ) def before_execute( self, conn: Connection, clauseelement: Executable, multiparams: _CoreMultiExecuteParams, params: _CoreSingleExecuteParams, execution_options: _ExecuteOptions, ) -> Optional[ Tuple[Executable, _CoreMultiExecuteParams, _CoreSingleExecuteParams] ]: """Intercept high level execute() events, receiving uncompiled SQL constructs and other objects prior to rendering into SQL. This event is good for debugging SQL compilation issues as well as early manipulation of the parameters being sent to the database, as the parameter lists will be in a consistent format here. This event can be optionally established with the ``retval=True`` flag. The ``clauseelement``, ``multiparams``, and ``params`` arguments should be returned as a three-tuple in this case:: @event.listens_for(Engine, "before_execute", retval=True) def before_execute(conn, clauseelement, multiparams, params): # do something with clauseelement, multiparams, params return clauseelement, multiparams, params :param conn: :class:`_engine.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` instance, or string statement passed to :meth:`_engine.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. :param execution_options: dictionary of execution options passed along with the statement, if any. This is a merge of all options that will be used, including those of the statement, the connection, and those passed in to the method itself for the 2.0 style of execution. .. versionadded: 1.4 .. seealso:: :meth:`.before_cursor_execute` """ @event._legacy_signature( "1.4", ["conn", "clauseelement", "multiparams", "params", "result"], lambda conn, clauseelement, multiparams, params, execution_options, result: ( # noqa conn, clauseelement, multiparams, params, result, ), ) def after_execute( self, conn: Connection, clauseelement: Executable, multiparams: _CoreMultiExecuteParams, params: _CoreSingleExecuteParams, execution_options: _ExecuteOptions, result: Result[Any], ) -> None: """Intercept high level execute() events after execute. :param conn: :class:`_engine.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` instance, or string statement passed to :meth:`_engine.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. :param execution_options: dictionary of execution options passed along with the statement, if any. This is a merge of all options that will be used, including those of the statement, the connection, and those passed in to the method itself for the 2.0 style of execution. .. versionadded: 1.4 :param result: :class:`_engine.CursorResult` generated by the execution. """ def before_cursor_execute( self, conn: Connection, cursor: DBAPICursor, statement: str, parameters: _DBAPIAnyExecuteParams, context: Optional[ExecutionContext], executemany: bool, ) -> Optional[Tuple[str, _DBAPIAnyExecuteParams]]: """Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor. This event is a good choice for logging as well as late modifications to the SQL string. It's less ideal for parameter modifications except for those which are specific to a target backend. This event can be optionally established with the ``retval=True`` flag. The ``statement`` and ``parameters`` arguments should be returned as a two-tuple in this case:: @event.listens_for(Engine, "before_cursor_execute", retval=True) def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): # do something with statement, parameters return statement, parameters See the example at :class:`_events.ConnectionEvents`. :param conn: :class:`_engine.Connection` object :param cursor: DBAPI cursor object :param statement: string SQL statement, as to be passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being passed to the ``execute()`` or ``executemany()`` method of the DBAPI ``cursor``. In some cases may be ``None``. :param context: :class:`.ExecutionContext` object in use. May be ``None``. :param executemany: boolean, if ``True``, this is an ``executemany()`` call, if ``False``, this is an ``execute()`` call. .. seealso:: :meth:`.before_execute` :meth:`.after_cursor_execute` """ def after_cursor_execute( self, conn: Connection, cursor: DBAPICursor, statement: str, parameters: _DBAPIAnyExecuteParams, context: Optional[ExecutionContext], executemany: bool, ) -> None: """Intercept low-level cursor execute() events after execution. :param conn: :class:`_engine.Connection` object :param cursor: DBAPI cursor object. Will have results pending if the statement was a SELECT, but these should not be consumed as they will be needed by the :class:`_engine.CursorResult`. :param statement: string SQL statement, as passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being passed to the ``execute()`` or ``executemany()`` method of the DBAPI ``cursor``. In some cases may be ``None``. :param context: :class:`.ExecutionContext` object in use. May be ``None``. :param executemany: boolean, if ``True``, this is an ``executemany()`` call, if ``False``, this is an ``execute()`` call. """ @event._legacy_signature( "2.0", ["conn", "branch"], converter=lambda conn: (conn, False) ) def engine_connect(self, conn: Connection) -> None: """Intercept the creation of a new :class:`_engine.Connection`. This event is called typically as the direct result of calling the :meth:`_engine.Engine.connect` method. It differs from the :meth:`_events.PoolEvents.connect` method, which refers to the actual connection to a database at the DBAPI level; a DBAPI connection may be pooled and reused for many operations. In contrast, this event refers only to the production of a higher level :class:`_engine.Connection` wrapper around such a DBAPI connection. It also differs from the :meth:`_events.PoolEvents.checkout` event in that it is specific to the :class:`_engine.Connection` object, not the DBAPI connection that :meth:`_events.PoolEvents.checkout` deals with, although this DBAPI connection is available here via the :attr:`_engine.Connection.connection` attribute. But note there can in fact be multiple :meth:`_events.PoolEvents.checkout` events within the lifespan of a single :class:`_engine.Connection` object, if that :class:`_engine.Connection` is invalidated and re-established. :param conn: :class:`_engine.Connection` object. .. seealso:: :meth:`_events.PoolEvents.checkout` the lower-level pool checkout event for an individual DBAPI connection """ def set_connection_execution_options( self, conn: Connection, opts: Dict[str, Any] ) -> None: """Intercept when the :meth:`_engine.Connection.execution_options` method is called. This method is called after the new :class:`_engine.Connection` has been produced, with the newly updated execution options collection, but before the :class:`.Dialect` has acted upon any of those new options. Note that this method is not called when a new :class:`_engine.Connection` is produced which is inheriting execution options from its parent :class:`_engine.Engine`; to intercept this condition, use the :meth:`_events.ConnectionEvents.engine_connect` event. :param conn: The newly copied :class:`_engine.Connection` object :param opts: dictionary of options that were passed to the :meth:`_engine.Connection.execution_options` method. This dictionary may be modified in place to affect the ultimate options which take effect. .. versionadded:: 2.0 the ``opts`` dictionary may be modified in place. .. seealso:: :meth:`_events.ConnectionEvents.set_engine_execution_options` - event which is called when :meth:`_engine.Engine.execution_options` is called. """ def set_engine_execution_options( self, engine: Engine, opts: Dict[str, Any] ) -> None: """Intercept when the :meth:`_engine.Engine.execution_options` method is called. The :meth:`_engine.Engine.execution_options` method produces a shallow copy of the :class:`_engine.Engine` which stores the new options. That new :class:`_engine.Engine` is passed here. A particular application of this method is to add a :meth:`_events.ConnectionEvents.engine_connect` event handler to the given :class:`_engine.Engine` which will perform some per- :class:`_engine.Connection` task specific to these execution options. :param conn: The newly copied :class:`_engine.Engine` object :param opts: dictionary of options that were passed to the :meth:`_engine.Connection.execution_options` method. This dictionary may be modified in place to affect the ultimate options which take effect. .. versionadded:: 2.0 the ``opts`` dictionary may be modified in place. .. seealso:: :meth:`_events.ConnectionEvents.set_connection_execution_options` - event which is called when :meth:`_engine.Connection.execution_options` is called. """ def engine_disposed(self, engine: Engine) -> None: """Intercept when the :meth:`_engine.Engine.dispose` method is called. The :meth:`_engine.Engine.dispose` method instructs the engine to "dispose" of it's connection pool (e.g. :class:`_pool.Pool`), and replaces it with a new one. Disposing of the old pool has the effect that existing checked-in connections are closed. The new pool does not establish any new connections until it is first used. This event can be used to indicate that resources related to the :class:`_engine.Engine` should also be cleaned up, keeping in mind that the :class:`_engine.Engine` can still be used for new requests in which case it re-acquires connection resources. .. versionadded:: 1.0.5 """ def begin(self, conn: Connection) -> None: """Intercept begin() events. :param conn: :class:`_engine.Connection` object """ def rollback(self, conn: Connection) -> None: """Intercept rollback() events, as initiated by a :class:`.Transaction`. Note that the :class:`_pool.Pool` also "auto-rolls back" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to its default value of ``'rollback'``. To intercept this rollback, use the :meth:`_events.PoolEvents.reset` hook. :param conn: :class:`_engine.Connection` object .. seealso:: :meth:`_events.PoolEvents.reset` """ def commit(self, conn: Connection) -> None: """Intercept commit() events, as initiated by a :class:`.Transaction`. Note that the :class:`_pool.Pool` may also "auto-commit" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to the value ``'commit'``. To intercept this commit, use the :meth:`_events.PoolEvents.reset` hook. :param conn: :class:`_engine.Connection` object """ def savepoint(self, conn: Connection, name: str) -> None: """Intercept savepoint() events. :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. """ def rollback_savepoint( self, conn: Connection, name: str, context: None ) -> None: """Intercept rollback_savepoint() events. :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. :param context: not used """ # TODO: deprecate "context" def release_savepoint( self, conn: Connection, name: str, context: None ) -> None: """Intercept release_savepoint() events. :param conn: :class:`_engine.Connection` object :param name: specified name used for the savepoint. :param context: not used """ # TODO: deprecate "context" def begin_twophase(self, conn: Connection, xid: Any) -> None: """Intercept begin_twophase() events. :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier """ def prepare_twophase(self, conn: Connection, xid: Any) -> None: """Intercept prepare_twophase() events. :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier """ def rollback_twophase( self, conn: Connection, xid: Any, is_prepared: bool ) -> None: """Intercept rollback_twophase() events. :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. """ def commit_twophase( self, conn: Connection, xid: Any, is_prepared: bool ) -> None: """Intercept commit_twophase() events. :param conn: :class:`_engine.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. """ class DialectEvents(event.Events[Dialect]): """event interface for execution-replacement functions. These events allow direct instrumentation and replacement of key dialect functions which interact with the DBAPI. .. note:: :class:`.DialectEvents` hooks should be considered **semi-public** and experimental. These hooks are not for general use and are only for those situations where intricate re-statement of DBAPI mechanics must be injected onto an existing dialect. For general-use statement-interception events, please use the :class:`_events.ConnectionEvents` interface. .. seealso:: :meth:`_events.ConnectionEvents.before_cursor_execute` :meth:`_events.ConnectionEvents.before_execute` :meth:`_events.ConnectionEvents.after_cursor_execute` :meth:`_events.ConnectionEvents.after_execute` .. versionadded:: 0.9.4 """ _target_class_doc = "SomeEngine" _dispatch_target = Dialect @classmethod def _listen( # type: ignore cls, event_key: event._EventKey[Dialect], *, retval: bool = False, **kw: Any, ) -> None: target = event_key.dispatch_target target._has_events = True event_key.base_listen() @classmethod def _accept_with( cls, target: Union[Engine, Type[Engine], Dialect, Type[Dialect]], identifier: str, ) -> Optional[Union[Dialect, Type[Dialect]]]: if isinstance(target, type): if issubclass(target, Engine): return Dialect elif issubclass(target, Dialect): return target elif isinstance(target, Engine): return target.dialect elif isinstance(target, Dialect): return target elif isinstance(target, Connection) and identifier == "handle_error": raise exc.InvalidRequestError( "The handle_error() event hook as of SQLAlchemy 2.0 is " "established on the Dialect, and may only be applied to the " "Engine as a whole or to a specific Dialect as a whole, " "not on a per-Connection basis." ) elif hasattr(target, "_no_async_engine_events"): target._no_async_engine_events() else: return None def handle_error( self, exception_context: ExceptionContext ) -> Optional[BaseException]: r"""Intercept all exceptions processed by the :class:`_engine.Dialect`, typically but not limited to those emitted within the scope of a :class:`_engine.Connection`. .. versionchanged:: 2.0 the :meth:`.DialectEvents.handle_error` event is moved to the :class:`.DialectEvents` class, moved from the :class:`.ConnectionEvents` class, so that it may also participate in the "pre ping" operation configured with the :paramref:`_sa.create_engine.pool_pre_ping` parameter. The event remains registered by using the :class:`_engine.Engine` as the event target, however note that using the :class:`_engine.Connection` as an event target for :meth:`.DialectEvents.handle_error` is no longer supported. This includes all exceptions emitted by the DBAPI as well as within SQLAlchemy's statement invocation process, including encoding errors and other statement validation errors. Other areas in which the event is invoked include transaction begin and end, result row fetching, cursor creation. Note that :meth:`.handle_error` may support new kinds of exceptions and new calling scenarios at *any time*. Code which uses this event must expect new calling patterns to be present in minor releases. To support the wide variety of members that correspond to an exception, as well as to allow extensibility of the event without backwards incompatibility, the sole argument received is an instance of :class:`.ExceptionContext`. This object contains data members representing detail about the exception. Use cases supported by this hook include: * read-only, low-level exception handling for logging and debugging purposes * Establishing whether a DBAPI connection error message indicates that the database connection needs to be reconnected, including for the "pre_ping" handler used by **some** dialects * Establishing or disabling whether a connection or the owning connection pool is invalidated or expired in response to a specific exception * exception re-writing The hook is called while the cursor from the failed operation (if any) is still open and accessible. Special cleanup operations can be called on this cursor; SQLAlchemy will attempt to close this cursor subsequent to this hook being invoked. As of SQLAlchemy 2.0, the "pre_ping" handler enabled using the :paramref:`_sa.create_engine.pool_pre_ping` parameter will also participate in the :meth:`.handle_error` process, **for those dialects that rely upon disconnect codes to detect database liveness**. Note that some dialects such as psycopg, psycopg2, and most MySQL dialects make use of a native ``ping()`` method supplied by the DBAPI which does not make use of disconnect codes. A handler function has two options for replacing the SQLAlchemy-constructed exception into one that is user defined. It can either raise this new exception directly, in which case all further event listeners are bypassed and the exception will be raised, after appropriate cleanup as taken place:: @event.listens_for(Engine, "handle_error") def handle_exception(context): if isinstance(context.original_exception, psycopg2.OperationalError) and \ "failed" in str(context.original_exception): raise MySpecialException("failed operation") .. warning:: Because the :meth:`_events.DialectEvents.handle_error` event specifically provides for exceptions to be re-thrown as the ultimate exception raised by the failed statement, **stack traces will be misleading** if the user-defined event handler itself fails and throws an unexpected exception; the stack trace may not illustrate the actual code line that failed! It is advised to code carefully here and use logging and/or inline debugging if unexpected exceptions are occurring. Alternatively, a "chained" style of event handling can be used, by configuring the handler with the ``retval=True`` modifier and returning the new exception instance from the function. In this case, event handling will continue onto the next handler. The "chained" exception is available using :attr:`.ExceptionContext.chained_exception`:: @event.listens_for(Engine, "handle_error", retval=True) def handle_exception(context): if context.chained_exception is not None and \ "special" in context.chained_exception.message: return MySpecialException("failed", cause=context.chained_exception) Handlers that return ``None`` may be used within the chain; when a handler returns ``None``, the previous exception instance, if any, is maintained as the current exception that is passed onto the next handler. When a custom exception is raised or returned, SQLAlchemy raises this new exception as-is, it is not wrapped by any SQLAlchemy object. If the exception is not a subclass of :class:`sqlalchemy.exc.StatementError`, certain features may not be available; currently this includes the ORM's feature of adding a detail hint about "autoflush" to exceptions raised within the autoflush process. :param context: an :class:`.ExceptionContext` object. See this class for details on all available members. .. seealso:: :ref:`pool_new_disconnect_codes` """ def do_connect( self, dialect: Dialect, conn_rec: ConnectionPoolEntry, cargs: Tuple[Any, ...], cparams: Dict[str, Any], ) -> Optional[DBAPIConnection]: """Receive connection arguments before a connection is made. This event is useful in that it allows the handler to manipulate the cargs and/or cparams collections that control how the DBAPI ``connect()`` function will be called. ``cargs`` will always be a Python list that can be mutated in-place, and ``cparams`` a Python dictionary that may also be mutated:: e = create_engine("postgresql+psycopg2://user@host/dbname") @event.listens_for(e, 'do_connect') def receive_do_connect(dialect, conn_rec, cargs, cparams): cparams["password"] = "some_password" The event hook may also be used to override the call to ``connect()`` entirely, by returning a non-``None`` DBAPI connection object:: e = create_engine("postgresql+psycopg2://user@host/dbname") @event.listens_for(e, 'do_connect') def receive_do_connect(dialect, conn_rec, cargs, cparams): return psycopg2.connect(*cargs, **cparams) .. versionadded:: 1.0.3 .. seealso:: :ref:`custom_dbapi_args` """ def do_executemany( self, cursor: DBAPICursor, statement: str, parameters: _DBAPIMultiExecuteParams, context: ExecutionContext, ) -> Optional[Literal[True]]: """Receive a cursor to have executemany() called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """ def do_execute_no_params( self, cursor: DBAPICursor, statement: str, context: ExecutionContext ) -> Optional[Literal[True]]: """Receive a cursor to have execute() with no parameters called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """ def do_execute( self, cursor: DBAPICursor, statement: str, parameters: _DBAPISingleExecuteParams, context: ExecutionContext, ) -> Optional[Literal[True]]: """Receive a cursor to have execute() called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """ def do_setinputsizes( self, inputsizes: Dict[BindParameter[Any], Any], cursor: DBAPICursor, statement: str, parameters: _DBAPIAnyExecuteParams, context: ExecutionContext, ) -> None: """Receive the setinputsizes dictionary for possible modification. This event is emitted in the case where the dialect makes use of the DBAPI ``cursor.setinputsizes()`` method which passes information about parameter binding for a particular statement. The given ``inputsizes`` dictionary will contain :class:`.BindParameter` objects as keys, linked to DBAPI-specific type objects as values; for parameters that are not bound, they are added to the dictionary with ``None`` as the value, which means the parameter will not be included in the ultimate setinputsizes call. The event may be used to inspect and/or log the datatypes that are being bound, as well as to modify the dictionary in place. Parameters can be added, modified, or removed from this dictionary. Callers will typically want to inspect the :attr:`.BindParameter.type` attribute of the given bind objects in order to make decisions about the DBAPI object. After the event, the ``inputsizes`` dictionary is converted into an appropriate datastructure to be passed to ``cursor.setinputsizes``; either a list for a positional bound parameter execution style, or a dictionary of string parameter keys to DBAPI type objects for a named bound parameter execution style. The setinputsizes hook overall is only used for dialects which include the flag ``use_setinputsizes=True``. Dialects which use this include cx_Oracle, pg8000, asyncpg, and pyodbc dialects. .. note:: For use with pyodbc, the ``use_setinputsizes`` flag must be passed to the dialect, e.g.:: create_engine("mssql+pyodbc://...", use_setinputsizes=True) .. seealso:: :ref:`mssql_pyodbc_setinputsizes` .. versionadded:: 1.2.9 .. seealso:: :ref:`cx_oracle_setinputsizes` """ pass
mit
c2fb7388f32ef720518a5f90e68b7d70
37.761955
93
0.633201
4.735783
false
false
false
false
sqlalchemy/sqlalchemy
examples/space_invaders/space_invaders.py
2
19712
import curses import logging import random import re import textwrap import time from sqlalchemy import Column from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import joinedload from sqlalchemy.orm import relationship from sqlalchemy.orm import Session logging.basicConfig( filename="space_invaders.log", format="%(asctime)s,%(msecs)03d %(levelname)-5.5s %(message)s", ) logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) Base = declarative_base() WINDOW_LEFT = 10 WINDOW_TOP = 2 WINDOW_WIDTH = 70 WINDOW_HEIGHT = 34 VERT_PADDING = 2 HORIZ_PADDING = 5 ENEMY_VERT_SPACING = 4 MAX_X = WINDOW_WIDTH - HORIZ_PADDING MAX_Y = WINDOW_HEIGHT - VERT_PADDING LEFT_KEY = ord("j") RIGHT_KEY = ord("l") FIRE_KEY = ord(" ") PAUSE_KEY = ord("p") COLOR_MAP = { "K": curses.COLOR_BLACK, "B": curses.COLOR_BLUE, "C": curses.COLOR_CYAN, "G": curses.COLOR_GREEN, "M": curses.COLOR_MAGENTA, "R": curses.COLOR_RED, "W": curses.COLOR_WHITE, "Y": curses.COLOR_YELLOW, } class Glyph(Base): """Describe a "glyph", a graphical element to be painted on the screen. """ __tablename__ = "glyph" id = Column(Integer, primary_key=True) name = Column(String) type = Column(String) width = Column(Integer) height = Column(Integer) data = Column(String) alt_data = Column(String) __mapper_args__ = {"polymorphic_on": type} def __init__(self, name, img, alt=None): self.name = name self.data, self.width, self.height = self._encode_glyph(img) if alt is not None: self.alt_data, alt_w, alt_h = self._encode_glyph(alt) def _encode_glyph(self, img): """Receive a textual description of the glyph and encode into a format understood by GlyphCoordinate.render(). """ img = re.sub(r"^\n", "", textwrap.dedent(img)) color = "W" lines = [line.rstrip() for line in img.split("\n")] data = [] for line in lines: render_line = [] line = list(line) while line: char = line.pop(0) if char == "#": color = line.pop(0) continue render_line.append((color, char)) data.append(render_line) width = max([len(rl) for rl in data]) data = "".join( "".join("%s%s" % (color, char) for color, char in render_line) + ("W " * (width - len(render_line))) for render_line in data ) return data, width, len(lines) def glyph_for_state(self, coord, state): """Return the appropriate data representation for this Glyph, based on the current coordinates and state. Subclasses may override this to provide animations. """ return self.data class GlyphCoordinate(Base): """Describe a glyph rendered at a certain x, y coordinate. The GlyphCoordinate may also include optional values such as the tick at time of render, a label, and a score value. """ __tablename__ = "glyph_coordinate" id = Column(Integer, primary_key=True) glyph_id = Column(Integer, ForeignKey("glyph.id")) x = Column(Integer) y = Column(Integer) tick = Column(Integer) label = Column(String) score = Column(Integer) glyph = relationship(Glyph, innerjoin=True) def __init__( self, session, glyph_name, x, y, tick=None, label=None, score=None ): self.glyph = session.query(Glyph).filter_by(name=glyph_name).one() self.x = x self.y = y self.tick = tick self.label = label self.score = score session.add(self) def render(self, window, state): """Render the Glyph at this position.""" col = 0 row = 0 glyph = self.glyph data = glyph.glyph_for_state(self, state) for color, char in [ (data[i], data[i + 1]) for i in range(0, len(data), 2) ]: x = self.x + col y = self.y + row if 0 <= x <= MAX_X and 0 <= y <= MAX_Y: window.addstr( y + VERT_PADDING, x + HORIZ_PADDING, char, _COLOR_PAIRS[color], ) col += 1 if col == glyph.width: col = 0 row += 1 if self.label: self._render_label(window, False) def _render_label(self, window, blank): label = self.label if not blank else " " * len(self.label) if self.x + self.width + len(self.label) < MAX_X: window.addstr(self.y, self.x + self.width, label) else: window.addstr(self.y, self.x - len(self.label), label) def blank(self, window): """Render a blank box for this glyph's position and size.""" glyph = self.glyph x = min(max(self.x, 0), MAX_X) width = min(glyph.width, MAX_X - x) or 1 for y_a in range(self.y, self.y + glyph.height): y = y_a window.addstr(y + VERT_PADDING, x + HORIZ_PADDING, " " * width) if self.label: self._render_label(window, True) @hybrid_property def width(self): return self.glyph.width @width.expression def width(cls): return Glyph.width @hybrid_property def height(self): return self.glyph.height @height.expression def height(cls): return Glyph.height @hybrid_property def bottom_bound(self): return self.y + self.height >= MAX_Y @hybrid_property def top_bound(self): return self.y <= 0 @hybrid_property def left_bound(self): return self.x <= 0 @hybrid_property def right_bound(self): return self.x + self.width >= MAX_X @hybrid_property def right_edge_bound(self): return self.x > MAX_X @hybrid_method def intersects(self, other): """Return True if this GlyphCoordinate intersects with the given GlyphCoordinate.""" return ~( (self.x + self.width < other.x) | (self.x > other.x + other.width) ) & ~( (self.y + self.height < other.y) | (self.y > other.y + other.height) ) class EnemyGlyph(Glyph): """Describe an enemy.""" __mapper_args__ = {"polymorphic_identity": "enemy"} class ArmyGlyph(EnemyGlyph): """Describe an enemy that's part of the "army".""" __mapper_args__ = {"polymorphic_identity": "army"} def glyph_for_state(self, coord, state): if state["flip"]: return self.alt_data else: return self.data class SaucerGlyph(EnemyGlyph): """Describe the enemy saucer flying overhead.""" __mapper_args__ = {"polymorphic_identity": "saucer"} def glyph_for_state(self, coord, state): if state["flip"] == 0: return self.alt_data else: return self.data class MessageGlyph(Glyph): """Describe a glyph for displaying a message.""" __mapper_args__ = {"polymorphic_identity": "message"} class PlayerGlyph(Glyph): """Describe a glyph representing the player.""" __mapper_args__ = {"polymorphic_identity": "player"} class MissileGlyph(Glyph): """Describe a glyph representing a missile.""" __mapper_args__ = {"polymorphic_identity": "missile"} class SplatGlyph(Glyph): """Describe a glyph representing a "splat".""" __mapper_args__ = {"polymorphic_identity": "splat"} def glyph_for_state(self, coord, state): age = state["tick"] - coord.tick if age > 5: return self.alt_data else: return self.data def init_glyph(session): """Create the glyphs used during play.""" enemy1 = ArmyGlyph( "enemy1", """ #W-#B^#R-#B^#W- #G| | """, """ #W>#B^#R-#B^#W< #G^ ^ """, ) enemy2 = ArmyGlyph( "enemy2", """ #W*** #R<#C~~~#R> """, """ #W@@@ #R<#C---#R> """, ) enemy3 = ArmyGlyph( "enemy3", """ #Y((--)) #M-~-~-~ """, """ #Y[[--]] #M~-~-~- """, ) saucer = SaucerGlyph( "saucer", """#R~#Y^#R~#G<<((=#WOO#G=))>>""", """#Y^#R~#Y^#G<<((=#WOO#G=))>>""", ) splat1 = SplatGlyph( "splat1", """ #WVVVVV #W> #R*** #W< #W^^^^^ """, """ #M| #M- #Y+++ #M- #M| """, ) ship = PlayerGlyph( "ship", """ #Y^ #G===== """, ) missile = MissileGlyph( "missile", """ | """, ) start = MessageGlyph( "start_message", "J = move left; L = move right; SPACE = fire\n" " #GPress any key to start", ) lose = MessageGlyph("lose_message", "#YY O U L O S E ! ! !") win = MessageGlyph("win_message", "#RL E V E L C L E A R E D ! ! !") paused = MessageGlyph( "pause_message", "#WP A U S E D\n#GPress P to continue" ) session.add_all( [ enemy1, enemy2, enemy3, ship, saucer, missile, start, lose, win, paused, splat1, ] ) def setup_curses(): """Setup terminal/curses state.""" window = curses.initscr() curses.noecho() window = curses.newwin( WINDOW_HEIGHT + (VERT_PADDING * 2), WINDOW_WIDTH + (HORIZ_PADDING * 2), WINDOW_TOP - VERT_PADDING, WINDOW_LEFT - HORIZ_PADDING, ) curses.start_color() global _COLOR_PAIRS _COLOR_PAIRS = {} for i, (k, v) in enumerate(COLOR_MAP.items(), 1): curses.init_pair(i, v, curses.COLOR_BLACK) _COLOR_PAIRS[k] = curses.color_pair(i) return window def init_positions(session): """Establish a new field of play. This generates GlyphCoordinate objects and persists them to the database. """ # delete all existing coordinates session.query(GlyphCoordinate).delete() session.add( GlyphCoordinate( session, "ship", WINDOW_WIDTH // 2 - 2, WINDOW_HEIGHT - 4 ) ) arrangement = ( ("enemy3", 50), ("enemy2", 25), ("enemy1", 10), ("enemy2", 25), ("enemy1", 10), ) for (ship_vert, (etype, score)) in zip( range(5, 30, ENEMY_VERT_SPACING), arrangement ): for ship_horiz in range(0, 50, 10): session.add( GlyphCoordinate( session, etype, ship_horiz, ship_vert, score=score ) ) def draw(session, window, state): """Load all current GlyphCoordinate objects from the database and render. """ for gcoord in session.query(GlyphCoordinate).options( joinedload(GlyphCoordinate.glyph) ): gcoord.render(window, state) window.addstr(1, WINDOW_WIDTH - 5, "Score: %.4d" % state["score"]) window.move(0, 0) window.refresh() def check_win(session, state): """Return the number of army glyphs remaining - the player wins if this is zero.""" return ( session.query(func.count(GlyphCoordinate.id)) .join(GlyphCoordinate.glyph.of_type(ArmyGlyph)) .scalar() ) def check_lose(session, state): """Return the number of army glyphs either colliding with the player or hitting the bottom of the screen. The player loses if this is non-zero.""" player = state["player"] return ( session.query(GlyphCoordinate) .join(GlyphCoordinate.glyph.of_type(ArmyGlyph)) .filter( GlyphCoordinate.intersects(player) | GlyphCoordinate.bottom_bound ) .count() ) def render_message(session, window, msg, x, y): """Render a message glyph. Clears the area beneath the message first and assumes the display will be paused afterwards. """ # create message box msg = GlyphCoordinate(session, msg, x, y) # clear existing glyphs which intersect for gly in ( session.query(GlyphCoordinate) .join(GlyphCoordinate.glyph) .filter(GlyphCoordinate.intersects(msg)) ): gly.blank(window) # render msg.render(window, {}) window.refresh() return msg def win(session, window, state): """Handle the win case.""" render_message(session, window, "win_message", 15, 15) time.sleep(2) start(session, window, state, True) def lose(session, window, state): """Handle the lose case.""" render_message(session, window, "lose_message", 15, 15) time.sleep(2) start(session, window, state) def pause(session, window, state): """Pause the game.""" msg = render_message(session, window, "pause_message", 15, 15) prompt(window) msg.blank(window) session.delete(msg) def prompt(window): """Display a prompt, quashing any keystrokes which might have remained.""" window.move(0, 0) window.nodelay(1) window.getch() window.nodelay(0) window.getch() window.nodelay(1) def move_army(session, window, state): """Update the army position based on the current size of the field.""" speed = 30 // 25 * state["num_enemies"] flip = (state["tick"] % speed) == 0 if not flip: return else: state["flip"] = not state["flip"] x_slide = 1 # get the lower/upper boundaries of the army # along the X axis. min_x, max_x = ( session.query( func.min(GlyphCoordinate.x), func.max(GlyphCoordinate.x + GlyphCoordinate.width), ) .join(GlyphCoordinate.glyph.of_type(ArmyGlyph)) .first() ) if min_x is None or max_x is None: # no enemies return direction = state["army_direction"] move_y = False if direction == 0 and max_x + x_slide >= MAX_X: direction = state["army_direction"] = 1 move_y = True elif direction == 1 and min_x - x_slide <= 0: direction = state["army_direction"] = 0 move_y = True for enemy_g in session.query(GlyphCoordinate).join( GlyphCoordinate.glyph.of_type(ArmyGlyph) ): enemy_g.blank(window) if move_y: enemy_g.y += 1 elif direction == 0: enemy_g.x += x_slide elif direction == 1: enemy_g.x -= x_slide def move_player(session, window, state): """Receive player input and adjust state.""" ch = window.getch() if ch not in (LEFT_KEY, RIGHT_KEY, FIRE_KEY, PAUSE_KEY): return elif ch == PAUSE_KEY: pause(session, window, state) return player = state["player"] if ch == RIGHT_KEY and not player.right_bound: player.blank(window) player.x += 1 elif ch == LEFT_KEY and not player.left_bound: player.blank(window) player.x -= 1 elif ch == FIRE_KEY and state["missile"] is None: state["missile"] = GlyphCoordinate( session, "missile", player.x + 3, player.y - 1 ) def move_missile(session, window, state): """Update the status of the current missile, if any.""" if state["missile"] is None or state["tick"] % 2 != 0: return missile = state["missile"] # locate enemy glyphs which intersect with the # missile's current position; i.e. a hit glyph = ( session.query(GlyphCoordinate) .join(GlyphCoordinate.glyph.of_type(EnemyGlyph)) .filter(GlyphCoordinate.intersects(missile)) .first() ) missile.blank(window) if glyph or missile.top_bound: # missile is done session.delete(missile) state["missile"] = None if glyph: # score! score(session, window, state, glyph) else: # move missile up one character. missile.y -= 1 def move_saucer(session, window, state): """Update the status of the saucer.""" saucer_interval = 500 saucer_speed_interval = 4 if state["saucer"] is None and state["tick"] % saucer_interval != 0: return if state["saucer"] is None: state["saucer"] = saucer = GlyphCoordinate( session, "saucer", -6, 1, score=random.randrange(100, 600, 100) ) elif state["tick"] % saucer_speed_interval == 0: saucer = state["saucer"] saucer.blank(window) saucer.x += 1 if saucer.right_edge_bound: session.delete(saucer) state["saucer"] = None def update_splat(session, window, state): """Render splat animations.""" for splat in session.query(GlyphCoordinate).join( GlyphCoordinate.glyph.of_type(SplatGlyph) ): age = state["tick"] - splat.tick if age > 10: splat.blank(window) session.delete(splat) else: splat.render(window, state) def score(session, window, state, glyph): """Process a glyph intersecting with a missile.""" glyph.blank(window) session.delete(glyph) if state["saucer"] is glyph: state["saucer"] = None state["score"] += glyph.score # render a splat ! GlyphCoordinate( session, "splat1", glyph.x, glyph.y, tick=state["tick"], label=str(glyph.score), ) def update_state(session, window, state): """Update all state for each game tick.""" num_enemies = state["num_enemies"] = check_win(session, state) if num_enemies == 0: win(session, window, state) elif check_lose(session, state): lose(session, window, state) else: # update the tick counter. state["tick"] += 1 move_player(session, window, state) move_missile(session, window, state) move_army(session, window, state) move_saucer(session, window, state) update_splat(session, window, state) def start(session, window, state, continue_=False): """Start a new field of play.""" render_message(session, window, "start_message", 15, 20) prompt(window) init_positions(session) player = ( session.query(GlyphCoordinate) .join(GlyphCoordinate.glyph.of_type(PlayerGlyph)) .one() ) state.update( { "field_pos": 0, "alt": False, "tick": 0, "missile": None, "saucer": None, "player": player, "army_direction": 0, "flip": False, } ) if not continue_: state["score"] = 0 window.clear() window.box() draw(session, window, state) def main(): """Initialize the database and establish the game loop.""" e = create_engine("sqlite://") Base.metadata.create_all(e) session = Session(e) init_glyph(session) session.commit() window = setup_curses() state = {} start(session, window, state) while True: update_state(session, window, state) draw(session, window, state) time.sleep(0.01) if __name__ == "__main__": main()
mit
d5d1e5fbe4dd34df4b8105e148391e8a
23.983523
78
0.555956
3.589221
false
false
false
false
sqlalchemy/sqlalchemy
test/ext/mypy/plain_files/mapped_column.py
2
3006
from typing import Optional from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column class Base(DeclarativeBase): pass class X(Base): __tablename__ = "x" # these are fine - pk, column is not null, have the attribute be # non-optional, fine id: Mapped[int] = mapped_column(primary_key=True) int_id: Mapped[int] = mapped_column(Integer, primary_key=True) # but this is also "fine" because the developer may wish to have the object # in a pending state with None for the id for some period of time. # "primary_key=True" will still be interpreted correctly in DDL err_int_id: Mapped[Optional[int]] = mapped_column( Integer, primary_key=True ) # also fine, X(err_int_id_name) is None when you first make the # object err_int_id_name: Mapped[Optional[int]] = mapped_column( "err_int_id_name", Integer, primary_key=True ) id_name: Mapped[int] = mapped_column("id_name", primary_key=True) int_id_name: Mapped[int] = mapped_column( "int_id_name", Integer, primary_key=True ) a: Mapped[str] = mapped_column() b: Mapped[Optional[str]] = mapped_column() # this can't be detected because we don't know the type c: Mapped[str] = mapped_column(nullable=True) d: Mapped[str] = mapped_column(nullable=False) e: Mapped[Optional[str]] = mapped_column(nullable=True) f: Mapped[Optional[str]] = mapped_column(nullable=False) g: Mapped[str] = mapped_column(String) h: Mapped[Optional[str]] = mapped_column(String) # this probably is wrong. however at the moment it seems better to # decouple the right hand arguments from declaring things about the # left side since it mostly doesn't work in any case. i: Mapped[str] = mapped_column(String, nullable=True) j: Mapped[str] = mapped_column(String, nullable=False) k: Mapped[Optional[str]] = mapped_column(String, nullable=True) l: Mapped[Optional[str]] = mapped_column(String, nullable=False) a_name: Mapped[str] = mapped_column("a_name") b_name: Mapped[Optional[str]] = mapped_column("b_name") c_name: Mapped[str] = mapped_column("c_name", nullable=True) d_name: Mapped[str] = mapped_column("d_name", nullable=False) e_name: Mapped[Optional[str]] = mapped_column("e_name", nullable=True) f_name: Mapped[Optional[str]] = mapped_column("f_name", nullable=False) g_name: Mapped[str] = mapped_column("g_name", String) h_name: Mapped[Optional[str]] = mapped_column("h_name", String) i_name: Mapped[str] = mapped_column("i_name", String, nullable=True) j_name: Mapped[str] = mapped_column("j_name", String, nullable=False) k_name: Mapped[Optional[str]] = mapped_column( "k_name", String, nullable=True ) l_name: Mapped[Optional[str]] = mapped_column( "l_name", String, nullable=False, )
mit
7ca5ef9a6d299748811195474f3cb142
32.4
79
0.670659
3.328904
false
false
false
false
sqlalchemy/sqlalchemy
lib/sqlalchemy/orm/identity.py
2
9249
# orm/identity.py # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: https://www.opensource.org/licenses/mit-license.php from __future__ import annotations from typing import Any from typing import cast from typing import Dict from typing import Iterable from typing import Iterator from typing import List from typing import NoReturn from typing import Optional from typing import Set from typing import Tuple from typing import TYPE_CHECKING from typing import TypeVar import weakref from . import util as orm_util from .. import exc as sa_exc if TYPE_CHECKING: from ._typing import _IdentityKeyType from .state import InstanceState _T = TypeVar("_T", bound=Any) _O = TypeVar("_O", bound=object) class IdentityMap: _wr: weakref.ref[IdentityMap] _dict: Dict[_IdentityKeyType[Any], Any] _modified: Set[InstanceState[Any]] def __init__(self) -> None: self._dict = {} self._modified = set() self._wr = weakref.ref(self) def _kill(self) -> None: self._add_unpresent = _killed # type: ignore def all_states(self) -> List[InstanceState[Any]]: raise NotImplementedError() def contains_state(self, state: InstanceState[Any]) -> bool: raise NotImplementedError() def __contains__(self, key: _IdentityKeyType[Any]) -> bool: raise NotImplementedError() def safe_discard(self, state: InstanceState[Any]) -> None: raise NotImplementedError() def __getitem__(self, key: _IdentityKeyType[_O]) -> _O: raise NotImplementedError() def get( self, key: _IdentityKeyType[_O], default: Optional[_O] = None ) -> Optional[_O]: raise NotImplementedError() def fast_get_state( self, key: _IdentityKeyType[_O] ) -> Optional[InstanceState[_O]]: raise NotImplementedError() def keys(self) -> Iterable[_IdentityKeyType[Any]]: return self._dict.keys() def values(self) -> Iterable[object]: raise NotImplementedError() def replace(self, state: InstanceState[_O]) -> Optional[InstanceState[_O]]: raise NotImplementedError() def add(self, state: InstanceState[Any]) -> bool: raise NotImplementedError() def _fast_discard(self, state: InstanceState[Any]) -> None: raise NotImplementedError() def _add_unpresent( self, state: InstanceState[Any], key: _IdentityKeyType[Any] ) -> None: """optional inlined form of add() which can assume item isn't present in the map""" self.add(state) def _manage_incoming_state(self, state: InstanceState[Any]) -> None: state._instance_dict = self._wr if state.modified: self._modified.add(state) def _manage_removed_state(self, state: InstanceState[Any]) -> None: del state._instance_dict if state.modified: self._modified.discard(state) def _dirty_states(self) -> Set[InstanceState[Any]]: return self._modified def check_modified(self) -> bool: """return True if any InstanceStates present have been marked as 'modified'. """ return bool(self._modified) def has_key(self, key: _IdentityKeyType[Any]) -> bool: return key in self def __len__(self) -> int: return len(self._dict) class WeakInstanceDict(IdentityMap): _dict: Dict[_IdentityKeyType[Any], InstanceState[Any]] def __getitem__(self, key: _IdentityKeyType[_O]) -> _O: state = cast("InstanceState[_O]", self._dict[key]) o = state.obj() if o is None: raise KeyError(key) return o def __contains__(self, key: _IdentityKeyType[Any]) -> bool: try: if key in self._dict: state = self._dict[key] o = state.obj() else: return False except KeyError: return False else: return o is not None def contains_state(self, state: InstanceState[Any]) -> bool: if state.key in self._dict: if TYPE_CHECKING: assert state.key is not None try: return self._dict[state.key] is state except KeyError: return False else: return False def replace( self, state: InstanceState[Any] ) -> Optional[InstanceState[Any]]: assert state.key is not None if state.key in self._dict: try: existing = existing_non_none = self._dict[state.key] except KeyError: # catch gc removed the key after we just checked for it existing = None else: if existing_non_none is not state: self._manage_removed_state(existing_non_none) else: return None else: existing = None self._dict[state.key] = state self._manage_incoming_state(state) return existing def add(self, state: InstanceState[Any]) -> bool: key = state.key assert key is not None # inline of self.__contains__ if key in self._dict: try: existing_state = self._dict[key] except KeyError: # catch gc removed the key after we just checked for it pass else: if existing_state is not state: o = existing_state.obj() if o is not None: raise sa_exc.InvalidRequestError( "Can't attach instance " "%s; another instance with key %s is already " "present in this session." % (orm_util.state_str(state), state.key) ) else: return False self._dict[key] = state self._manage_incoming_state(state) return True def _add_unpresent( self, state: InstanceState[Any], key: _IdentityKeyType[Any] ) -> None: # inlined form of add() called by loading.py self._dict[key] = state state._instance_dict = self._wr def fast_get_state( self, key: _IdentityKeyType[_O] ) -> Optional[InstanceState[_O]]: return self._dict.get(key) def get( self, key: _IdentityKeyType[_O], default: Optional[_O] = None ) -> Optional[_O]: if key not in self._dict: return default try: state = cast("InstanceState[_O]", self._dict[key]) except KeyError: # catch gc removed the key after we just checked for it return default else: o = state.obj() if o is None: return default return o def items(self) -> List[Tuple[_IdentityKeyType[Any], InstanceState[Any]]]: values = self.all_states() result = [] for state in values: value = state.obj() key = state.key assert key is not None if value is not None: result.append((key, value)) return result def values(self) -> List[object]: values = self.all_states() result = [] for state in values: value = state.obj() if value is not None: result.append(value) return result def __iter__(self) -> Iterator[_IdentityKeyType[Any]]: return iter(self.keys()) def all_states(self) -> List[InstanceState[Any]]: return list(self._dict.values()) def _fast_discard(self, state: InstanceState[Any]) -> None: # used by InstanceState for state being # GC'ed, inlines _managed_removed_state key = state.key assert key is not None try: st = self._dict[key] except KeyError: # catch gc removed the key after we just checked for it pass else: if st is state: self._dict.pop(key, None) def discard(self, state: InstanceState[Any]) -> None: self.safe_discard(state) def safe_discard(self, state: InstanceState[Any]) -> None: key = state.key if key in self._dict: assert key is not None try: st = self._dict[key] except KeyError: # catch gc removed the key after we just checked for it pass else: if st is state: self._dict.pop(key, None) self._manage_removed_state(state) def _killed(state: InstanceState[Any], key: _IdentityKeyType[Any]) -> NoReturn: # external function to avoid creating cycles when assigned to # the IdentityMap raise sa_exc.InvalidRequestError( "Object %s cannot be converted to 'persistent' state, as this " "identity map is no longer valid. Has the owning Session " "been closed?" % orm_util.state_str(state), code="lkrp", )
mit
89a19831a5bcbb7efc58cc7d7d558363
29.625828
79
0.56644
4.315912
false
false
false
false
sqlalchemy/sqlalchemy
test/ext/asyncio/test_scoping_py3k.py
2
2258
import sqlalchemy as sa from sqlalchemy import func from sqlalchemy import select from sqlalchemy.ext.asyncio import async_scoped_session from sqlalchemy.ext.asyncio import AsyncSession as _AsyncSession from sqlalchemy.orm import sessionmaker from sqlalchemy.testing import async_test from sqlalchemy.testing import eq_ from sqlalchemy.testing import is_ from .test_session_py3k import AsyncFixture class AsyncScopedSessionTest(AsyncFixture): @async_test async def test_basic(self, async_engine): from asyncio import current_task AsyncSession = async_scoped_session( sa.orm.sessionmaker(async_engine, class_=_AsyncSession), scopefunc=current_task, ) some_async_session = AsyncSession() some_other_async_session = AsyncSession() is_(some_async_session, some_other_async_session) is_(some_async_session.bind, async_engine) User = self.classes.User async with AsyncSession.begin(): user_name = "scoped_async_session_u1" u1 = User(name=user_name) AsyncSession.add(u1) await AsyncSession.flush() conn = await AsyncSession.connection() stmt = select(func.count(User.id)).where(User.name == user_name) eq_(await AsyncSession.scalar(stmt), 1) await AsyncSession.delete(u1) await AsyncSession.flush() eq_(await conn.scalar(stmt), 0) def test_attributes(self, async_engine): from asyncio import current_task expected = [ name for cls in _AsyncSession.mro() for name in vars(cls) if not name.startswith("_") ] ignore_list = { "dispatch", "sync_session_class", "run_sync", "get_transaction", "get_nested_transaction", "in_transaction", "in_nested_transaction", } SM = async_scoped_session( sessionmaker(async_engine, class_=_AsyncSession), current_task ) missing = [ name for name in expected if not hasattr(SM, name) and name not in ignore_list ] eq_(missing, [])
mit
5aec6271268531bf630a27d8d536412a
28.324675
76
0.605403
4.342308
false
true
false
false
datactive/bigbang
bigbang/visualisation/stackedareachart.py
1
2061
from typing import Dict, List, Optional, Tuple, Union import numpy as np import pylab from colour import Color from pylab import cm import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.lines as mlines from matplotlib.pyplot import figure from bigbang.visualisation import utils def get_ylabels(data) -> List[str]: ylabels = list( set([ykey for ydic in data.values() for ykey in ydic.keys()]) ) return ylabels def data_transformation( idata: dict, ylabels: Optional[List[str]] = None, percentage: bool = False, ) -> np.ndarray: """ Parameters ---------- idata : ylabels : percentage : Returns ------- odata : array with the format (# of ylabels, # of xlabels) """ if ylabels is None: # collect all ylabels ylabels = get_ylabels(idata) # create numpy array and fill sparse matrix odata = np.zeros((len(ylabels), len(idata.keys()))) for iy, ylab in enumerate(ylabels): for ix, ydic in enumerate(idata.values()): if ylab in list(ydic.keys()): odata[iy, ix] = ydic[ylab] if percentage: odata = odata / np.sum(odata, axis=0) return odata def stacked_area_chart( data: dict, ax: mpl.axes, domains_in_focus: Optional[list] = None, percentage: bool = False, colormap: Optional[mpl.colors.LinearSegmentedColormap] = None, color_default: Optional[np.array] = None, ): """ Parameters ---------- data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}} domains_in_focus : percentage : """ x = list(data.keys()) y = data_transformation(data, percentage) ylabels = get_ylabels(data) colors = utils.create_color_palette( ylabels, domains_in_focus, colormap, include_dof=True, return_dict=False, ) ax.stackplot( x, y, colors=colors, ) ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(y), np.max(y)) return ax
mit
9e4db30e7edd9a276bcdd3f6afdc2760
23.535714
82
0.609413
3.52911
false
false
false
false
ccxt/ccxt
examples/py/async-kucoin-rate-limit.py
1
1252
# -*- coding: utf-8 -*- import os import sys from asyncio import run root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 print('CCXT Version:', ccxt.__version__) async def main(): exchange = ccxt.kucoin() markets = await exchange.load_markets() i = 0 while True: try: symbol = 'BTC/USDT' timeframe = '5m' since = None limit = 1000 ohlcvs = await exchange.fetch_ohlcv(symbol, timeframe, since, limit) now = exchange.milliseconds() datetime = exchange.iso8601(now) print(datetime, i, 'fetched', len(ohlcvs), symbol, timeframe, 'candles', 'from', exchange.iso8601(ohlcvs[0][0]), 'to', exchange.iso8601(ohlcvs[len(ohlcvs)-1][0])) except ccxt.RateLimitExceeded as e: now = exchange.milliseconds() datetime = exchange.iso8601(now) print(datetime, i, type(e).__name__, str(e)) await exchange.sleep(10000) except Exception as e: print(type(e).__name__, str(e)) raise e i += 1 run (main())
mit
55ea00aa2e36315c160c14930c40b63c
28.116279
84
0.563898
3.546742
false
false
false
false
ccxt/ccxt
python/ccxt/hitbtc.py
1
61606
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import BadSymbol from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import RequestTimeout from ccxt.base.decimal_to_precision import TRUNCATE from ccxt.base.decimal_to_precision import TICK_SIZE from ccxt.base.precise import Precise class hitbtc(Exchange): def describe(self): return self.deep_extend(super(hitbtc, self).describe(), { 'id': 'hitbtc', 'name': 'HitBTC', 'countries': ['HK'], # 300 requests per second => 1000ms / 300 = 3.333ms between requests on average(Trading) # 100 requests per second =>( 1000ms / rateLimit ) / 100 => cost = 3.0003(Market Data) # 20 requests per second =>( 1000ms / rateLimit ) / 20 => cost = 15.0015(Other Requests) 'rateLimit': 3.333, 'version': '2', 'pro': True, 'has': { 'CORS': None, 'spot': True, 'margin': False, 'swap': False, 'future': False, 'option': False, 'addMargin': False, 'cancelOrder': True, 'createDepositAddress': True, 'createOrder': True, 'createReduceOnlyOrder': False, 'editOrder': True, 'fetchBalance': True, 'fetchBorrowRate': False, 'fetchBorrowRateHistories': False, 'fetchBorrowRateHistory': False, 'fetchBorrowRates': False, 'fetchBorrowRatesPerSymbol': False, 'fetchClosedOrders': True, 'fetchCurrencies': True, 'fetchDepositAddress': True, 'fetchDeposits': None, 'fetchFundingHistory': False, 'fetchFundingRate': False, 'fetchFundingRateHistory': False, 'fetchFundingRates': False, 'fetchIndexOHLCV': False, 'fetchLeverage': False, 'fetchLeverageTiers': False, 'fetchMarkets': True, 'fetchMarkOHLCV': False, 'fetchMyTrades': True, 'fetchOHLCV': True, 'fetchOpenInterestHistory': False, 'fetchOpenOrder': True, 'fetchOpenOrders': True, 'fetchOrder': True, 'fetchOrderBook': True, 'fetchOrders': None, 'fetchOrderTrades': True, 'fetchPosition': False, 'fetchPositions': False, 'fetchPositionsRisk': False, 'fetchPremiumIndexOHLCV': False, 'fetchTicker': True, 'fetchTickers': True, 'fetchTrades': True, 'fetchTradingFee': True, 'fetchTradingFees': False, 'fetchTransactions': True, 'fetchWithdrawals': None, 'reduceMargin': False, 'setLeverage': False, 'setMarginMode': False, 'setPositionMode': False, 'transfer': True, 'withdraw': True, }, 'timeframes': { '1m': 'M1', '3m': 'M3', '5m': 'M5', '15m': 'M15', '30m': 'M30', # default '1h': 'H1', '4h': 'H4', '1d': 'D1', '1w': 'D7', '1M': '1M', }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg', 'test': { 'public': 'https://api.demo.hitbtc.com', 'private': 'https://api.demo.hitbtc.com', }, 'api': { 'public': 'https://api.hitbtc.com', 'private': 'https://api.hitbtc.com', }, 'www': 'https://hitbtc.com', 'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466', 'doc': [ 'https://api.hitbtc.com/v2', ], 'fees': [ 'https://hitbtc.com/fees-and-limits', 'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits', ], }, 'api': { 'public': { 'get': { 'currency': 3, # Available Currencies 'currency/{currency}': 3, # Get currency info 'symbol': 3, # Available Currency Symbols 'symbol/{symbol}': 3, # Get symbol info 'ticker': 3, # Ticker list for all symbols 'ticker/{symbol}': 3, # Ticker for symbol 'trades': 3, 'trades/{symbol}': 3, # Trades 'orderbook': 3, 'orderbook/{symbol}': 3, # Orderbook 'candles': 3, 'candles/{symbol}': 3, # Candles }, }, 'private': { 'get': { 'trading/balance': 15.0015, # Get trading balance 'order': 15.0015, # List your current open orders 'order/{clientOrderId}': 15.0015, # Get a single order by clientOrderId 'trading/fee/all': 15.0015, # Get trading fee rate 'trading/fee/{symbol}': 15.0015, # Get trading fee rate 'margin/account': 15.0015, 'margin/account/{symbol}': 15.0015, 'margin/position': 15.0015, 'margin/position/{symbol}': 15.0015, 'margin/order': 15.0015, 'margin/order/{clientOrderId}': 15.0015, 'history/order': 15.0015, # Get historical orders 'history/trades': 15.0015, # Get historical trades 'history/order/{orderId}/trades': 15.0015, # Get historical trades by specified order 'account/balance': 15.0015, # Get main acccount balance 'account/crypto/address/{currency}': 15.0015, # Get current address 'account/crypto/addresses/{currency}': 15.0015, # Get last 10 deposit addresses for currency 'account/crypto/used-addresses/{currency}': 15.0015, # Get last 10 unique addresses used for withdraw by currency 'account/crypto/estimate-withdraw': 15.0015, 'account/crypto/is-mine/{address}': 15.0015, 'account/transactions': 15.0015, # Get account transactions 'account/transactions/{id}': 15.0015, # Get account transaction by id 'sub-acc': 15.0015, 'sub-acc/acl': 15.0015, 'sub-acc/balance/{subAccountUserID}': 15.0015, 'sub-acc/deposit-address/{subAccountUserId}/{currency}': 15.0015, }, 'post': { 'order': 1, # Create new order 'margin/order': 1, 'account/crypto/address/{currency}': 1, # Create new crypto deposit address 'account/crypto/withdraw': 1, # Withdraw crypto 'account/crypto/transfer-convert': 1, 'account/transfer': 1, # Transfer amount to trading account or to main account 'account/transfer/internal': 1, 'sub-acc/freeze': 1, 'sub-acc/activate': 1, 'sub-acc/transfer': 1, }, 'put': { 'order/{clientOrderId}': 1, # Create new order 'margin/account/{symbol}': 1, 'margin/order/{clientOrderId}': 1, 'account/crypto/withdraw/{id}': 1, # Commit crypto withdrawal 'sub-acc/acl/{subAccountUserId}': 1, }, 'delete': { 'order': 1, # Cancel all open orders 'order/{clientOrderId}': 1, # Cancel order 'margin/account': 1, 'margin/account/{symbol}': 1, 'margin/position': 1, 'margin/position/{symbol}': 1, 'margin/order': 1, 'margin/order/{clientOrderId}': 1, 'account/crypto/withdraw/{id}': 1, # Rollback crypto withdrawal }, # outdated? 'patch': { 'order/{clientOrderId}': 1, # Cancel Replace order }, }, }, 'precisionMode': TICK_SIZE, 'fees': { 'trading': { 'tierBased': False, 'percentage': True, 'maker': self.parse_number('0.001'), 'taker': self.parse_number('0.002'), }, }, 'options': { 'networks': { 'ETH': 'T20', 'ERC20': 'T20', 'TRX': 'TTRX', 'TRC20': 'TTRX', 'OMNI': '', }, 'defaultTimeInForce': 'FOK', 'accountsByType': { 'funding': 'bank', 'spot': 'exchange', }, 'fetchBalanceMethod': { 'account': 'account', 'bank': 'account', 'main': 'account', 'funding': 'account', 'exchange': 'trading', 'spot': 'trading', 'trade': 'trading', 'trading': 'trading', }, }, 'commonCurrencies': { 'AUTO': 'Cube', 'BCC': 'BCC', # initial symbol for Bitcoin Cash, now inactive 'BDP': 'BidiPass', 'BET': 'DAO.Casino', 'BIT': 'BitRewards', 'BOX': 'BOX Token', 'CPT': 'Cryptaur', # conflict with CPT = Contents Protocol https://github.com/ccxt/ccxt/issues/4920 and https://github.com/ccxt/ccxt/issues/6081 'GET': 'Themis', 'GMT': 'GMT Token', 'HSR': 'HC', 'IQ': 'IQ.Cash', 'LNC': 'LinkerCoin', 'PLA': 'PlayChip', 'PNT': 'Penta', 'SBTC': 'Super Bitcoin', 'STEPN': 'GMT', 'STX': 'STOX', 'TV': 'Tokenville', 'USD': 'USDT', 'XMT': 'MTL', 'XPNT': 'PNT', }, 'exceptions': { '504': RequestTimeout, # {"error":{"code":504,"message":"Gateway Timeout"}} '1002': AuthenticationError, # {"error":{"code":1002,"message":"Authorization failed","description":""}} '1003': PermissionDenied, # "Action is forbidden for self API key" '2010': InvalidOrder, # "Quantity not a valid number" '2001': BadSymbol, # "Symbol not found" '2011': InvalidOrder, # "Quantity too low" '2020': InvalidOrder, # "Price not a valid number" '20002': OrderNotFound, # canceling non-existent order '20001': InsufficientFunds, # {"error":{"code":20001,"message":"Insufficient funds","description":"Check that the funds are sufficient, given commissions"}} '20010': BadSymbol, # {"error":{"code":20010,"message":"Exchange temporary closed","description":"Exchange market for self symbol is temporary closed"}} '20045': InvalidOrder, # {"error":{"code":20045,"message":"Fat finger limit exceeded"}} }, }) def fee_to_precision(self, symbol, fee): return self.decimal_to_precision(fee, TRUNCATE, 0.00000001, TICK_SIZE) def fetch_markets(self, params={}): """ retrieves data on all markets for hitbtc :param dict params: extra parameters specific to the exchange api endpoint :returns [dict]: an array of objects representing market data """ response = self.publicGetSymbol(params) # # [ # { # "id":"BCNBTC", # "baseCurrency":"BCN", # "quoteCurrency":"BTC", # "quantityIncrement":"100", # "tickSize":"0.00000000001", # "takeLiquidityRate":"0.002", # "provideLiquidityRate":"0.001", # "feeCurrency":"BTC" # } # ] # result = [] for i in range(0, len(response)): market = response[i] id = self.safe_string(market, 'id') baseId = self.safe_string(market, 'baseCurrency') quoteId = self.safe_string(market, 'quoteCurrency') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) # bequant fix symbol = base + '/' + quote if id.find('_') >= 0: symbol = id lotString = self.safe_string(market, 'quantityIncrement') stepString = self.safe_string(market, 'tickSize') lot = self.parse_number(lotString) step = self.parse_number(stepString) feeCurrencyId = self.safe_string(market, 'feeCurrency') result.append(self.extend(self.fees['trading'], { 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'settle': None, 'baseId': baseId, 'quoteId': quoteId, 'settleId': None, 'type': 'spot', 'spot': True, 'margin': False, 'swap': False, 'future': False, 'option': False, 'active': True, 'contract': False, 'linear': None, 'inverse': None, 'taker': self.safe_number(market, 'takeLiquidityRate'), 'maker': self.safe_number(market, 'provideLiquidityRate'), 'contractSize': None, 'expiry': None, 'expiryDatetime': None, 'strike': None, 'optionType': None, 'feeCurrency': self.safe_currency_code(feeCurrencyId), 'precision': { 'amount': lot, 'price': step, }, 'limits': { 'leverage': { 'min': None, 'max': None, }, 'amount': { 'min': lot, 'max': None, }, 'price': { 'min': step, 'max': None, }, 'cost': { 'min': self.parse_number(Precise.string_mul(lotString, stepString)), 'max': None, }, }, 'info': market, })) return result def transfer(self, code, amount, fromAccount, toAccount, params={}): """ transfer currency internally between wallets on the same account :param str code: unified currency code :param float amount: amount to transfer :param str fromAccount: account to transfer from :param str toAccount: account to transfer to :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>` """ # account can be "exchange" or "bank", with aliases "main" or "trading" respectively self.load_markets() currency = self.currency(code) requestAmount = self.currency_to_precision(code, amount) request = { 'currency': currency['id'], 'amount': requestAmount, } type = self.safe_string(params, 'type') if type is None: accountsByType = self.safe_value(self.options, 'accountsByType', {}) fromId = self.safe_string(accountsByType, fromAccount, fromAccount) toId = self.safe_string(accountsByType, toAccount, toAccount) if fromId == toId: raise ExchangeError(self.id + ' transfer() from and to cannot be the same account') type = fromId + 'To' + self.capitalize(toId) request['type'] = type response = self.privatePostAccountTransfer(self.extend(request, params)) # # { # 'id': '2db6ebab-fb26-4537-9ef8-1a689472d236' # } # transfer = self.parse_transfer(response, currency) return self.extend(transfer, { 'fromAccount': fromAccount, 'toAccount': toAccount, 'amount': self.parse_number(requestAmount), }) def parse_transfer(self, transfer, currency=None): # # { # 'id': '2db6ebab-fb26-4537-9ef8-1a689472d236' # } # timestamp = self.milliseconds() return { 'id': self.safe_string(transfer, 'id'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'currency': self.safe_currency_code(None, currency), 'amount': None, 'fromAccount': None, 'toAccount': None, 'status': None, 'info': transfer, } def fetch_currencies(self, params={}): """ fetches all available currencies on an exchange :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an associative dictionary of currencies """ response = self.publicGetCurrency(params) # # [ # { # "id":"XPNT", # "fullName":"pToken", # "crypto":true, # "payinEnabled":true, # "payinPaymentId":false, # "payinConfirmations":9, # "payoutEnabled":true, # "payoutIsPaymentId":false, # "transferEnabled":true, # "delisted":false, # "payoutFee":"26.510000000000", # "precisionPayout":18, # "precisionTransfer":8 # } # ] # result = {} for i in range(0, len(response)): currency = response[i] id = self.safe_string(currency, 'id') # todo: will need to rethink the fees # to add support for multiple withdrawal/deposit methods and # differentiated fees for each particular method precision = self.safe_string(currency, 'precisionTransfer', '8') code = self.safe_currency_code(id) payin = self.safe_value(currency, 'payinEnabled') payout = self.safe_value(currency, 'payoutEnabled') transfer = self.safe_value(currency, 'transferEnabled') active = payin and payout and transfer if 'disabled' in currency: if currency['disabled']: active = False type = 'fiat' if ('crypto' in currency) and currency['crypto']: type = 'crypto' name = self.safe_string(currency, 'fullName') result[code] = { 'id': id, 'code': code, 'type': type, 'payin': payin, 'payout': payout, 'transfer': transfer, 'info': currency, 'name': name, 'active': active, 'deposit': payin, 'withdraw': payout, 'fee': self.safe_number(currency, 'payoutFee'), # todo: redesign 'precision': self.parse_number(self.parse_precision(precision)), 'limits': { 'amount': { 'min': None, 'max': None, }, 'withdraw': { 'min': None, 'max': None, }, }, } return result def parse_trading_fee(self, fee, market=None): # # # { # takeLiquidityRate: '0.001', # provideLiquidityRate: '-0.0001' # } # return { 'info': fee, 'symbol': self.safe_symbol(None, market), 'maker': self.safe_number(fee, 'provideLiquidityRate'), 'taker': self.safe_number(fee, 'takeLiquidityRate'), 'percentage': True, 'tierBased': True, } def fetch_trading_fee(self, symbol, params={}): """ fetch the trading fees for a market :param str symbol: unified market symbol :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a `fee structure <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` """ self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = self.privateGetTradingFeeSymbol(request) # # { # takeLiquidityRate: '0.001', # provideLiquidityRate: '-0.0001' # } # return self.parse_trading_fee(response, market) def parse_balance(self, response): result = { 'info': response, 'timestamp': None, 'datetime': None, } for i in range(0, len(response)): balance = response[i] currencyId = self.safe_string(balance, 'currency') code = self.safe_currency_code(currencyId) account = self.account() account['free'] = self.safe_string(balance, 'available') account['used'] = self.safe_string(balance, 'reserved') result[code] = account return self.safe_balance(result) def fetch_balance(self, params={}): """ query for balance and get the amount of funds available for trading or funds locked in orders :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>` """ self.load_markets() type = self.safe_string(params, 'type', 'trading') fetchBalanceAccounts = self.safe_value(self.options, 'fetchBalanceMethod', {}) typeId = self.safe_string(fetchBalanceAccounts, type) if typeId is None: raise ExchangeError(self.id + ' fetchBalance() account type must be either main or trading') method = 'privateGet' + self.capitalize(typeId) + 'Balance' query = self.omit(params, 'type') response = getattr(self, method)(query) # # [ # {"currency":"SPI","available":"0","reserved":"0"}, # {"currency":"GRPH","available":"0","reserved":"0"}, # {"currency":"DGTX","available":"0","reserved":"0"}, # ] # return self.parse_balance(response) def parse_ohlcv(self, ohlcv, market=None): # # { # "timestamp":"2015-08-20T19:01:00.000Z", # "open":"0.006", # "close":"0.006", # "min":"0.006", # "max":"0.006", # "volume":"0.003", # "volumeQuote":"0.000018" # } # return [ self.parse8601(self.safe_string(ohlcv, 'timestamp')), self.safe_number(ohlcv, 'open'), self.safe_number(ohlcv, 'max'), self.safe_number(ohlcv, 'min'), self.safe_number(ohlcv, 'close'), self.safe_number(ohlcv, 'volume'), ] def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): """ fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int|None since: timestamp in ms of the earliest candle to fetch :param int|None limit: the maximum amount of candles to fetch :param dict params: extra parameters specific to the hitbtc api endpoint :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume """ self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], 'period': self.timeframes[timeframe], } if since is not None: request['from'] = self.iso8601(since) if limit is not None: request['limit'] = limit response = self.publicGetCandlesSymbol(self.extend(request, params)) # # [ # {"timestamp":"2015-08-20T19:01:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.003","volumeQuote":"0.000018"}, # {"timestamp":"2015-08-20T19:03:00.000Z","open":"0.006","close":"0.006","min":"0.006","max":"0.006","volume":"0.013","volumeQuote":"0.000078"}, # {"timestamp":"2015-08-20T19:06:00.000Z","open":"0.0055","close":"0.005","min":"0.005","max":"0.0055","volume":"0.003","volumeQuote":"0.0000155"}, # ] # return self.parse_ohlcvs(response, market, timeframe, since, limit) def fetch_order_book(self, symbol, limit=None, params={}): """ fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data :param str symbol: unified symbol of the market to fetch the order book for :param int|None limit: the maximum amount of order book entries to return :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols """ self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } if limit is not None: request['limit'] = limit # default = 100, 0 = unlimited response = self.publicGetOrderbookSymbol(self.extend(request, params)) return self.parse_order_book(response, market['symbol'], None, 'bid', 'ask', 'price', 'size') def parse_ticker(self, ticker, market=None): timestamp = self.parse8601(ticker['timestamp']) symbol = self.safe_symbol(None, market) baseVolume = self.safe_string(ticker, 'volume') quoteVolume = self.safe_string(ticker, 'volumeQuote') open = self.safe_string(ticker, 'open') last = self.safe_string(ticker, 'last') return self.safe_ticker({ 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_string(ticker, 'high'), 'low': self.safe_string(ticker, 'low'), 'bid': self.safe_string(ticker, 'bid'), 'bidVolume': None, 'ask': self.safe_string(ticker, 'ask'), 'askVolume': None, 'vwap': None, 'open': open, 'close': last, 'last': last, 'previousClose': None, 'change': None, 'percentage': None, 'average': None, 'baseVolume': baseVolume, 'quoteVolume': quoteVolume, 'info': ticker, }, market) def fetch_tickers(self, symbols=None, params={}): """ fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market :param [str]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>` """ self.load_markets() symbols = self.market_symbols(symbols) response = self.publicGetTicker(params) result = {} for i in range(0, len(response)): ticker = response[i] marketId = self.safe_string(ticker, 'symbol') market = self.safe_market(marketId) symbol = market['symbol'] result[symbol] = self.parse_ticker(ticker, market) return self.filter_by_array(result, 'symbol', symbols) def fetch_ticker(self, symbol, params={}): """ fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market :param str symbol: unified symbol of the market to fetch the ticker for :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>` """ self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } response = self.publicGetTickerSymbol(self.extend(request, params)) if 'message' in response: raise ExchangeError(self.id + ' ' + response['message']) return self.parse_ticker(response, market) def parse_trade(self, trade, market=None): # createMarketOrder # # { fee: "0.0004644", # id: 386394956, # price: "0.4644", # quantity: "1", # timestamp: "2018-10-25T16:41:44.780Z"} # # fetchTrades # # {id: 974786185, # price: '0.032462', # quantity: '0.3673', # side: 'buy', # timestamp: '2020-10-16T12:57:39.846Z'} # # fetchMyTrades # # {id: 277210397, # clientOrderId: '6e102f3e7f3f4e04aeeb1cdc95592f1a', # orderId: 28102855393, # symbol: 'ETHBTC', # side: 'sell', # quantity: '0.002', # price: '0.073365', # fee: '0.000000147', # timestamp: '2018-04-28T18:39:55.345Z'} # # { # "id":1568938909, # "orderId":793293348428, # "clientOrderId":"fbc5c5b753e8476cb14697458cb928ef", # "symbol":"DOGEUSD", # "side":"sell", # "quantity":"100", # "price":"0.03904191", # "fee":"0.009760477500", # "timestamp":"2022-01-25T15:15:41.353Z", # "taker":true # } # timestamp = self.parse8601(trade['timestamp']) marketId = self.safe_string(trade, 'symbol') market = self.safe_market(marketId, market) symbol = market['symbol'] fee = None feeCostString = self.safe_string(trade, 'fee') if feeCostString is not None: feeCurrencyCode = market['feeCurrency'] if market else None fee = { 'cost': feeCostString, 'currency': feeCurrencyCode, } # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 orderId = self.safe_string(trade, 'clientOrderId') priceString = self.safe_string(trade, 'price') amountString = self.safe_string(trade, 'quantity') side = self.safe_string(trade, 'side') id = self.safe_string(trade, 'id') return self.safe_trade({ 'info': trade, 'id': id, 'order': orderId, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'type': None, 'side': side, 'takerOrMaker': None, 'price': priceString, 'amount': amountString, 'cost': None, 'fee': fee, }, market) def fetch_transactions(self, code=None, since=None, limit=None, params={}): """ fetch history of deposits and withdrawals :param str|None code: unified currency code for the currency of the transactions, default is None :param int|None since: timestamp in ms of the earliest transaction, default is None :param int|None limit: max number of transactions to return, default is None :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a list of `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>` """ self.load_markets() currency = None request = {} if code is not None: currency = self.currency(code) request['asset'] = currency['id'] if since is not None: request['startTime'] = since response = self.privateGetAccountTransactions(self.extend(request, params)) return self.parse_transactions(response, currency, since, limit) def parse_transaction(self, transaction, currency=None): # # transactions # # { # id: 'd53ee9df-89bf-4d09-886e-849f8be64647', # index: 1044718371, # type: 'payout', # payout, payin # status: 'success', # currency: 'ETH', # amount: '4.522683200000000000000000', # createdAt: '2018-06-07T00:43:32.426Z', # updatedAt: '2018-06-07T00:45:36.447Z', # hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f', # address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c', # fee: '0.00958', # }, # { # id: 'e6c63331-467e-4922-9edc-019e75d20ba3', # index: 1044714672, # type: 'exchangeToBank', # exchangeToBank, bankToExchange, withdraw # status: 'success', # currency: 'ETH', # amount: '4.532263200000000000', # createdAt: '2018-06-07T00:42:39.543Z', # updatedAt: '2018-06-07T00:42:39.683Z', # }, # # withdraw # # { # "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b" # } # id = self.safe_string(transaction, 'id') timestamp = self.parse8601(self.safe_string(transaction, 'createdAt')) updated = self.parse8601(self.safe_string(transaction, 'updatedAt')) currencyId = self.safe_string(transaction, 'currency') code = self.safe_currency_code(currencyId, currency) status = self.parse_transaction_status(self.safe_string(transaction, 'status')) amount = self.safe_number(transaction, 'amount') address = self.safe_string(transaction, 'address') txid = self.safe_string(transaction, 'hash') fee = None feeCost = self.safe_number(transaction, 'fee') if feeCost is not None: fee = { 'cost': feeCost, 'currency': code, } type = self.parse_transaction_type(self.safe_string(transaction, 'type')) return { 'info': transaction, 'id': id, 'txid': txid, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'network': None, 'address': address, 'addressTo': None, 'addressFrom': None, 'tag': None, 'tagTo': None, 'tagFrom': None, 'type': type, 'amount': amount, 'currency': code, 'status': status, 'updated': updated, 'fee': fee, } def parse_transaction_status(self, status): statuses = { 'pending': 'pending', 'failed': 'failed', 'success': 'ok', } return self.safe_string(statuses, status, status) def parse_transaction_type(self, type): types = { 'payin': 'deposit', 'payout': 'withdrawal', 'withdraw': 'withdrawal', } return self.safe_string(types, type, type) def fetch_trades(self, symbol, since=None, limit=None, params={}): """ get the list of most recent trades for a particular symbol :param str symbol: unified symbol of the market to fetch trades for :param int|None since: timestamp in ms of the earliest trade to fetch :param int|None limit: the maximum amount of trades to fetch :param dict params: extra parameters specific to the hitbtc api endpoint :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>` """ self.load_markets() market = self.market(symbol) request = { 'symbol': market['id'], } if limit is not None: request['limit'] = limit if since is not None: request['sort'] = 'ASC' request['from'] = self.iso8601(since) response = self.publicGetTradesSymbol(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def create_order(self, symbol, type, side, amount, price=None, params={}): """ create a trade order :param str symbol: unified symbol of the market to create an order in :param str type: 'market' or 'limit' :param str side: 'buy' or 'sell' :param float amount: how much of currency you want to trade in units of base currency :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() market = self.market(symbol) # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # their max accepted length is 32 characters uuid = self.uuid() parts = uuid.split('-') clientOrderId = ''.join(parts) clientOrderId = clientOrderId[0:32] amount = float(amount) request = { 'clientOrderId': clientOrderId, 'symbol': market['id'], 'side': side, 'quantity': self.amount_to_precision(symbol, amount), 'type': type, } if type == 'limit': request['price'] = self.price_to_precision(symbol, price) else: request['timeInForce'] = self.options['defaultTimeInForce'] response = self.privatePostOrder(self.extend(request, params)) order = self.parse_order(response) if order['status'] == 'rejected': raise InvalidOrder(self.id + ' order was rejected by the exchange ' + self.json(order)) return order def edit_order(self, id, symbol, type, side, amount=None, price=None, params={}): self.load_markets() # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 # their max accepted length is 32 characters uuid = self.uuid() parts = uuid.split('-') requestClientId = ''.join(parts) requestClientId = requestClientId[0:32] request = { 'clientOrderId': id, 'requestClientId': requestClientId, } if amount is not None: request['quantity'] = self.amount_to_precision(symbol, amount) if price is not None: request['price'] = self.price_to_precision(symbol, price) response = self.privatePatchOrderClientOrderId(self.extend(request, params)) return self.parse_order(response) def cancel_order(self, id, symbol=None, params={}): """ cancels an open order :param str id: order id :param str|None symbol: unified symbol of the market the order was made in :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 request = { 'clientOrderId': id, } response = self.privateDeleteOrderClientOrderId(self.extend(request, params)) return self.parse_order(response) def parse_order_status(self, status): statuses = { 'new': 'open', 'suspended': 'open', 'partiallyFilled': 'open', 'filled': 'closed', 'canceled': 'canceled', 'expired': 'failed', } return self.safe_string(statuses, status, status) def parse_order(self, order, market=None): # # createMarketOrder # # { # clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0", # createdAt: "2018-10-25T16:41:44.780Z", # cumQuantity: "1", # id: "66799540063", # quantity: "1", # side: "sell", # status: "filled", # symbol: "XRPUSDT", # timeInForce: "FOK", # tradesReport: [ # { # fee: "0.0004644", # id: 386394956, # price: "0.4644", # quantity: "1", # timestamp: "2018-10-25T16:41:44.780Z" # } # ], # type: "market", # updatedAt: "2018-10-25T16:41:44.780Z" # } # # { # "id": 119499457455, # "clientOrderId": "87baab109d58401b9202fa0749cb8288", # "symbol": "ETHUSD", # "side": "buy", # "status": "filled", # "type": "market", # "timeInForce": "FOK", # "quantity": "0.0007", # "price": "181.487", # "avgPrice": "164.989", # "cumQuantity": "0.0007", # "createdAt": "2019-04-17T13:27:38.062Z", # "updatedAt": "2019-04-17T13:27:38.062Z" # } # created = self.parse8601(self.safe_string(order, 'createdAt')) updated = self.parse8601(self.safe_string(order, 'updatedAt')) marketId = self.safe_string(order, 'symbol') market = self.safe_market(marketId, market) symbol = market['symbol'] amount = self.safe_string(order, 'quantity') filled = self.safe_string(order, 'cumQuantity') status = self.parse_order_status(self.safe_string(order, 'status')) # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 id = self.safe_string(order, 'clientOrderId') clientOrderId = id price = self.safe_string(order, 'price') type = self.safe_string(order, 'type') side = self.safe_string(order, 'side') trades = self.safe_value(order, 'tradesReport') fee = None average = self.safe_string(order, 'avgPrice') timeInForce = self.safe_string(order, 'timeInForce') return self.safe_order({ 'id': id, 'clientOrderId': clientOrderId, # https://github.com/ccxt/ccxt/issues/5674 'timestamp': created, 'datetime': self.iso8601(created), 'lastTradeTimestamp': updated, 'status': status, 'symbol': symbol, 'type': type, 'timeInForce': timeInForce, 'side': side, 'price': price, 'stopPrice': None, 'average': average, 'amount': amount, 'cost': None, 'filled': filled, 'remaining': None, 'fee': fee, 'trades': trades, 'info': order, }, market) def fetch_order(self, id, symbol=None, params={}): """ fetches information on an order made by the user :param str|None symbol: not used by hitbtc fetchOrder :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 request = { 'clientOrderId': id, } response = self.privateGetHistoryOrder(self.extend(request, params)) numOrders = len(response) if numOrders > 0: return self.parse_order(response[0]) raise OrderNotFound(self.id + ' order ' + id + ' not found') def fetch_open_order(self, id, symbol=None, params={}): """ fetch an open order by it's id :param str id: order id :param str|None symbol: not used by hitbtc fetchOpenOrder() :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() # we use clientOrderId as the order id with self exchange intentionally # because most of their endpoints will require clientOrderId # explained here: https://github.com/ccxt/ccxt/issues/5674 request = { 'clientOrderId': id, } response = self.privateGetOrderClientOrderId(self.extend(request, params)) return self.parse_order(response) def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): """ fetch all unfilled currently open orders :param str|None symbol: unified market symbol :param int|None since: the earliest time in ms to fetch open orders for :param int|None limit: the maximum number of open orders structures to retrieve :param dict params: extra parameters specific to the hitbtc api endpoint :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() market = None request = {} if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] response = self.privateGetOrder(self.extend(request, params)) return self.parse_orders(response, market, since, limit) def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): """ fetches information on multiple closed orders made by the user :param str|None symbol: unified market symbol of the market orders were made in :param int|None since: the earliest time in ms to fetch orders for :param int|None limit: the maximum number of orde structures to retrieve :param dict params: extra parameters specific to the hitbtc api endpoint :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>` """ self.load_markets() market = None request = {} if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] if limit is not None: request['limit'] = limit if since is not None: request['from'] = self.iso8601(since) response = self.privateGetHistoryOrder(self.extend(request, params)) parsedOrders = self.parse_orders(response, market) orders = [] for i in range(0, len(parsedOrders)): order = parsedOrders[i] status = order['status'] if (status == 'closed') or (status == 'canceled'): orders.append(order) return self.filter_by_since_limit(orders, since, limit) def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}): """ fetch all trades made by the user :param str|None symbol: unified market symbol :param int|None since: the earliest time in ms to fetch trades for :param int|None limit: the maximum number of trades structures to retrieve :param dict params: extra parameters specific to the hitbtc api endpoint :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>` """ self.load_markets() request = { # 'symbol': 'BTC/USD', # optional # 'sort': 'DESC', # or 'ASC' # 'by': 'timestamp', # or 'id' str timestamp by default, or id # 'from': 'Datetime or Number', # ISO 8601 # 'till': 'Datetime or Number', # 'limit': 100, # 'offset': 0, } market = None if symbol is not None: market = self.market(symbol) request['symbol'] = market['id'] if since is not None: request['from'] = self.iso8601(since) if limit is not None: request['limit'] = limit response = self.privateGetHistoryTrades(self.extend(request, params)) # # [ # { # "id": 9535486, # "clientOrderId": "f8dbaab336d44d5ba3ff578098a68454", # "orderId": 816088377, # "symbol": "ETHBTC", # "side": "sell", # "quantity": "0.061", # "price": "0.045487", # "fee": "0.000002775", # "timestamp": "2017-05-17T12:32:57.848Z" # }, # { # "id": 9535437, # "clientOrderId": "27b9bfc068b44194b1f453c7af511ed6", # "orderId": 816088021, # "symbol": "ETHBTC", # "side": "buy", # "quantity": "0.038", # "price": "0.046000", # "fee": "-0.000000174", # "timestamp": "2017-05-17T12:30:57.848Z" # } # ] # return self.parse_trades(response, market, since, limit) def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}): """ fetch all the trades made from a single order :param str id: order id :param str|None symbol: unified market symbol :param int|None since: the earliest time in ms to fetch trades for :param int|None limit: the maximum number of trades to retrieve :param dict params: extra parameters specific to the hitbtc api endpoint :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>` """ # The id needed here is the exchange's id, and not the clientOrderID, # which is the id that is stored in the unified order id # To get the exchange's id you need to grab it from order['info']['id'] self.load_markets() market = None if symbol is not None: market = self.market(symbol) request = { 'orderId': id, } response = self.privateGetHistoryOrderOrderIdTrades(self.extend(request, params)) numOrders = len(response) if numOrders > 0: return self.parse_trades(response, market, since, limit) raise OrderNotFound(self.id + ' order ' + id + ' not found, ' + self.id + '.fetchOrderTrades() requires an exchange-specific order id, you need to grab it from order["info"]["id"]') def create_deposit_address(self, code, params={}): """ create a currency deposit address :param str code: unified currency code of the currency for the deposit address :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>` """ self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], } response = self.privatePostAccountCryptoAddressCurrency(self.extend(request, params)) address = self.safe_string(response, 'address') self.check_address(address) tag = self.safe_string(response, 'paymentId') return { 'currency': currency, 'address': address, 'tag': tag, 'info': response, } def fetch_deposit_address(self, code, params={}): """ fetch the deposit address for a currency associated with self account :param str code: unified currency code :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>` """ self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], } network = self.safe_string(params, 'network') if network is not None: params = self.omit(params, 'network') networks = self.safe_value(self.options, 'networks') endpart = self.safe_string(networks, network, network) request['currency'] += endpart response = self.privateGetAccountCryptoAddressCurrency(self.extend(request, params)) address = self.safe_string(response, 'address') self.check_address(address) tag = self.safe_string(response, 'paymentId') return { 'currency': currency['code'], 'address': address, 'tag': tag, 'network': None, 'info': response, } def convert_currency_network(self, code, amount, fromNetwork, toNetwork, params): self.load_markets() currency = self.currency(code) networks = self.safe_value(self.options, 'networks', {}) fromNetwork = self.safe_string(networks, fromNetwork, fromNetwork) # handle ETH>ERC20 alias toNetwork = self.safe_string(networks, toNetwork, toNetwork) # handle ETH>ERC20 alias if fromNetwork == toNetwork: raise ExchangeError(self.id + ' convertCurrencyNetwork() fromNetwork cannot be the same as toNetwork') request = { 'fromCurrency': currency['id'] + fromNetwork, 'toCurrency': currency['id'] + toNetwork, 'amount': float(self.currency_to_precision(code, amount)), } response = self.privatePostAccountCryptoTransferConvert(self.extend(request, params)) return { 'info': response, } def withdraw(self, code, amount, address, tag=None, params={}): """ make a withdrawal :param str code: unified currency code :param float amount: the amount to withdraw :param str address: the address to withdraw to :param str|None tag: :param dict params: extra parameters specific to the hitbtc api endpoint :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>` """ tag, params = self.handle_withdraw_tag_and_params(tag, params) self.load_markets() self.check_address(address) currency = self.currency(code) request = { 'currency': currency['id'], 'amount': float(amount), 'address': address, } if tag: request['paymentId'] = tag networks = self.safe_value(self.options, 'networks', {}) network = self.safe_string_upper(params, 'network') # self line allows the user to specify either ERC20 or ETH network = self.safe_string(networks, network, network) # handle ERC20>ETH alias if network is not None: request['currency'] += network # when network the currency need to be changed to currency + network params = self.omit(params, 'network') response = self.privatePostAccountCryptoWithdraw(self.extend(request, params)) # # { # "id": "d2ce578f-647d-4fa0-b1aa-4a27e5ee597b" # } # return self.parse_transaction(response, currency) def nonce(self): return self.milliseconds() def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): url = '/api/' + self.version + '/' query = self.omit(params, self.extract_params(path)) if api == 'public': url += api + '/' + self.implode_params(path, params) if query: url += '?' + self.urlencode(query) else: self.check_required_credentials() url += self.implode_params(path, params) if method == 'GET': if query: url += '?' + self.urlencode(query) elif query: body = self.json(query) payload = self.encode(self.apiKey + ':' + self.secret) auth = self.string_to_base64(payload) headers = { 'Authorization': 'Basic ' + self.decode(auth), 'Content-Type': 'application/json', } url = self.urls['api'][api] + url return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody): if response is None: return if code >= 400: feedback = self.id + ' ' + body # {"code":504,"message":"Gateway Timeout","description":""} if (code == 503) or (code == 504): raise ExchangeNotAvailable(feedback) # fallback to default error handler on rate limit errors # {"code":429,"message":"Too many requests","description":"Too many requests"} if code == 429: return # {"error":{"code":20002,"message":"Order not found","description":""}} if body[0] == '{': if 'error' in response: errorCode = self.safe_string(response['error'], 'code') self.throw_exactly_matched_exception(self.exceptions, errorCode, feedback) message = self.safe_string(response['error'], 'message') if message == 'Duplicate clientOrderId': raise InvalidOrder(feedback) raise ExchangeError(feedback)
mit
c2fc16da282f2eca802510c9e734b7b5
42.384507
189
0.524251
4.124665
false
false
false
false
ccxt/ccxt
python/ccxt/base/exchange.py
1
148427
# -*- coding: utf-8 -*- """Base exchange class""" # ----------------------------------------------------------------------------- __version__ = '2.2.27' # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import NetworkError from ccxt.base.errors import NotSupported from ccxt.base.errors import AuthenticationError from ccxt.base.errors import DDoSProtection from ccxt.base.errors import RequestTimeout from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import InvalidAddress from ccxt.base.errors import InvalidOrder from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import BadSymbol from ccxt.base.errors import NullResponse from ccxt.base.errors import RateLimitExceeded # ----------------------------------------------------------------------------- from ccxt.base.decimal_to_precision import decimal_to_precision from ccxt.base.decimal_to_precision import DECIMAL_PLACES, TICK_SIZE, NO_PADDING, TRUNCATE, ROUND, ROUND_UP, ROUND_DOWN from ccxt.base.decimal_to_precision import number_to_string from ccxt.base.precise import Precise # ----------------------------------------------------------------------------- # rsa jwt signing from cryptography.hazmat import backends from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_private_key # ----------------------------------------------------------------------------- # ecdsa signing from ccxt.static_dependencies import ecdsa from ccxt.static_dependencies import keccak # eddsa signing try: import axolotl_curve25519 as eddsa except ImportError: eddsa = None # ----------------------------------------------------------------------------- __all__ = [ 'Exchange', ] # ----------------------------------------------------------------------------- import types import logging import base64 import binascii import calendar import collections import datetime from email.utils import parsedate import functools import gzip import hashlib import hmac import io import json import math import random from numbers import Number import re from requests import Session from requests.utils import default_user_agent from requests.exceptions import HTTPError, Timeout, TooManyRedirects, RequestException, ConnectionError as requestsConnectionError # import socket from ssl import SSLError # import sys import time import uuid import zlib from decimal import Decimal from time import mktime from wsgiref.handlers import format_date_time import urllib.parse as _urlencode # ----------------------------------------------------------------------------- class Exchange(object): """Base exchange class""" id = None name = None version = None certified = False # if certified by the CCXT dev team pro = False # if it is integrated with CCXT Pro for WebSocket support alias = False # whether this exchange is an alias to another exchange # rate limiter settings enableRateLimit = True rateLimit = 2000 # milliseconds = seconds * 1000 timeout = 10000 # milliseconds = seconds * 1000 asyncio_loop = None aiohttp_proxy = None aiohttp_trust_env = False requests_trust_env = False session = None # Session () by default verify = True # SSL verification validateServerSsl = True validateClientSsl = False logger = None # logging.getLogger(__name__) by default userAgent = None userAgents = { 'chrome': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', 'chrome39': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36', 'chrome100': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36', } verbose = False markets = None symbols = None codes = None timeframes = None fees = { 'trading': { 'percentage': True, # subclasses should rarely have to redefine this }, 'funding': { 'withdraw': {}, 'deposit': {}, }, } loaded_fees = { 'trading': { 'percentage': True, }, 'funding': { 'withdraw': {}, 'deposit': {}, }, } ids = None urls = None api = None parseJsonResponse = True proxy = '' origin = '*' # CORS origin proxies = None hostname = None # in case of inaccessibility of the "main" domain apiKey = '' secret = '' password = '' uid = '' privateKey = '' # a "0x"-prefixed hexstring private key for a wallet walletAddress = '' # the wallet address "0x"-prefixed hexstring token = '' # reserved for HTTP auth in some cases twofa = None markets_by_id = None currencies_by_id = None precision = None exceptions = None limits = { 'leverage': { 'min': None, 'max': None, }, 'amount': { 'min': None, 'max': None, }, 'price': { 'min': None, 'max': None, }, 'cost': { 'min': None, 'max': None, }, } httpExceptions = { '422': ExchangeError, '418': DDoSProtection, '429': RateLimitExceeded, '404': ExchangeNotAvailable, '409': ExchangeNotAvailable, '410': ExchangeNotAvailable, '500': ExchangeNotAvailable, '501': ExchangeNotAvailable, '502': ExchangeNotAvailable, '520': ExchangeNotAvailable, '521': ExchangeNotAvailable, '522': ExchangeNotAvailable, '525': ExchangeNotAvailable, '526': ExchangeNotAvailable, '400': ExchangeNotAvailable, '403': ExchangeNotAvailable, '405': ExchangeNotAvailable, '503': ExchangeNotAvailable, '530': ExchangeNotAvailable, '408': RequestTimeout, '504': RequestTimeout, '401': AuthenticationError, '511': AuthenticationError, } headers = None balance = None orderbooks = None orders = None myTrades = None trades = None transactions = None ohlcvs = None tickers = None base_currencies = None quote_currencies = None currencies = None options = None # Python does not allow to define properties in run-time with setattr accounts = None positions = None status = { 'status': 'ok', 'updated': None, 'eta': None, 'url': None, } requiredCredentials = { 'apiKey': True, 'secret': True, 'uid': False, 'login': False, 'password': False, 'twofa': False, # 2-factor authentication (one-time password key) 'privateKey': False, # a "0x"-prefixed hexstring private key for a wallet 'walletAddress': False, # the wallet address "0x"-prefixed hexstring 'token': False, # reserved for HTTP auth in some cases } # API method metainfo has = { 'publxicAPI': True, 'privateAPI': True, 'CORS': None, 'spot': None, 'margin': None, 'swap': None, 'future': None, 'option': None, 'addMargin': None, 'cancelAllOrders': None, 'cancelOrder': True, 'cancelOrders': None, 'createDepositAddress': None, 'createLimitOrder': True, 'createMarketOrder': True, 'createOrder': True, 'createPostOnlyOrder': None, 'createReduceOnlyOrder': None, 'createStopOrder': None, 'createStopLimitOrder': None, 'createStopMarketOrder': None, 'editOrder': 'emulated', 'fetchAccounts': None, 'fetchBalance': True, 'fetchBidsAsks': None, 'fetchBorrowInterest': None, 'fetchBorrowRate': None, 'fetchBorrowRateHistory': None, 'fetchBorrowRatesPerSymbol': None, 'fetchBorrowRates': None, 'fetchCanceledOrders': None, 'fetchClosedOrder': None, 'fetchClosedOrders': None, 'fetchCurrencies': 'emulated', 'fetchDeposit': None, 'fetchDepositAddress': None, 'fetchDepositAddresses': None, 'fetchDepositAddressesByNetwork': None, 'fetchDeposits': None, 'fetchFundingFee': None, 'fetchFundingFees': None, 'fetchFundingHistory': None, 'fetchFundingRate': None, 'fetchFundingRateHistory': None, 'fetchFundingRates': None, 'fetchIndexOHLCV': None, 'fetchL2OrderBook': True, 'fetchLedger': None, 'fetchLedgerEntry': None, 'fetchLeverageTiers': None, 'fetchMarketLeverageTiers': None, 'fetchMarkets': True, 'fetchMarkOHLCV': None, 'fetchMyTrades': None, 'fetchOHLCV': 'emulated', 'fetchOpenOrder': None, 'fetchOpenOrders': None, 'fetchOrder': None, 'fetchOrderBook': True, 'fetchOrderBooks': None, 'fetchOrders': None, 'fetchOrderTrades': None, 'fetchPermissions': None, 'fetchPosition': None, 'fetchPositions': None, 'fetchPositionsRisk': None, 'fetchPremiumIndexOHLCV': None, 'fetchStatus': 'emulated', 'fetchTicker': True, 'fetchTickers': None, 'fetchTime': None, 'fetchTrades': True, 'fetchTradingFee': None, 'fetchTradingFees': None, 'fetchTradingLimits': None, 'fetchTransactions': None, 'fetchTransfers': None, 'fetchWithdrawal': None, 'fetchWithdrawals': None, 'reduceMargin': None, 'setLeverage': None, 'setMargin': None, 'setMarginMode': None, 'setPositionMode': None, 'signIn': None, 'transfer': None, 'withdraw': None, } precisionMode = DECIMAL_PLACES paddingMode = NO_PADDING minFundingAddressLength = 1 # used in check_address substituteCommonCurrencyCodes = True quoteJsonNumbers = True number = float # or str (a pointer to a class) handleContentTypeApplicationZip = False # whether fees should be summed by currency code reduceFees = True lastRestRequestTimestamp = 0 lastRestPollTimestamp = 0 restRequestQueue = None restPollerLoopIsRunning = False rateLimitTokens = 16 rateLimitMaxTokens = 16 rateLimitUpdateTime = 0 enableLastHttpResponse = True enableLastJsonResponse = True enableLastResponseHeaders = True last_http_response = None last_json_response = None last_response_headers = None requiresEddsa = False base58_encoder = None base58_decoder = None # no lower case l or upper case I, O base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' commonCurrencies = { 'XBT': 'BTC', 'BCC': 'BCH', 'BCHABC': 'BCH', 'BCHSV': 'BSV', } synchronous = True def __init__(self, config={}): self.precision = dict() if self.precision is None else self.precision self.limits = dict() if self.limits is None else self.limits self.exceptions = dict() if self.exceptions is None else self.exceptions self.headers = dict() if self.headers is None else self.headers self.balance = dict() if self.balance is None else self.balance self.orderbooks = dict() if self.orderbooks is None else self.orderbooks self.tickers = dict() if self.tickers is None else self.tickers self.trades = dict() if self.trades is None else self.trades self.transactions = dict() if self.transactions is None else self.transactions self.positions = dict() if self.positions is None else self.positions self.ohlcvs = dict() if self.ohlcvs is None else self.ohlcvs self.currencies = dict() if self.currencies is None else self.currencies self.options = dict() if self.options is None else self.options # Python does not allow to define properties in run-time with setattr self.decimal_to_precision = decimal_to_precision self.number_to_string = number_to_string # version = '.'.join(map(str, sys.version_info[:3])) # self.userAgent = { # 'User-Agent': 'ccxt/' + __version__ + ' (+https://github.com/ccxt/ccxt) Python/' + version # } self.origin = self.uuid() self.userAgent = default_user_agent() settings = self.deep_extend(self.describe(), config) for key in settings: if hasattr(self, key) and isinstance(getattr(self, key), dict): setattr(self, key, self.deep_extend(getattr(self, key), settings[key])) else: setattr(self, key, settings[key]) if self.api: self.define_rest_api(self.api, 'request') if self.markets: self.set_markets(self.markets) # convert all properties from underscore notation foo_bar to camelcase notation fooBar cls = type(self) for name in dir(self): if name[0] != '_' and name[-1] != '_' and '_' in name: parts = name.split('_') # fetch_ohlcv → fetchOHLCV (not fetchOhlcv!) exceptions = {'ohlcv': 'OHLCV', 'le': 'LE', 'be': 'BE'} camelcase = parts[0] + ''.join(exceptions.get(i, self.capitalize(i)) for i in parts[1:]) attr = getattr(self, name) if isinstance(attr, types.MethodType): setattr(cls, camelcase, getattr(cls, name)) else: setattr(self, camelcase, attr) self.tokenBucket = self.extend({ 'refillRate': 1.0 / self.rateLimit if self.rateLimit > 0 else float('inf'), 'delay': 0.001, 'capacity': 1.0, 'defaultCost': 1.0, }, getattr(self, 'tokenBucket', {})) if not self.session and self.synchronous: self.session = Session() self.session.trust_env = self.requests_trust_env self.logger = self.logger if self.logger else logging.getLogger(__name__) def __del__(self): if self.session: try: self.session.close() except Exception as e: pass def __repr__(self): return 'ccxt.' + ('async_support.' if self.asyncio_loop else '') + self.id + '()' def __str__(self): return self.name def describe(self): return {} def set_sandbox_mode(self, enabled): if enabled: if 'test' in self.urls: self.urls['apiBackup'] = self.urls['api'] self.urls['api'] = self.urls['test'] else: raise NotSupported(self.id + ' does not have a sandbox URL') elif 'apiBackup' in self.urls: self.urls['api'] = self.urls['apiBackup'] del self.urls['apiBackup'] def define_rest_api_endpoint(self, method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, config={}): cls = type(self) entry = getattr(cls, method_name) # returns a function (instead of a bound method) delimiters = re.compile('[^a-zA-Z0-9]') split_path = delimiters.split(path) lowercase_path = [x.strip().lower() for x in split_path] camelcase_suffix = ''.join([Exchange.capitalize(x) for x in split_path]) underscore_suffix = '_'.join([x for x in lowercase_path if len(x)]) camelcase_prefix = '' underscore_prefix = '' if len(paths): camelcase_prefix = paths[0] underscore_prefix = paths[0] if len(paths) > 1: camelcase_prefix += ''.join([Exchange.capitalize(x) for x in paths[1:]]) underscore_prefix += '_' + '_'.join([x.strip() for p in paths[1:] for x in delimiters.split(p)]) api_argument = paths else: api_argument = paths[0] camelcase = camelcase_prefix + camelcase_method + Exchange.capitalize(camelcase_suffix) underscore = underscore_prefix + '_' + lowercase_method + '_' + underscore_suffix.lower() def partialer(): outer_kwargs = {'path': path, 'api': api_argument, 'method': uppercase_method, 'config': config} @functools.wraps(entry) def inner(_self, params=None, context=None): """ Inner is called when a generated method (publicGetX) is called. _self is a reference to self created by function.__get__(exchange, type(exchange)) https://en.wikipedia.org/wiki/Closure_(computer_programming) equivalent to functools.partial """ inner_kwargs = dict(outer_kwargs) # avoid mutation if params is not None: inner_kwargs['params'] = params if context is not None: inner_kwargs['context'] = params return entry(_self, **inner_kwargs) return inner to_bind = partialer() setattr(cls, camelcase, to_bind) setattr(cls, underscore, to_bind) def define_rest_api(self, api, method_name, paths=[]): for key, value in api.items(): uppercase_method = key.upper() lowercase_method = key.lower() camelcase_method = lowercase_method.capitalize() if isinstance(value, list): for path in value: self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths) # the options HTTP method conflicts with the 'options' API url path # elif re.search(r'^(?:get|post|put|delete|options|head|patch)$', key, re.IGNORECASE) is not None: elif re.search(r'^(?:get|post|put|delete|head|patch)$', key, re.IGNORECASE) is not None: for [endpoint, config] in value.items(): path = endpoint.strip() if isinstance(config, dict): self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, config) elif isinstance(config, Number): self.define_rest_api_endpoint(method_name, uppercase_method, lowercase_method, camelcase_method, path, paths, {'cost': config}) else: raise NotSupported(self.id + ' define_rest_api() API format not supported, API leafs must strings, objects or numbers') else: self.define_rest_api(value, method_name, paths + [key]) def throttle(self, cost=None): now = float(self.milliseconds()) elapsed = now - self.lastRestRequestTimestamp cost = 1 if cost is None else cost sleep_time = self.rateLimit * cost if elapsed < sleep_time: delay = sleep_time - elapsed time.sleep(delay / 1000.0) @staticmethod def gzip_deflate(response, text): encoding = response.info().get('Content-Encoding') if encoding in ('gzip', 'x-gzip', 'deflate'): if encoding == 'deflate': return zlib.decompress(text, -zlib.MAX_WBITS) else: return gzip.GzipFile('', 'rb', 9, io.BytesIO(text)).read() return text def prepare_request_headers(self, headers=None): headers = headers or {} if self.session: headers.update(self.session.headers) headers.update(self.headers) if self.userAgent: if type(self.userAgent) is str: headers.update({'User-Agent': self.userAgent}) elif (type(self.userAgent) is dict) and ('User-Agent' in self.userAgent): headers.update(self.userAgent) if self.proxy: headers.update({'Origin': self.origin}) headers.update({'Accept-Encoding': 'gzip, deflate'}) return self.set_headers(headers) def log(self, *args): print(*args) def on_rest_response(self, code, reason, url, method, response_headers, response_body, request_headers, request_body): return response_body.strip() def on_json_response(self, response_body): if self.quoteJsonNumbers: return json.loads(response_body, parse_float=str, parse_int=str) else: return json.loads(response_body) def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: self.log("\nfetch Request:", self.id, method, url, "RequestHeaders:", request_headers, "RequestBody:", body) self.logger.debug("%s %s, Request: %s %s", method, url, request_headers, body) request_body = body if body: body = body.encode() self.session.cookies.clear() http_response = None http_status_code = None http_status_text = None json_response = None try: response = self.session.request( method, url, data=body, headers=request_headers, timeout=int(self.timeout / 1000), proxies=self.proxies, verify=self.verify and self.validateServerSsl ) # does not try to detect encoding response.encoding = 'utf-8' headers = response.headers http_status_code = response.status_code http_status_text = response.reason http_response = self.on_rest_response(http_status_code, http_status_text, url, method, headers, response.text, request_headers, request_body) json_response = self.parse_json(http_response) # FIXME remove last_x_responses from subclasses if self.enableLastHttpResponse: self.last_http_response = http_response if self.enableLastJsonResponse: self.last_json_response = json_response if self.enableLastResponseHeaders: self.last_response_headers = headers if self.verbose: self.log("\nfetch Response:", self.id, method, url, http_status_code, "ResponseHeaders:", headers, "ResponseBody:", http_response) self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response) response.raise_for_status() except Timeout as e: details = ' '.join([self.id, method, url]) raise RequestTimeout(details) from e except TooManyRedirects as e: details = ' '.join([self.id, method, url]) raise ExchangeError(details) from e except SSLError as e: details = ' '.join([self.id, method, url]) raise ExchangeError(details) from e except HTTPError as e: details = ' '.join([self.id, method, url]) skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) if not skip_further_error_handling: self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response) raise ExchangeError(details) from e except requestsConnectionError as e: error_string = str(e) details = ' '.join([self.id, method, url]) if 'Read timed out' in error_string: raise RequestTimeout(details) from e else: raise NetworkError(details) from e except ConnectionResetError as e: error_string = str(e) details = ' '.join([self.id, method, url]) raise NetworkError(details) from e except RequestException as e: # base exception class error_string = str(e) details = ' '.join([self.id, method, url]) if any(x in error_string for x in ['ECONNRESET', 'Connection aborted.', 'Connection broken:']): raise NetworkError(details) from e else: raise ExchangeError(details) from e self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) if json_response is not None: return json_response elif self.is_text_response(headers): return http_response else: return response.content def parse_json(self, http_response): try: if Exchange.is_json_encoded_object(http_response): return self.on_json_response(http_response) except ValueError: # superclass of JsonDecodeError (python2) pass def is_text_response(self, headers): # https://github.com/ccxt/ccxt/issues/5302 content_type = headers.get('Content-Type', '') return content_type.startswith('application/json') or content_type.startswith('text/') @staticmethod def key_exists(dictionary, key): if dictionary is None or key is None: return False if isinstance(dictionary, list): if isinstance(key, int) and 0 <= key and key < len(dictionary): return dictionary[key] is not None else: return False if key in dictionary: return dictionary[key] is not None and dictionary[key] != '' return False @staticmethod def safe_float(dictionary, key, default_value=None): value = default_value try: if Exchange.key_exists(dictionary, key): value = float(dictionary[key]) except ValueError as e: value = default_value return value @staticmethod def safe_string(dictionary, key, default_value=None): return str(dictionary[key]) if Exchange.key_exists(dictionary, key) else default_value @staticmethod def safe_string_lower(dictionary, key, default_value=None): return str(dictionary[key]).lower() if Exchange.key_exists(dictionary, key) else default_value @staticmethod def safe_string_upper(dictionary, key, default_value=None): return str(dictionary[key]).upper() if Exchange.key_exists(dictionary, key) else default_value @staticmethod def safe_integer(dictionary, key, default_value=None): if not Exchange.key_exists(dictionary, key): return default_value value = dictionary[key] try: # needed to avoid breaking on "100.0" # https://stackoverflow.com/questions/1094717/convert-a-string-to-integer-with-decimal-in-python#1094721 return int(float(value)) except ValueError: return default_value except TypeError: return default_value @staticmethod def safe_integer_product(dictionary, key, factor, default_value=None): if not Exchange.key_exists(dictionary, key): return default_value value = dictionary[key] if isinstance(value, Number): return int(value * factor) elif isinstance(value, str): try: return int(float(value) * factor) except ValueError: pass return default_value @staticmethod def safe_timestamp(dictionary, key, default_value=None): return Exchange.safe_integer_product(dictionary, key, 1000, default_value) @staticmethod def safe_value(dictionary, key, default_value=None): return dictionary[key] if Exchange.key_exists(dictionary, key) else default_value # we're not using safe_floats with a list argument as we're trying to save some cycles here # we're not using safe_float_3 either because those cases are too rare to deserve their own optimization @staticmethod def safe_float_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_float, dictionary, key1, key2, default_value) @staticmethod def safe_string_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_string, dictionary, key1, key2, default_value) @staticmethod def safe_string_lower_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_string_lower, dictionary, key1, key2, default_value) @staticmethod def safe_string_upper_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_string_upper, dictionary, key1, key2, default_value) @staticmethod def safe_integer_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_integer, dictionary, key1, key2, default_value) @staticmethod def safe_integer_product_2(dictionary, key1, key2, factor, default_value=None): value = Exchange.safe_integer_product(dictionary, key1, factor) return value if value is not None else Exchange.safe_integer_product(dictionary, key2, factor, default_value) @staticmethod def safe_timestamp_2(dictionary, key1, key2, default_value=None): return Exchange.safe_integer_product_2(dictionary, key1, key2, 1000, default_value) @staticmethod def safe_value_2(dictionary, key1, key2, default_value=None): return Exchange.safe_either(Exchange.safe_value, dictionary, key1, key2, default_value) # safe_method_n methods family @staticmethod def safe_float_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) if value is None: return default_value try: value = float(value) except ValueError as e: value = default_value return value @staticmethod def safe_string_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) return str(value) if value is not None else default_value @staticmethod def safe_string_lower_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) return str(value).lower() if value is not None else default_value @staticmethod def safe_string_upper_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) return str(value).upper() if value is not None else default_value @staticmethod def safe_integer_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) if value is None: return default_value try: # needed to avoid breaking on "100.0" # https://stackoverflow.com/questions/1094717/convert-a-string-to-integer-with-decimal-in-python#1094721 return int(float(value)) except ValueError: return default_value except TypeError: return default_value @staticmethod def safe_integer_product_n(dictionary, key_list, factor, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) if value is None: return default_value if isinstance(value, Number): return int(value * factor) elif isinstance(value, str): try: return int(float(value) * factor) except ValueError: pass return default_value @staticmethod def safe_timestamp_n(dictionary, key_list, default_value=None): return Exchange.safe_integer_product_n(dictionary, key_list, 1000, default_value) @staticmethod def safe_value_n(dictionary, key_list, default_value=None): value = Exchange.get_object_value_from_key_list(dictionary, key_list) return value if value is not None else default_value @staticmethod def get_object_value_from_key_list(dictionary, key_list): filtered_list = list(filter(lambda el: el in dictionary, key_list)) if (len(filtered_list) == 0): return None return dictionary[filtered_list[0]] @staticmethod def safe_either(method, dictionary, key1, key2, default_value=None): """A helper-wrapper for the safe_value_2() family.""" value = method(dictionary, key1) return value if value is not None else method(dictionary, key2, default_value) @staticmethod def truncate(num, precision=0): """Deprecated, use decimal_to_precision instead""" if precision > 0: decimal_precision = math.pow(10, precision) return math.trunc(num * decimal_precision) / decimal_precision return int(Exchange.truncate_to_string(num, precision)) @staticmethod def truncate_to_string(num, precision=0): """Deprecated, todo: remove references from subclasses""" if precision > 0: parts = ('{0:.%df}' % precision).format(Decimal(num)).split('.') decimal_digits = parts[1][:precision].rstrip('0') decimal_digits = decimal_digits if len(decimal_digits) else '0' return parts[0] + '.' + decimal_digits return ('%d' % num) @staticmethod def uuid22(length=22): return format(random.getrandbits(length * 4), 'x') @staticmethod def uuid16(length=16): return format(random.getrandbits(length * 4), 'x') @staticmethod def uuid(): return str(uuid.uuid4()) @staticmethod def uuidv1(): return str(uuid.uuid1()).replace('-', '') @staticmethod def capitalize(string): # first character only, rest characters unchanged # the native pythonic .capitalize() method lowercases all other characters # which is an unwanted behaviour, therefore we use this custom implementation # check it yourself: print('foobar'.capitalize(), 'fooBar'.capitalize()) if len(string) > 1: return "%s%s" % (string[0].upper(), string[1:]) return string.upper() @staticmethod def strip(string): return string.strip() @staticmethod def keysort(dictionary): return collections.OrderedDict(sorted(dictionary.items(), key=lambda t: t[0])) @staticmethod def extend(*args): if args is not None: result = None if type(args[0]) is collections.OrderedDict: result = collections.OrderedDict() else: result = {} for arg in args: result.update(arg) return result return {} @staticmethod def deep_extend(*args): result = None for arg in args: if isinstance(arg, dict): if not isinstance(result, dict): result = {} for key in arg: result[key] = Exchange.deep_extend(result[key] if key in result else None, arg[key]) else: result = arg return result @staticmethod def filter_by(array, key, value=None): array = Exchange.to_array(array) return list(filter(lambda x: x[key] == value, array)) @staticmethod def filterBy(array, key, value=None): return Exchange.filter_by(array, key, value) @staticmethod def group_by(array, key): result = {} array = Exchange.to_array(array) array = [entry for entry in array if (key in entry) and (entry[key] is not None)] for entry in array: if entry[key] not in result: result[entry[key]] = [] result[entry[key]].append(entry) return result @staticmethod def groupBy(array, key): return Exchange.group_by(array, key) @staticmethod def index_by(array, key): result = {} if type(array) is dict: array = Exchange.keysort(array).values() is_int_key = isinstance(key, int) for element in array: if ((is_int_key and (key < len(element))) or (key in element)) and (element[key] is not None): k = element[key] result[k] = element return result @staticmethod def sort_by(array, key, descending=False): return sorted(array, key=lambda k: k[key] if k[key] is not None else "", reverse=descending) @staticmethod def sort_by_2(array, key1, key2, descending=False): return sorted(array, key=lambda k: (k[key1] if k[key1] is not None else "", k[key2] if k[key2] is not None else ""), reverse=descending) @staticmethod def array_concat(a, b): return a + b @staticmethod def in_array(needle, haystack): return needle in haystack @staticmethod def is_empty(object): return not object @staticmethod def extract_params(string): return re.findall(r'{([\w-]+)}', string) @staticmethod def implode_params(string, params): if isinstance(params, dict): for key in params: if not isinstance(params[key], list): string = string.replace('{' + key + '}', str(params[key])) return string @staticmethod def urlencode(params={}, doseq=False): for key, value in params.items(): if isinstance(value, bool): params[key] = 'true' if value else 'false' return _urlencode.urlencode(params, doseq) @staticmethod def urlencode_with_array_repeat(params={}): return re.sub(r'%5B\d*%5D', '', Exchange.urlencode(params, True)) @staticmethod def urlencode_nested(params): result = {} def _encode_params(params, p_key=None): encode_params = {} if isinstance(params, dict): for key in params: encode_key = '{}[{}]'.format(p_key, key) encode_params[encode_key] = params[key] elif isinstance(params, (list, tuple)): for offset, value in enumerate(params): encode_key = '{}[{}]'.format(p_key, offset) encode_params[encode_key] = value else: result[p_key] = params for key in encode_params: value = encode_params[key] _encode_params(value, key) if isinstance(params, dict): for key in params: _encode_params(params[key], key) return _urlencode.urlencode(result) @staticmethod def rawencode(params={}): return _urlencode.unquote(Exchange.urlencode(params)) @staticmethod def encode_uri_component(uri, safe="~()*!.'"): return _urlencode.quote(uri, safe=safe) @staticmethod def omit(d, *args): if isinstance(d, dict): result = d.copy() for arg in args: if type(arg) is list: for key in arg: if key in result: del result[key] else: if arg in result: del result[arg] return result return d @staticmethod def unique(array): return list(set(array)) @staticmethod def pluck(array, key): return [ element[key] for element in array if (key in element) and (element[key] is not None) ] @staticmethod def sum(*args): return sum([arg for arg in args if isinstance(arg, (float, int))]) @staticmethod def ordered(array): return collections.OrderedDict(array) @staticmethod def aggregate(bidasks): ordered = Exchange.ordered({}) for [price, volume, *_] in bidasks: if volume > 0: ordered[price] = (ordered[price] if price in ordered else 0) + volume result = [] items = list(ordered.items()) for price, volume in items: result.append([price, volume]) return result @staticmethod def sec(): return Exchange.seconds() @staticmethod def msec(): return Exchange.milliseconds() @staticmethod def usec(): return Exchange.microseconds() @staticmethod def seconds(): return int(time.time()) @staticmethod def milliseconds(): return int(time.time() * 1000) @staticmethod def microseconds(): return int(time.time() * 1000000) @staticmethod def iso8601(timestamp=None): if timestamp is None: return timestamp if not isinstance(timestamp, int): return None if int(timestamp) < 0: return None try: utc = datetime.datetime.utcfromtimestamp(timestamp // 1000) return utc.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-6] + "{:03d}".format(int(timestamp) % 1000) + 'Z' except (TypeError, OverflowError, OSError): return None @staticmethod def rfc2616(self, timestamp=None): if timestamp is None: ts = datetime.datetime.now() else: ts = timestamp stamp = mktime(ts.timetuple()) return format_date_time(stamp) @staticmethod def dmy(timestamp, infix='-'): utc_datetime = datetime.datetime.utcfromtimestamp(int(round(timestamp / 1000))) return utc_datetime.strftime('%m' + infix + '%d' + infix + '%Y') @staticmethod def ymd(timestamp, infix='-', fullYear=True): year_format = '%Y' if fullYear else '%y' utc_datetime = datetime.datetime.utcfromtimestamp(int(round(timestamp / 1000))) return utc_datetime.strftime(year_format + infix + '%m' + infix + '%d') @staticmethod def yymmdd(timestamp, infix=''): return Exchange.ymd(timestamp, infix, False) @staticmethod def yyyymmdd(timestamp, infix='-'): return Exchange.ymd(timestamp, infix, True) @staticmethod def ymdhms(timestamp, infix=' '): utc_datetime = datetime.datetime.utcfromtimestamp(int(round(timestamp / 1000))) return utc_datetime.strftime('%Y-%m-%d' + infix + '%H:%M:%S') @staticmethod def parse_date(timestamp=None): if timestamp is None: return timestamp if not isinstance(timestamp, str): return None if 'GMT' in timestamp: try: string = ''.join([str(value) for value in parsedate(timestamp)[:6]]) + '.000Z' dt = datetime.datetime.strptime(string, "%Y%m%d%H%M%S.%fZ") return calendar.timegm(dt.utctimetuple()) * 1000 except (TypeError, OverflowError, OSError): return None else: return Exchange.parse8601(timestamp) @staticmethod def parse8601(timestamp=None): if timestamp is None: return timestamp yyyy = '([0-9]{4})-?' mm = '([0-9]{2})-?' dd = '([0-9]{2})(?:T|[\\s])?' h = '([0-9]{2}):?' m = '([0-9]{2}):?' s = '([0-9]{2})' ms = '(\\.[0-9]{1,3})?' tz = '(?:(\\+|\\-)([0-9]{2})\\:?([0-9]{2})|Z)?' regex = r'' + yyyy + mm + dd + h + m + s + ms + tz try: match = re.search(regex, timestamp, re.IGNORECASE) if match is None: return None yyyy, mm, dd, h, m, s, ms, sign, hours, minutes = match.groups() ms = ms or '.000' ms = (ms + '00')[0:4] msint = int(ms[1:]) sign = sign or '' sign = int(sign + '1') * -1 hours = int(hours or 0) * sign minutes = int(minutes or 0) * sign offset = datetime.timedelta(hours=hours, minutes=minutes) string = yyyy + mm + dd + h + m + s + ms + 'Z' dt = datetime.datetime.strptime(string, "%Y%m%d%H%M%S.%fZ") dt = dt + offset return calendar.timegm(dt.utctimetuple()) * 1000 + msint except (TypeError, OverflowError, OSError, ValueError): return None @staticmethod def hash(request, algorithm='md5', digest='hex'): if algorithm == 'keccak': binary = bytes(keccak.SHA3(request)) else: h = hashlib.new(algorithm, request) binary = h.digest() if digest == 'base64': return Exchange.binary_to_base64(binary) elif digest == 'hex': return Exchange.binary_to_base16(binary) return binary @staticmethod def hmac(request, secret, algorithm=hashlib.sha256, digest='hex'): h = hmac.new(secret, request, algorithm) binary = h.digest() if digest == 'hex': return Exchange.binary_to_base16(binary) elif digest == 'base64': return Exchange.binary_to_base64(binary) return binary @staticmethod def binary_concat(*args): result = bytes() for arg in args: result = result + arg return result @staticmethod def binary_concat_array(array): result = bytes() for element in array: result = result + element return result @staticmethod def base64urlencode(s): return Exchange.decode(base64.urlsafe_b64encode(s)).replace('=', '') @staticmethod def binary_to_base64(s): return Exchange.decode(base64.standard_b64encode(s)) @staticmethod def base64_to_binary(s): return base64.standard_b64decode(s) @staticmethod def string_to_base64(s): # will return string in the future binary = Exchange.encode(s) if isinstance(s, str) else s return Exchange.encode(Exchange.binary_to_base64(binary)) @staticmethod def base64_to_string(s): return base64.b64decode(s).decode('utf-8') @staticmethod def jwt(request, secret, alg='HS256'): algos = { 'HS256': hashlib.sha256, 'HS384': hashlib.sha384, 'HS512': hashlib.sha512, } header = Exchange.encode(Exchange.json({ 'alg': alg, 'typ': 'JWT', })) encoded_header = Exchange.base64urlencode(header) encoded_data = Exchange.base64urlencode(Exchange.encode(Exchange.json(request))) token = encoded_header + '.' + encoded_data if alg[:2] == 'RS': signature = Exchange.rsa(token, secret, alg) else: algorithm = algos[alg] signature = Exchange.hmac(Exchange.encode(token), secret, algorithm, 'binary') return token + '.' + Exchange.base64urlencode(signature) @staticmethod def rsa(request, secret, alg='RS256'): algorithms = { "RS256": hashes.SHA256(), "RS384": hashes.SHA384(), "RS512": hashes.SHA512(), } algorithm = algorithms[alg] priv_key = load_pem_private_key(secret, None, backends.default_backend()) return priv_key.sign(Exchange.encode(request), padding.PKCS1v15(), algorithm) @staticmethod def ecdsa(request, secret, algorithm='p256', hash=None, fixed_length=False): # your welcome - frosty00 algorithms = { 'p192': [ecdsa.NIST192p, 'sha256'], 'p224': [ecdsa.NIST224p, 'sha256'], 'p256': [ecdsa.NIST256p, 'sha256'], 'p384': [ecdsa.NIST384p, 'sha384'], 'p521': [ecdsa.NIST521p, 'sha512'], 'secp256k1': [ecdsa.SECP256k1, 'sha256'], } if algorithm not in algorithms: raise ArgumentsRequired(algorithm + ' is not a supported algorithm') curve_info = algorithms[algorithm] hash_function = getattr(hashlib, curve_info[1]) encoded_request = Exchange.encode(request) if hash is not None: digest = Exchange.hash(encoded_request, hash, 'binary') else: digest = base64.b16decode(encoded_request, casefold=True) key = ecdsa.SigningKey.from_string(base64.b16decode(Exchange.encode(secret), casefold=True), curve=curve_info[0]) r_binary, s_binary, v = key.sign_digest_deterministic(digest, hashfunc=hash_function, sigencode=ecdsa.util.sigencode_strings_canonize) r_int, s_int = ecdsa.util.sigdecode_strings((r_binary, s_binary), key.privkey.order) counter = 0 minimum_size = (1 << (8 * 31)) - 1 half_order = key.privkey.order / 2 while fixed_length and (r_int > half_order or r_int <= minimum_size or s_int <= minimum_size): r_binary, s_binary, v = key.sign_digest_deterministic(digest, hashfunc=hash_function, sigencode=ecdsa.util.sigencode_strings_canonize, extra_entropy=Exchange.number_to_le(counter, 32)) r_int, s_int = ecdsa.util.sigdecode_strings((r_binary, s_binary), key.privkey.order) counter += 1 r, s = Exchange.decode(base64.b16encode(r_binary)).lower(), Exchange.decode(base64.b16encode(s_binary)).lower() return { 'r': r, 's': s, 'v': v, } @staticmethod def eddsa(request, secret, curve='ed25519'): random = b'\x00' * 64 request = base64.b16decode(request, casefold=True) secret = base64.b16decode(secret, casefold=True) signature = eddsa.calculateSignature(random, secret, request) return Exchange.binary_to_base58(signature) @staticmethod def json(data, params=None): return json.dumps(data, separators=(',', ':')) @staticmethod def is_json_encoded_object(input): return (isinstance(input, str) and (len(input) >= 2) and ((input[0] == '{') or (input[0] == '['))) @staticmethod def encode(string): return string.encode('latin-1') @staticmethod def decode(string): return string.decode('latin-1') @staticmethod def to_array(value): return list(value.values()) if type(value) is dict else value @staticmethod def check_required_version(required_version, error=True): result = True [major1, minor1, patch1] = required_version.split('.') [major2, minor2, patch2] = __version__.split('.') int_major1 = int(major1) int_minor1 = int(minor1) int_patch1 = int(patch1) int_major2 = int(major2) int_minor2 = int(minor2) int_patch2 = int(patch2) if int_major1 > int_major2: result = False if int_major1 == int_major2: if int_minor1 > int_minor2: result = False elif int_minor1 == int_minor2 and int_patch1 > int_patch2: result = False if not result: if error: raise NotSupported('Your current version of CCXT is ' + __version__ + ', a newer version ' + required_version + ' is required, please, upgrade your version of CCXT') else: return error return result def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" if address is None: raise InvalidAddress(self.id + ' address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddressLength or ' ' in address: raise InvalidAddress(self.id + ' address is invalid or has less than ' + str(self.minFundingAddressLength) + ' characters: "' + str(address) + '"') return address def precision_from_string(self, string): parts = re.sub(r'0+$', '', string).split('.') return len(parts[1]) if len(parts) > 1 else 0 def load_markets(self, reload=False, params={}): if not reload: if self.markets: if not self.markets_by_id: return self.set_markets(self.markets) return self.markets currencies = None if self.has['fetchCurrencies'] is True: currencies = self.fetch_currencies() markets = self.fetch_markets(params) return self.set_markets(markets, currencies) def load_fees(self, reload=False): if not reload: if self.loaded_fees != Exchange.loaded_fees: return self.loaded_fees self.loaded_fees = self.deep_extend(self.loaded_fees, self.fetch_fees()) return self.loaded_fees def fetch_markets(self, params={}): # markets are returned as a list # currencies are returned as a dict # this is for historical reasons # and may be changed for consistency later return self.to_array(self.markets) def fetch_currencies(self, params={}): # markets are returned as a list # currencies are returned as a dict # this is for historical reasons # and may be changed for consistency later return self.currencies def fetch_fees(self): trading = {} funding = {} if self.has['fetchTradingFees']: trading = self.fetch_trading_fees() if self.has['fetchFundingFees']: funding = self.fetch_funding_fees() return { 'trading': trading, 'funding': funding, } def fetch_order_trades(self, id, symbol=None, params={}): raise NotSupported(self.id + ' fetch_order_trades() is not supported yet') def build_ohlcvc(self, trades, timeframe='1m', since=None, limit=None): ms = self.parse_timeframe(timeframe) * 1000 ohlcvs = [] (timestamp, open, high, low, close, volume, count) = (0, 1, 2, 3, 4, 5, 6) num_trades = len(trades) oldest = (num_trades - 1) if limit is None else min(num_trades - 1, limit) for i in range(0, oldest): trade = trades[i] if (since is not None) and (trade['timestamp'] < since): continue opening_time = None if trade['timestamp']: opening_time = int(math.floor(trade['timestamp'] / ms) * ms) # Shift the edge of the m/h/d (but not M) j = len(ohlcvs) candle = j - 1 if (j == 0) or (opening_time and opening_time >= ohlcvs[candle][timestamp] + ms): # moved to a new timeframe -> create a new candle from opening trade ohlcvs.append([ opening_time, trade['price'], trade['price'], trade['price'], trade['price'], trade['amount'], 1, # count ]) else: # still processing the same timeframe -> update opening trade ohlcvs[candle][high] = max(ohlcvs[candle][high], trade['price']) ohlcvs[candle][low] = min(ohlcvs[candle][low], trade['price']) ohlcvs[candle][close] = trade['price'] ohlcvs[candle][volume] += trade['amount'] ohlcvs[candle][count] += 1 return ohlcvs @staticmethod def parse_timeframe(timeframe): amount = int(timeframe[0:-1]) unit = timeframe[-1] if 'y' == unit: scale = 60 * 60 * 24 * 365 elif 'M' == unit: scale = 60 * 60 * 24 * 30 elif 'w' == unit: scale = 60 * 60 * 24 * 7 elif 'd' == unit: scale = 60 * 60 * 24 elif 'h' == unit: scale = 60 * 60 elif 'm' == unit: scale = 60 elif 's' == unit: scale = 1 else: raise NotSupported('timeframe unit {} is not supported'.format(unit)) return amount * scale @staticmethod def round_timeframe(timeframe, timestamp, direction=ROUND_DOWN): ms = Exchange.parse_timeframe(timeframe) * 1000 # Get offset based on timeframe in milliseconds offset = timestamp % ms return timestamp - offset + (ms if direction == ROUND_UP else 0) def filter_by_value_since_limit(self, array, field, value=None, since=None, limit=None, key='timestamp', tail=False): array = self.to_array(array) if value is not None: array = [entry for entry in array if entry[field] == value] if since is not None: array = [entry for entry in array if entry[key] >= since] if limit is not None: array = array[-limit:] if tail else array[:limit] return array def filter_by_since_limit(self, array, since=None, limit=None, key='timestamp', tail=False): array = self.to_array(array) if since is not None: array = [entry for entry in array if entry[key] >= since] if limit is not None: array = array[-limit:] if tail else array[:limit] return array def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): raise NotSupported(self.id + ' sign() pure method must be redefined in derived classes') def vwap(self, baseVolume, quoteVolume): return (quoteVolume / baseVolume) if (quoteVolume is not None) and (baseVolume is not None) and (baseVolume > 0) else None def check_required_dependencies(self): if self.requiresEddsa and eddsa is None: raise NotSupported(self.id + ' Eddsa functionality requires python-axolotl-curve25519, install with `pip install python-axolotl-curve25519==0.4.1.post2`: https://github.com/tgalal/python-axolotl-curve25519') def privateKeyToAddress(self, privateKey): private_key_bytes = base64.b16decode(Exchange.encode(privateKey), True) public_key_bytes = ecdsa.SigningKey.from_string(private_key_bytes, curve=ecdsa.SECP256k1).verifying_key.to_string() public_key_hash = keccak.SHA3(public_key_bytes) return '0x' + Exchange.decode(base64.b16encode(public_key_hash))[-40:].lower() @staticmethod def remove0x_prefix(value): if value[:2] == '0x': return value[2:] return value def hashMessage(self, message): message_bytes = base64.b16decode(Exchange.encode(Exchange.remove0x_prefix(message)), True) hash_bytes = keccak.SHA3(b"\x19Ethereum Signed Message:\n" + Exchange.encode(str(len(message_bytes))) + message_bytes) return '0x' + Exchange.decode(base64.b16encode(hash_bytes)).lower() @staticmethod def signHash(hash, privateKey): signature = Exchange.ecdsa(hash[-64:], privateKey, 'secp256k1', None) return { 'r': '0x' + signature['r'], 's': '0x' + signature['s'], 'v': 27 + signature['v'], } def sign_message_string(self, message, privateKey): signature = self.signMessage(message, privateKey) return signature['r'] + Exchange.remove0x_prefix(signature['s']) + Exchange.binary_to_base16(Exchange.number_to_be(signature['v'], 1)) def signMessage(self, message, privateKey): # # The following comment is related to MetaMask, we use the upper type of signature prefix: # # z.ecSignOrderHashAsync ('0xcfdb0a485324ff37699b4c8557f6858f25916fc6fce5993b32fe018aea510b9f', # '0x731fc101bbe102221c91c31ed0489f1ddfc439a3', { # prefixType: 'ETH_SIGN', # shouldAddPrefixBeforeCallingEthSign: true # }).then ((e, r) => console.log (e,r)) # # { ↓ # v: 28, # r: "0xea7a68268b47c48d5d7a4c900e6f9af0015bf70951b3db2f1d835c5d544aaec2", # s: "0x5d1db2a060c955c1fde4c967237b995c2361097405407b33c6046c8aeb3ccbdf" # } # # -------------------------------------------------------------------- # # z.ecSignOrderHashAsync ('0xcfdb0a485324ff37699b4c8557f6858f25916fc6fce5993b32fe018aea510b9f', # '0x731fc101bbe102221c91c31ed0489f1ddfc439a3', { # prefixType: 'NONE', # shouldAddPrefixBeforeCallingEthSign: true # }).then ((e, r) => console.log (e,r)) # # { ↓ # v: 27, # r: "0xc8c710022c57de4f529d448e9b40517dd9bfb49ff1eb245f5856664b865d14a6", # s: "0x0740bb21f4f094fbbdbafa903bb8f057f82e0c6e4fe65d19a1daed4ed97cd394" # } # message_hash = self.hashMessage(message) signature = self.signHash(message_hash[-64:], privateKey[-64:]) return signature @staticmethod def totp(key): def hex_to_dec(n): return int(n, base=16) def base32_to_bytes(n): missing_padding = len(n) % 8 padding = 8 - missing_padding if missing_padding > 0 else 0 padded = n.upper() + ('=' * padding) return base64.b32decode(padded) # throws an error if the key is invalid epoch = int(time.time()) // 30 hmac_res = Exchange.hmac(epoch.to_bytes(8, 'big'), base32_to_bytes(key.replace(' ', '')), hashlib.sha1, 'hex') offset = hex_to_dec(hmac_res[-1]) * 2 otp = str(hex_to_dec(hmac_res[offset: offset + 8]) & 0x7fffffff) return otp[-6:] @staticmethod def number_to_le(n, size): return int(n).to_bytes(size, 'little') @staticmethod def number_to_be(n, size): return int(n).to_bytes(size, 'big') @staticmethod def base16_to_binary(s): return base64.b16decode(s, True) @staticmethod def binary_to_base16(s): return Exchange.decode(base64.b16encode(s)).lower() def sleep(self, milliseconds): return time.sleep(milliseconds / 1000) @staticmethod def base58_to_binary(s): """encodes a base58 string to as a big endian integer""" if Exchange.base58_decoder is None: Exchange.base58_decoder = {} Exchange.base58_encoder = {} for i, c in enumerate(Exchange.base58_alphabet): Exchange.base58_decoder[c] = i Exchange.base58_encoder[i] = c result = 0 for i in range(len(s)): result *= 58 result += Exchange.base58_decoder[s[i]] return result.to_bytes((result.bit_length() + 7) // 8, 'big') @staticmethod def binary_to_base58(b): if Exchange.base58_encoder is None: Exchange.base58_decoder = {} Exchange.base58_encoder = {} for i, c in enumerate(Exchange.base58_alphabet): Exchange.base58_decoder[c] = i Exchange.base58_encoder[i] = c result = 0 # undo decimal_to_bytes for byte in b: result *= 0x100 result += byte string = [] while result > 0: result, next_character = divmod(result, 58) string.append(Exchange.base58_encoder[next_character]) string.reverse() return ''.join(string) def parse_number(self, value, default=None): if value is None: return default else: try: return self.number(value) except Exception: return default def omit_zero(self, string_number): if string_number is None or string_number == '': return None if float(string_number) == 0: return None return string_number def check_order_arguments(self, market, type, side, amount, price, params): if price is None: if type == 'limit': raise ArgumentsRequired(self.id + ' create_order() requires a price argument for a limit order') if amount <= 0: raise ArgumentsRequired(self.id + ' create_order() amount should be above 0') def handle_http_status_code(self, code, reason, url, method, body): codeAsString = str(code) if codeAsString in self.httpExceptions: ErrorClass = self.httpExceptions[codeAsString] raise ErrorClass(self.id + ' ' + method + ' ' + url + ' ' + codeAsString + ' ' + reason + ' ' + body) @staticmethod def crc32(string, signed=False): unsigned = binascii.crc32(string.encode('utf8')) if signed and (unsigned >= 0x80000000): return unsigned - 0x100000000 else: return unsigned # ######################################################################## # ######################################################################## # ######################################################################## # ######################################################################## # ######## ######## ######## # ######## ######## ######## # ######## ######## ######## # ######## ######## ######## # ######## ######################## ######################## # ######## ######################## ######################## # ######## ######################## ######################## # ######## ######################## ######################## # ######## ######## ######## # ######## ######## ######## # ######## ######## ######## # ######## ######## ######## # ######################################################################## # ######################################################################## # ######################################################################## # ######################################################################## # ######## ######## ######## ######## # ######## ######## ######## ######## # ######## ######## ######## ######## # ######## ######## ######## ######## # ################ ######################## ################ # ################ ######################## ################ # ################ ######################## ################ # ################ ######################## ################ # ######## ######## ################ ################ # ######## ######## ################ ################ # ######## ######## ################ ################ # ######## ######## ################ ################ # ######################################################################## # ######################################################################## # ######################################################################## # ######################################################################## # METHODS BELOW THIS LINE ARE TRANSPILED FROM JAVASCRIPT TO PYTHON AND PHP def safe_ledger_entry(self, entry, currency=None): currency = self.safe_currency(None, currency) direction = self.safe_string(entry, 'direction') before = self.safe_string(entry, 'before') after = self.safe_string(entry, 'after') amount = self.safe_string(entry, 'amount') if amount is not None: if before is None and after is not None: before = Precise.string_sub(after, amount) elif before is not None and after is None: after = Precise.string_add(before, amount) if before is not None and after is not None: if direction is None: if Precise.string_gt(before, after): direction = 'out' if Precise.string_gt(after, before): direction = 'in' fee = self.safe_value(entry, 'fee') if fee is not None: fee['cost'] = self.safe_number(fee, 'cost') timestamp = self.safe_integer(entry, 'timestamp') return { 'id': self.safe_string(entry, 'id'), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'direction': direction, 'account': self.safe_string(entry, 'account'), 'referenceId': self.safe_string(entry, 'referenceId'), 'referenceAccount': self.safe_string(entry, 'referenceAccount'), 'type': self.safe_string(entry, 'type'), 'currency': currency['code'], 'amount': self.parse_number(amount), 'before': self.parse_number(before), 'after': self.parse_number(after), 'status': self.safe_string(entry, 'status'), 'fee': fee, 'info': entry, } def set_markets(self, markets, currencies=None): values = [] marketValues = self.to_array(markets) for i in range(0, len(marketValues)): market = self.deep_extend(self.safe_market(), { 'precision': self.precision, 'limits': self.limits, }, self.fees['trading'], marketValues[i]) values.append(market) self.markets = self.index_by(values, 'symbol') self.markets_by_id = self.index_by(markets, 'id') marketsSortedBySymbol = self.keysort(self.markets) marketsSortedById = self.keysort(self.markets_by_id) self.symbols = list(marketsSortedBySymbol.keys()) self.ids = list(marketsSortedById.keys()) if currencies is not None: self.currencies = self.deep_extend(self.currencies, currencies) else: baseCurrencies = [] quoteCurrencies = [] for i in range(0, len(values)): market = values[i] defaultCurrencyPrecision = 8 if (self.precisionMode == DECIMAL_PLACES) else self.parse_number('0.00000001') marketPrecision = self.safe_value(market, 'precision', {}) if 'base' in market: currencyPrecision = self.safe_value_2(marketPrecision, 'base', 'amount', defaultCurrencyPrecision) currency = { 'id': self.safe_string_2(market, 'baseId', 'base'), 'numericId': self.safe_string(market, 'baseNumericId'), 'code': self.safe_string(market, 'base'), 'precision': currencyPrecision, } baseCurrencies.append(currency) if 'quote' in market: currencyPrecision = self.safe_value_2(marketPrecision, 'quote', 'price', defaultCurrencyPrecision) currency = { 'id': self.safe_string_2(market, 'quoteId', 'quote'), 'numericId': self.safe_string(market, 'quoteNumericId'), 'code': self.safe_string(market, 'quote'), 'precision': currencyPrecision, } quoteCurrencies.append(currency) baseCurrencies = self.sort_by(baseCurrencies, 'code') quoteCurrencies = self.sort_by(quoteCurrencies, 'code') self.baseCurrencies = self.index_by(baseCurrencies, 'code') self.quoteCurrencies = self.index_by(quoteCurrencies, 'code') allCurrencies = self.array_concat(baseCurrencies, quoteCurrencies) groupedCurrencies = self.group_by(allCurrencies, 'code') codes = list(groupedCurrencies.keys()) resultingCurrencies = [] for i in range(0, len(codes)): code = codes[i] groupedCurrenciesCode = self.safe_value(groupedCurrencies, code, []) highestPrecisionCurrency = self.safe_value(groupedCurrenciesCode, 0) for j in range(1, len(groupedCurrenciesCode)): currentCurrency = groupedCurrenciesCode[j] if self.precisionMode == TICK_SIZE: highestPrecisionCurrency = currentCurrency if (currentCurrency['precision'] < highestPrecisionCurrency['precision']) else highestPrecisionCurrency else: highestPrecisionCurrency = currentCurrency if (currentCurrency['precision'] > highestPrecisionCurrency['precision']) else highestPrecisionCurrency resultingCurrencies.append(highestPrecisionCurrency) sortedCurrencies = self.sort_by(resultingCurrencies, 'code') self.currencies = self.deep_extend(self.currencies, self.index_by(sortedCurrencies, 'code')) self.currencies_by_id = self.index_by(self.currencies, 'id') currenciesSortedByCode = self.keysort(self.currencies) self.codes = list(currenciesSortedByCode.keys()) return self.markets def safe_balance(self, balance): balances = self.omit(balance, ['info', 'timestamp', 'datetime', 'free', 'used', 'total']) codes = list(balances.keys()) balance['free'] = {} balance['used'] = {} balance['total'] = {} debtBalance = {} for i in range(0, len(codes)): code = codes[i] total = self.safe_string(balance[code], 'total') free = self.safe_string(balance[code], 'free') used = self.safe_string(balance[code], 'used') debt = self.safe_string(balance[code], 'debt') if (total is None) and (free is not None) and (used is not None): total = Precise.string_add(free, used) if (free is None) and (total is not None) and (used is not None): free = Precise.string_sub(total, used) if (used is None) and (total is not None) and (free is not None): used = Precise.string_sub(total, free) balance[code]['free'] = self.parse_number(free) balance[code]['used'] = self.parse_number(used) balance[code]['total'] = self.parse_number(total) balance['free'][code] = balance[code]['free'] balance['used'][code] = balance[code]['used'] balance['total'][code] = balance[code]['total'] if debt is not None: balance[code]['debt'] = self.parse_number(debt) debtBalance[code] = balance[code]['debt'] debtBalanceArray = list(debtBalance.keys()) length = len(debtBalanceArray) if length: balance['debt'] = debtBalance return balance def safe_order(self, order, market=None): # parses numbers as strings # it is important pass the trades as unparsed rawTrades amount = self.omit_zero(self.safe_string(order, 'amount')) remaining = self.safe_string(order, 'remaining') filled = self.safe_string(order, 'filled') cost = self.safe_string(order, 'cost') average = self.omit_zero(self.safe_string(order, 'average')) price = self.omit_zero(self.safe_string(order, 'price')) lastTradeTimeTimestamp = self.safe_integer(order, 'lastTradeTimestamp') parseFilled = (filled is None) parseCost = (cost is None) parseLastTradeTimeTimestamp = (lastTradeTimeTimestamp is None) fee = self.safe_value(order, 'fee') parseFee = (fee is None) parseFees = self.safe_value(order, 'fees') is None shouldParseFees = parseFee or parseFees fees = self.safe_value(order, 'fees', []) trades = [] if parseFilled or parseCost or shouldParseFees: rawTrades = self.safe_value(order, 'trades', trades) oldNumber = self.number # we parse trades as strings here! self.number = str trades = self.parse_trades(rawTrades, market, None, None, { 'symbol': order['symbol'], 'side': order['side'], 'type': order['type'], 'order': order['id'], }) self.number = oldNumber tradesLength = 0 isArray = isinstance(trades, list) if isArray: tradesLength = len(trades) if isArray and (tradesLength > 0): # move properties that are defined in trades up into the order if order['symbol'] is None: order['symbol'] = trades[0]['symbol'] if order['side'] is None: order['side'] = trades[0]['side'] if order['type'] is None: order['type'] = trades[0]['type'] if order['id'] is None: order['id'] = trades[0]['order'] if parseFilled: filled = '0' if parseCost: cost = '0' for i in range(0, len(trades)): trade = trades[i] tradeAmount = self.safe_string(trade, 'amount') if parseFilled and (tradeAmount is not None): filled = Precise.string_add(filled, tradeAmount) tradeCost = self.safe_string(trade, 'cost') if parseCost and (tradeCost is not None): cost = Precise.string_add(cost, tradeCost) tradeTimestamp = self.safe_value(trade, 'timestamp') if parseLastTradeTimeTimestamp and (tradeTimestamp is not None): if lastTradeTimeTimestamp is None: lastTradeTimeTimestamp = tradeTimestamp else: lastTradeTimeTimestamp = max(lastTradeTimeTimestamp, tradeTimestamp) if shouldParseFees: tradeFees = self.safe_value(trade, 'fees') if tradeFees is not None: for j in range(0, len(tradeFees)): tradeFee = tradeFees[j] fees.append(self.extend({}, tradeFee)) else: tradeFee = self.safe_value(trade, 'fee') if tradeFee is not None: fees.append(self.extend({}, tradeFee)) if shouldParseFees: reducedFees = self.reduce_fees_by_currency(fees) if self.reduceFees else fees reducedLength = len(reducedFees) for i in range(0, reducedLength): reducedFees[i]['cost'] = self.safe_number(reducedFees[i], 'cost') if 'rate' in reducedFees[i]: reducedFees[i]['rate'] = self.safe_number(reducedFees[i], 'rate') if not parseFee and (reducedLength == 0): fee['cost'] = self.safe_number(fee, 'cost') if 'rate' in fee: fee['rate'] = self.safe_number(fee, 'rate') reducedFees.append(fee) order['fees'] = reducedFees if parseFee and (reducedLength == 1): order['fee'] = reducedFees[0] if amount is None: # ensure amount = filled + remaining if filled is not None and remaining is not None: amount = Precise.string_add(filled, remaining) elif self.safe_string(order, 'status') == 'closed': amount = filled if filled is None: if amount is not None and remaining is not None: filled = Precise.string_sub(amount, remaining) if remaining is None: if amount is not None and filled is not None: remaining = Precise.string_sub(amount, filled) # ensure that the average field is calculated correctly if average is None: if (filled is not None) and (cost is not None) and Precise.string_gt(filled, '0'): average = Precise.string_div(cost, filled) # also ensure the cost field is calculated correctly costPriceExists = (average is not None) or (price is not None) if parseCost and (filled is not None) and costPriceExists: multiplyPrice = None if average is None: multiplyPrice = price else: multiplyPrice = average # contract trading contractSize = self.safe_string(market, 'contractSize') if contractSize is not None: inverse = self.safe_value(market, 'inverse', False) if inverse: multiplyPrice = Precise.string_div('1', multiplyPrice) multiplyPrice = Precise.string_mul(multiplyPrice, contractSize) cost = Precise.string_mul(multiplyPrice, filled) # support for market orders orderType = self.safe_value(order, 'type') emptyPrice = (price is None) or Precise.string_equals(price, '0') if emptyPrice and (orderType == 'market'): price = average # we have trades with string values at self point so we will mutate them for i in range(0, len(trades)): entry = trades[i] entry['amount'] = self.safe_number(entry, 'amount') entry['price'] = self.safe_number(entry, 'price') entry['cost'] = self.safe_number(entry, 'cost') fee = self.safe_value(entry, 'fee', {}) fee['cost'] = self.safe_number(fee, 'cost') if 'rate' in fee: fee['rate'] = self.safe_number(fee, 'rate') entry['fee'] = fee # timeInForceHandling timeInForce = self.safe_string(order, 'timeInForce') if timeInForce is None: if self.safe_string(order, 'type') == 'market': timeInForce = 'IOC' # allow postOnly override if self.safe_value(order, 'postOnly', False): timeInForce = 'PO' return self.extend(order, { 'lastTradeTimestamp': lastTradeTimeTimestamp, 'price': self.parse_number(price), 'amount': self.parse_number(amount), 'cost': self.parse_number(cost), 'average': self.parse_number(average), 'filled': self.parse_number(filled), 'remaining': self.parse_number(remaining), 'timeInForce': timeInForce, 'trades': trades, }) def parse_orders(self, orders, market=None, since=None, limit=None, params={}): # # the value of orders is either a dict or a list # # dict # # { # 'id1': {...}, # 'id2': {...}, # 'id3': {...}, # ... # } # # list # # [ # {'id': 'id1', ...}, # {'id': 'id2', ...}, # {'id': 'id3', ...}, # ... # ] # results = [] if isinstance(orders, list): for i in range(0, len(orders)): order = self.extend(self.parse_order(orders[i], market), params) results.append(order) else: ids = list(orders.keys()) for i in range(0, len(ids)): id = ids[i] order = self.extend(self.parse_order(self.extend({'id': id}, orders[id]), market), params) results.append(order) results = self.sort_by(results, 'timestamp') symbol = market['symbol'] if (market is not None) else None tail = since is None return self.filter_by_symbol_since_limit(results, symbol, since, limit, tail) def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}): if type == 'market' and takerOrMaker == 'maker': raise ArgumentsRequired(self.id + ' calculateFee() - you have provided incompatible arguments - "market" type order can not be "maker". Change either the "type" or the "takerOrMaker" argument to calculate the fee.') market = self.markets[symbol] feeSide = self.safe_string(market, 'feeSide', 'quote') key = 'quote' cost = None amountString = self.number_to_string(amount) priceString = self.number_to_string(price) if feeSide == 'quote': # the fee is always in quote currency cost = Precise.string_mul(amountString, priceString) elif feeSide == 'base': # the fee is always in base currency cost = amountString elif feeSide == 'get': # the fee is always in the currency you get cost = amountString if side == 'sell': cost = Precise.string_mul(cost, priceString) else: key = 'base' elif feeSide == 'give': # the fee is always in the currency you give cost = amountString if side == 'buy': cost = Precise.string_mul(cost, priceString) else: key = 'base' # for derivatives, the fee is in 'settle' currency if not market['spot']: key = 'settle' # even if `takerOrMaker` argument was set to 'maker', for 'market' orders we should forcefully override it to 'taker' if type == 'market': takerOrMaker = 'taker' rate = self.safe_string(market, takerOrMaker) if cost is not None: cost = Precise.string_mul(cost, rate) return { 'type': takerOrMaker, 'currency': market[key], 'rate': self.parse_number(rate), 'cost': self.parse_number(cost), } def safe_trade(self, trade, market=None): amount = self.safe_string(trade, 'amount') price = self.safe_string(trade, 'price') cost = self.safe_string(trade, 'cost') if cost is None: # contract trading contractSize = self.safe_string(market, 'contractSize') multiplyPrice = price if contractSize is not None: inverse = self.safe_value(market, 'inverse', False) if inverse: multiplyPrice = Precise.string_div('1', price) multiplyPrice = Precise.string_mul(multiplyPrice, contractSize) cost = Precise.string_mul(multiplyPrice, amount) parseFee = self.safe_value(trade, 'fee') is None parseFees = self.safe_value(trade, 'fees') is None shouldParseFees = parseFee or parseFees fees = [] if shouldParseFees: tradeFees = self.safe_value(trade, 'fees') if tradeFees is not None: for j in range(0, len(tradeFees)): tradeFee = tradeFees[j] fees.append(self.extend({}, tradeFee)) else: tradeFee = self.safe_value(trade, 'fee') if tradeFee is not None: fees.append(self.extend({}, tradeFee)) fee = self.safe_value(trade, 'fee') if shouldParseFees: reducedFees = self.reduce_fees_by_currency(fees) if self.reduceFees else fees reducedLength = len(reducedFees) for i in range(0, reducedLength): reducedFees[i]['cost'] = self.safe_number(reducedFees[i], 'cost') if 'rate' in reducedFees[i]: reducedFees[i]['rate'] = self.safe_number(reducedFees[i], 'rate') if not parseFee and (reducedLength == 0): fee['cost'] = self.safe_number(fee, 'cost') if 'rate' in fee: fee['rate'] = self.safe_number(fee, 'rate') reducedFees.append(fee) if parseFees: trade['fees'] = reducedFees if parseFee and (reducedLength == 1): trade['fee'] = reducedFees[0] tradeFee = self.safe_value(trade, 'fee') if tradeFee is not None: tradeFee['cost'] = self.safe_number(tradeFee, 'cost') if 'rate' in tradeFee: tradeFee['rate'] = self.safe_number(tradeFee, 'rate') trade['fee'] = tradeFee trade['amount'] = self.parse_number(amount) trade['price'] = self.parse_number(price) trade['cost'] = self.parse_number(cost) return trade def reduce_fees_by_currency(self, fees): # # self function takes a list of fee structures having the following format # # string = True # # [ # {'currency': 'BTC', 'cost': '0.1'}, # {'currency': 'BTC', 'cost': '0.2' }, # {'currency': 'BTC', 'cost': '0.2', 'rate': '0.00123'}, # {'currency': 'BTC', 'cost': '0.4', 'rate': '0.00123'}, # {'currency': 'BTC', 'cost': '0.5', 'rate': '0.00456'}, # {'currency': 'USDT', 'cost': '12.3456'}, # ] # # string = False # # [ # {'currency': 'BTC', 'cost': 0.1}, # {'currency': 'BTC', 'cost': 0.2}, # {'currency': 'BTC', 'cost': 0.2, 'rate': 0.00123}, # {'currency': 'BTC', 'cost': 0.4, 'rate': 0.00123}, # {'currency': 'BTC', 'cost': 0.5, 'rate': 0.00456}, # {'currency': 'USDT', 'cost': 12.3456}, # ] # # and returns a reduced fee list, where fees are summed per currency and rate(if any) # # string = True # # [ # {'currency': 'BTC', 'cost': '0.3' }, # {'currency': 'BTC', 'cost': '0.6', 'rate': '0.00123'}, # {'currency': 'BTC', 'cost': '0.5', 'rate': '0.00456'}, # {'currency': 'USDT', 'cost': '12.3456'}, # ] # # string = False # # [ # {'currency': 'BTC', 'cost': 0.3 }, # {'currency': 'BTC', 'cost': 0.6, 'rate': 0.00123}, # {'currency': 'BTC', 'cost': 0.5, 'rate': 0.00456}, # {'currency': 'USDT', 'cost': 12.3456}, # ] # reduced = {} for i in range(0, len(fees)): fee = fees[i] feeCurrencyCode = self.safe_string(fee, 'currency') if feeCurrencyCode is not None: rate = self.safe_string(fee, 'rate') cost = self.safe_value(fee, 'cost') if Precise.string_eq(cost, '0'): # omit zero cost fees continue if not (feeCurrencyCode in reduced): reduced[feeCurrencyCode] = {} rateKey = '' if (rate is None) else rate if rateKey in reduced[feeCurrencyCode]: reduced[feeCurrencyCode][rateKey]['cost'] = Precise.string_add(reduced[feeCurrencyCode][rateKey]['cost'], cost) else: reduced[feeCurrencyCode][rateKey] = { 'currency': feeCurrencyCode, 'cost': cost, } if rate is not None: reduced[feeCurrencyCode][rateKey]['rate'] = rate result = [] feeValues = list(reduced.values()) for i in range(0, len(feeValues)): reducedFeeValues = list(feeValues[i].values()) result = self.array_concat(result, reducedFeeValues) return result def safe_ticker(self, ticker, market=None): open = self.safe_value(ticker, 'open') close = self.safe_value(ticker, 'close') last = self.safe_value(ticker, 'last') change = self.safe_value(ticker, 'change') percentage = self.safe_value(ticker, 'percentage') average = self.safe_value(ticker, 'average') vwap = self.safe_value(ticker, 'vwap') baseVolume = self.safe_value(ticker, 'baseVolume') quoteVolume = self.safe_value(ticker, 'quoteVolume') if vwap is None: vwap = Precise.string_div(quoteVolume, baseVolume) if (last is not None) and (close is None): close = last elif (last is None) and (close is not None): last = close if (last is not None) and (open is not None): if change is None: change = Precise.string_sub(last, open) if average is None: average = Precise.string_div(Precise.string_add(last, open), '2') if (percentage is None) and (change is not None) and (open is not None) and Precise.string_gt(open, '0'): percentage = Precise.string_mul(Precise.string_div(change, open), '100') if (change is None) and (percentage is not None) and (open is not None): change = Precise.string_div(Precise.string_mul(percentage, open), '100') if (open is None) and (last is not None) and (change is not None): open = Precise.string_sub(last, change) # timestamp and symbol operations don't belong in safeTicker # they should be done in the derived classes return self.extend(ticker, { 'bid': self.safe_number(ticker, 'bid'), 'bidVolume': self.safe_number(ticker, 'bidVolume'), 'ask': self.safe_number(ticker, 'ask'), 'askVolume': self.safe_number(ticker, 'askVolume'), 'high': self.safe_number(ticker, 'high'), 'low': self.safe_number(ticker, 'low'), 'open': self.parse_number(open), 'close': self.parse_number(close), 'last': self.parse_number(last), 'change': self.parse_number(change), 'percentage': self.parse_number(percentage), 'average': self.parse_number(average), 'vwap': self.parse_number(vwap), 'baseVolume': self.parse_number(baseVolume), 'quoteVolume': self.parse_number(quoteVolume), 'previousClose': self.safe_number(ticker, 'previousClose'), }) def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: raise NotSupported(self.id + ' fetchOHLCV() is not supported yet') self.load_markets() trades = self.fetchTrades(symbol, since, limit, params) ohlcvc = self.build_ohlcvc(trades, timeframe, since, limit) result = [] for i in range(0, len(ohlcvc)): result.append([ self.safe_integer(ohlcvc[i], 0), self.safe_number(ohlcvc[i], 1), self.safe_number(ohlcvc[i], 2), self.safe_number(ohlcvc[i], 3), self.safe_number(ohlcvc[i], 4), self.safe_number(ohlcvc[i], 5), ]) return result def convert_trading_view_to_ohlcv(self, ohlcvs, timestamp='t', open='o', high='h', low='l', close='c', volume='v', ms=False): result = [] timestamps = self.safe_value(ohlcvs, timestamp, []) opens = self.safe_value(ohlcvs, open, []) highs = self.safe_value(ohlcvs, high, []) lows = self.safe_value(ohlcvs, low, []) closes = self.safe_value(ohlcvs, close, []) volumes = self.safe_value(ohlcvs, volume, []) for i in range(0, len(timestamps)): result.append([ self.safe_integer(timestamps, i) if ms else self.safe_timestamp(timestamps, i), self.safe_value(opens, i), self.safe_value(highs, i), self.safe_value(lows, i), self.safe_value(closes, i), self.safe_value(volumes, i), ]) return result def convert_ohlcv_to_trading_view(self, ohlcvs, timestamp='t', open='o', high='h', low='l', close='c', volume='v', ms=False): result = {} result[timestamp] = [] result[open] = [] result[high] = [] result[low] = [] result[close] = [] result[volume] = [] for i in range(0, len(ohlcvs)): ts = ohlcvs[i][0] if ms else int(ohlcvs[i][0] / 1000) result[timestamp].append(ts) result[open].append(ohlcvs[i][1]) result[high].append(ohlcvs[i][2]) result[low].append(ohlcvs[i][3]) result[close].append(ohlcvs[i][4]) result[volume].append(ohlcvs[i][5]) return result def market_ids(self, symbols): result = [] for i in range(0, len(symbols)): result.append(self.market_id(symbols[i])) return result def market_symbols(self, symbols): if symbols is None: return symbols result = [] for i in range(0, len(symbols)): result.append(self.symbol(symbols[i])) return result def market_codes(self, codes): if codes is None: return codes result = [] for i in range(0, len(codes)): result.append(self.common_currency_code(codes[i])) return result def parse_bids_asks(self, bidasks, priceKey=0, amountKey=1): bidasks = self.to_array(bidasks) result = [] for i in range(0, len(bidasks)): result.append(self.parse_bid_ask(bidasks[i], priceKey, amountKey)) return result def fetch_l2_order_book(self, symbol, limit=None, params={}): orderbook = self.fetch_order_book(symbol, limit, params) return self.extend(orderbook, { 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0), 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True), }) def filter_by_symbol(self, objects, symbol=None): if symbol is None: return objects result = [] for i in range(0, len(objects)): objectSymbol = self.safe_string(objects[i], 'symbol') if objectSymbol == symbol: result.append(objects[i]) return result def parse_ohlcv(self, ohlcv, market=None): if isinstance(ohlcv, list): return [ self.safe_integer(ohlcv, 0), # timestamp self.safe_number(ohlcv, 1), # open self.safe_number(ohlcv, 2), # high self.safe_number(ohlcv, 3), # low self.safe_number(ohlcv, 4), # close self.safe_number(ohlcv, 5), # volume ] return ohlcv def get_network(self, network, code): network = network.upper() aliases = { 'ETHEREUM': 'ETH', 'ETHER': 'ETH', 'ERC20': 'ETH', 'ETH': 'ETH', 'TRC20': 'TRX', 'TRON': 'TRX', 'TRX': 'TRX', 'BEP20': 'BSC', 'BSC': 'BSC', 'HRC20': 'HT', 'HECO': 'HT', 'SPL': 'SOL', 'SOL': 'SOL', 'TERRA': 'LUNA', 'LUNA': 'LUNA', 'POLYGON': 'MATIC', 'MATIC': 'MATIC', 'EOS': 'EOS', 'WAVES': 'WAVES', 'AVALANCHE': 'AVAX', 'AVAX': 'AVAX', 'QTUM': 'QTUM', 'CHZ': 'CHZ', 'NEO': 'NEO', 'ONT': 'ONT', 'RON': 'RON', } if network == code: return network elif network in aliases: return aliases[network] else: raise NotSupported(self.id + ' network ' + network + ' is not yet supported') def network_code_to_id(self, networkCode): networks = self.safe_value(self.options, 'networks', {}) return self.safe_string(networks, networkCode, networkCode) def network_id_to_code(self, networkId): networksById = self.safe_value(self.options, 'networksById', {}) return self.safe_string(networksById, networkId, networkId) def handle_network_code_and_params(self, params): networkCodeInParams = self.safe_string_2(params, 'networkCode', 'network') if networkCodeInParams is not None: params = self.omit(params, ['networkCode', 'network']) # if it was not defined by user, we should not set it from 'defaultNetworks', because handleNetworkCodeAndParams is for only request-side and thus we do not fill it with anything. We can only use 'defaultNetworks' after parsing response-side return [networkCodeInParams, params] def default_network_code(self, currencyCode): defaultNetworkCode = None defaultNetworks = self.safe_value(self.options, 'defaultNetworks', {}) if currencyCode in defaultNetworks: # if currency had set its network in "defaultNetworks", use it defaultNetworkCode = defaultNetworks[currencyCode] else: # otherwise, try to use the global-scope 'defaultNetwork' value(even if that network is not supported by currency, it doesn't make any problem, self will be just used "at first" if currency supports self network at all) defaultNetwork = self.safe_value(self.options, 'defaultNetwork') if defaultNetwork is not None: defaultNetworkCode = defaultNetwork return defaultNetworkCode def select_network_id_from_available_networks(self, currencyCode, networkCode, networkEntriesIndexed): # self method is used against raw & unparse network entries, which are just indexed by network id chosenNetworkId = None availableNetworkIds = list(networkEntriesIndexed.keys()) responseNetworksLength = len(availableNetworkIds) if networkCode is not None: # if networkCode was provided by user, we should check it after response, as the referenced exchange doesn't support network-code during request networkId = self.networkCodeToId(networkCode) if responseNetworksLength == 0: raise NotSupported(self.id + ' - ' + networkCode + ' network did not return any result for ' + currencyCode) else: if networkId in networkEntriesIndexed: chosenNetworkId = networkId else: raise NotSupported(self.id + ' - ' + networkId + ' network was not found for ' + currencyCode + ', use one of ' + ', '.join(availableNetworkIds)) else: if responseNetworksLength == 0: raise NotSupported(self.id + ' - no networks were returned for' + currencyCode) else: # if networkCode was not provided by user, then we try to use the default network(if it was defined in "defaultNetworks"), otherwise, we just return the first network entry defaultNetwordCode = self.defaultNetworkCode(currencyCode) defaultNetwordId = self.networkCodeToId(defaultNetwordCode) chosenNetworkId = defaultNetwordId if (defaultNetwordId in networkEntriesIndexed) else availableNetworkIds[0] return chosenNetworkId def safe_number_2(self, dictionary, key1, key2, d=None): value = self.safe_string_2(dictionary, key1, key2) return self.parse_number(value, d) def parse_order_book(self, orderbook, symbol, timestamp=None, bidsKey='bids', asksKey='asks', priceKey=0, amountKey=1): bids = self.parse_bids_asks(self.safe_value(orderbook, bidsKey, []), priceKey, amountKey) asks = self.parse_bids_asks(self.safe_value(orderbook, asksKey, []), priceKey, amountKey) return { 'symbol': symbol, 'bids': self.sort_by(bids, 0, True), 'asks': self.sort_by(asks, 0), 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'nonce': None, } def parse_ohlcvs(self, ohlcvs, market=None, timeframe='1m', since=None, limit=None): results = [] for i in range(0, len(ohlcvs)): results.append(self.parse_ohlcv(ohlcvs[i], market)) sorted = self.sort_by(results, 0) tail = (since is None) return self.filter_by_since_limit(sorted, since, limit, 0, tail) def parse_leverage_tiers(self, response, symbols=None, marketIdKey=None): # marketIdKey should only be None when response is a dictionary symbols = self.market_symbols(symbols) tiers = {} for i in range(0, len(response)): item = response[i] id = self.safe_string(item, marketIdKey) market = self.safe_market(id) symbol = market['symbol'] contract = self.safe_value(market, 'contract', False) if contract and ((symbols is None) or self.in_array(symbol, symbols)): tiers[symbol] = self.parse_market_leverage_tiers(item, market) return tiers def load_trading_limits(self, symbols=None, reload=False, params={}): if self.has['fetchTradingLimits']: if reload or not ('limitsLoaded' in self.options): response = self.fetch_trading_limits(symbols) for i in range(0, len(symbols)): symbol = symbols[i] self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol]) self.options['limitsLoaded'] = self.milliseconds() return self.markets def parse_positions(self, positions, symbols=None, params={}): symbols = self.market_symbols(symbols) positions = self.to_array(positions) result = [] for i in range(0, len(positions)): position = self.extend(self.parse_position(positions[i], None), params) result.append(position) return self.filter_by_array(result, 'symbol', symbols, False) def parse_accounts(self, accounts, params={}): accounts = self.to_array(accounts) result = [] for i in range(0, len(accounts)): account = self.extend(self.parse_account(accounts[i]), params) result.append(account) return result def parse_trades(self, trades, market=None, since=None, limit=None, params={}): trades = self.to_array(trades) result = [] for i in range(0, len(trades)): trade = self.extend(self.parse_trade(trades[i], market), params) result.append(trade) result = self.sort_by_2(result, 'timestamp', 'id') symbol = market['symbol'] if (market is not None) else None tail = (since is None) return self.filter_by_symbol_since_limit(result, symbol, since, limit, tail) def parse_transactions(self, transactions, currency=None, since=None, limit=None, params={}): transactions = self.to_array(transactions) result = [] for i in range(0, len(transactions)): transaction = self.extend(self.parse_transaction(transactions[i], currency), params) result.append(transaction) result = self.sort_by(result, 'timestamp') code = currency['code'] if (currency is not None) else None tail = (since is None) return self.filter_by_currency_since_limit(result, code, since, limit, tail) def parse_transfers(self, transfers, currency=None, since=None, limit=None, params={}): transfers = self.to_array(transfers) result = [] for i in range(0, len(transfers)): transfer = self.extend(self.parse_transfer(transfers[i], currency), params) result.append(transfer) result = self.sort_by(result, 'timestamp') code = currency['code'] if (currency is not None) else None tail = (since is None) return self.filter_by_currency_since_limit(result, code, since, limit, tail) def parse_ledger(self, data, currency=None, since=None, limit=None, params={}): result = [] arrayData = self.to_array(data) for i in range(0, len(arrayData)): itemOrItems = self.parse_ledger_entry(arrayData[i], currency) if isinstance(itemOrItems, list): for j in range(0, len(itemOrItems)): result.append(self.extend(itemOrItems[j], params)) else: result.append(self.extend(itemOrItems, params)) result = self.sort_by(result, 'timestamp') code = currency['code'] if (currency is not None) else None tail = (since is None) return self.filter_by_currency_since_limit(result, code, since, limit, tail) def nonce(self): return self.seconds() def set_headers(self, headers): return headers def market_id(self, symbol): market = self.market(symbol) if market is not None: return market['id'] return symbol def symbol(self, symbol): market = self.market(symbol) return self.safe_string(market, 'symbol', symbol) def resolve_path(self, path, params): return [ self.implode_params(path, params), self.omit(params, self.extract_params(path)), ] def filter_by_array(self, objects, key, values=None, indexed=True): objects = self.to_array(objects) # return all of them if no values were passed if values is None or not values: return self.index_by(objects, key) if indexed else objects results = [] for i in range(0, len(objects)): if self.in_array(objects[i][key], values): results.append(objects[i]) return self.index_by(results, key) if indexed else results def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None, config={}, context={}): if self.enableRateLimit: cost = self.calculate_rate_limiter_cost(api, method, path, params, config, context) self.throttle(cost) self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return self.fetch(request['url'], request['method'], request['headers'], request['body']) def request(self, path, api='public', method='GET', params={}, headers=None, body=None, config={}, context={}): return self.fetch2(path, api, method, params, headers, body, config, context) def load_accounts(self, reload=False, params={}): if reload: self.accounts = self.fetch_accounts(params) else: if self.accounts: return self.accounts else: self.accounts = self.fetch_accounts(params) self.accountsById = self.index_by(self.accounts, 'id') return self.accounts def fetch_trades(self, symbol, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchTrades() is not supported yet') def fetch_ohlcvc(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: raise NotSupported(self.id + ' fetchOHLCV() is not supported yet') self.load_markets() trades = self.fetchTrades(symbol, since, limit, params) return self.build_ohlcvc(trades, timeframe, since, limit) def parse_trading_view_ohlcv(self, ohlcvs, market=None, timeframe='1m', since=None, limit=None): result = self.convert_trading_view_to_ohlcv(ohlcvs) return self.parse_ohlcvs(result, market, timeframe, since, limit) def edit_limit_buy_order(self, id, symbol, amount, price=None, params={}): return self.edit_limit_order(id, symbol, 'buy', amount, price, params) def edit_limit_sell_order(self, id, symbol, amount, price=None, params={}): return self.edit_limit_order(id, symbol, 'sell', amount, price, params) def edit_limit_order(self, id, symbol, side, amount, price=None, params={}): return self.edit_order(id, symbol, 'limit', side, amount, price, params) def edit_order(self, id, symbol, type, side, amount, price=None, params={}): self.cancelOrder(id, symbol) return self.create_order(symbol, type, side, amount, price, params) def fetch_permissions(self, params={}): raise NotSupported(self.id + ' fetchPermissions() is not supported yet') def fetch_position(self, symbol, params={}): raise NotSupported(self.id + ' fetchPosition() is not supported yet') def fetch_positions(self, symbols=None, params={}): raise NotSupported(self.id + ' fetchPositions() is not supported yet') def fetch_positions_risk(self, symbols=None, params={}): raise NotSupported(self.id + ' fetchPositionsRisk() is not supported yet') def fetch_bids_asks(self, symbols=None, params={}): raise NotSupported(self.id + ' fetchBidsAsks() is not supported yet') def parse_bid_ask(self, bidask, priceKey=0, amountKey=1): price = self.safe_number(bidask, priceKey) amount = self.safe_number(bidask, amountKey) return [price, amount] def safe_currency(self, currencyId, currency=None): if (currencyId is None) and (currency is not None): return currency if (self.currencies_by_id is not None) and (currencyId in self.currencies_by_id) and (self.currencies_by_id[currencyId] is not None): return self.currencies_by_id[currencyId] code = currencyId if currencyId is not None: code = self.common_currency_code(currencyId.upper()) return { 'id': currencyId, 'code': code, } def safe_market(self, marketId=None, market=None, delimiter=None): result = { 'id': marketId, 'symbol': marketId, 'base': None, 'quote': None, 'baseId': None, 'quoteId': None, 'active': None, 'type': None, 'linear': None, 'inverse': None, 'spot': False, 'swap': False, 'future': False, 'option': False, 'margin': False, 'contract': False, 'contractSize': None, 'expiry': None, 'expiryDatetime': None, 'optionType': None, 'strike': None, 'settle': None, 'settleId': None, 'precision': { 'amount': None, 'price': None, }, 'limits': { 'amount': { 'min': None, 'max': None, }, 'price': { 'min': None, 'max': None, }, 'cost': { 'min': None, 'max': None, }, }, 'info': None, } if marketId is not None: if (self.markets_by_id is not None) and (marketId in self.markets_by_id): market = self.markets_by_id[marketId] elif delimiter is not None: parts = marketId.split(delimiter) partsLength = len(parts) if partsLength == 2: result['baseId'] = self.safe_string(parts, 0) result['quoteId'] = self.safe_string(parts, 1) result['base'] = self.safe_currency_code(result['baseId']) result['quote'] = self.safe_currency_code(result['quoteId']) result['symbol'] = result['base'] + '/' + result['quote'] return result else: return result if market is not None: return market return result def check_required_credentials(self, error=True): keys = list(self.requiredCredentials.keys()) for i in range(0, len(keys)): key = keys[i] if self.requiredCredentials[key] and not getattr(self, key): if error: raise AuthenticationError(self.id + ' requires "' + key + '" credential') else: return error return True def oath(self): if self.twofa is not None: return self.totp(self.twofa) else: raise ExchangeError(self.id + ' exchange.twofa has not been set for 2FA Two-Factor Authentication') def fetch_balance(self, params={}): raise NotSupported(self.id + ' fetchBalance() is not supported yet') def fetch_partial_balance(self, part, params={}): balance = self.fetch_balance(params) return balance[part] def fetch_free_balance(self, params={}): return self.fetch_partial_balance('free', params) def fetch_used_balance(self, params={}): return self.fetch_partial_balance('used', params) def fetch_total_balance(self, params={}): return self.fetch_partial_balance('total', params) def fetch_status(self, params={}): if self.has['fetchTime']: time = self.fetchTime(params) self.status = self.extend(self.status, { 'updated': time, }) return self.status def fetch_funding_fee(self, code, params={}): warnOnFetchFundingFee = self.safe_value(self.options, 'warnOnFetchFundingFee', True) if warnOnFetchFundingFee: raise NotSupported(self.id + ' fetchFundingFee() method is deprecated, it will be removed in July 2022, please, use fetchTransactionFee() or set exchange.options["warnOnFetchFundingFee"] = False to suppress self warning') return self.fetch_transaction_fee(code, params) def fetch_funding_fees(self, codes=None, params={}): warnOnFetchFundingFees = self.safe_value(self.options, 'warnOnFetchFundingFees', True) if warnOnFetchFundingFees: raise NotSupported(self.id + ' fetchFundingFees() method is deprecated, it will be removed in July 2022. Please, use fetchTransactionFees() or set exchange.options["warnOnFetchFundingFees"] = False to suppress self warning') return self.fetch_transaction_fees(codes, params) def fetch_transaction_fee(self, code, params={}): if not self.has['fetchTransactionFees']: raise NotSupported(self.id + ' fetchTransactionFee() is not supported yet') return self.fetch_transaction_fees([code], params) def fetch_transaction_fees(self, codes=None, params={}): raise NotSupported(self.id + ' fetchTransactionFees() is not supported yet') def get_supported_mapping(self, key, mapping={}): if key in mapping: return mapping[key] else: raise NotSupported(self.id + ' ' + key + ' does not have a value in mapping') def fetch_borrow_rate(self, code, params={}): self.load_markets() if not self.has['fetchBorrowRates']: raise NotSupported(self.id + ' fetchBorrowRate() is not supported yet') borrowRates = self.fetch_borrow_rates(params) rate = self.safe_value(borrowRates, code) if rate is None: raise ExchangeError(self.id + ' fetchBorrowRate() could not find the borrow rate for currency code ' + code) return rate def handle_option_and_params(self, params, methodName, optionName, defaultValue=None): # This method can be used to obtain method specific properties, i.e: self.handleOptionAndParams(params, 'fetchPosition', 'marginMode', 'isolated') defaultOptionName = 'default' + self.capitalize(optionName) # we also need to check the 'defaultXyzWhatever' # check if params contain the key value = self.safe_string_2(params, optionName, defaultOptionName) if value is not None: params = self.omit(params, [optionName, defaultOptionName]) if value is None: # check if exchange-wide method options contain the key exchangeWideMethodOptions = self.safe_value(self.options, methodName) if exchangeWideMethodOptions is not None: value = self.safe_string_2(exchangeWideMethodOptions, optionName, defaultOptionName) if value is None: # check if exchange-wide options contain the key value = self.safe_string_2(self.options, optionName, defaultOptionName) value = value if (value is not None) else defaultValue return [value, params] def handle_market_type_and_params(self, methodName, market=None, params={}): defaultType = self.safe_string_2(self.options, 'defaultType', 'type', 'spot') methodOptions = self.safe_value(self.options, methodName) methodType = defaultType if methodOptions is not None: if isinstance(methodOptions, str): methodType = methodOptions else: methodType = self.safe_string_2(methodOptions, 'defaultType', 'type', methodType) marketType = methodType if (market is None) else market['type'] type = self.safe_string_2(params, 'defaultType', 'type', marketType) params = self.omit(params, ['defaultType', 'type']) return [type, params] def handle_sub_type_and_params(self, methodName, market=None, params={}, defaultValue='linear'): subType = None # if set in params, it takes precedence subTypeInParams = self.safe_string_2(params, 'subType', 'defaultSubType') # avoid omitting if it's not present if subTypeInParams is not None: subType = subTypeInParams params = self.omit(params, ['subType', 'defaultSubType']) else: # at first, check from market object if market is not None: if market['linear']: subType = 'linear' elif market['inverse']: subType = 'inverse' # if it was not defined in market object if subType is None: values = self.handleOptionAndParams(None, methodName, 'subType', defaultValue) # no need to re-test params here subType = values[0] return [subType, params] def handle_margin_mode_and_params(self, methodName, params={}, defaultValue=None): """ * @ignore :param dict params: extra parameters specific to the exchange api endpoint :returns [str|None, dict]: the marginMode in lowercase as specified by params["marginMode"], params["defaultMarginMode"] self.options["marginMode"] or self.options["defaultMarginMode"] """ return self.handleOptionAndParams(params, methodName, 'marginMode', defaultValue) def throw_exactly_matched_exception(self, exact, string, message): if string in exact: raise exact[string](message) def throw_broadly_matched_exception(self, broad, string, message): broadKey = self.find_broadly_matched_key(broad, string) if broadKey is not None: raise broad[broadKey](message) def find_broadly_matched_key(self, broad, string): # a helper for matching error strings exactly vs broadly keys = list(broad.keys()) for i in range(0, len(keys)): key = keys[i] if string is not None: # #issues/12698 if string.find(key) >= 0: return key return None def handle_errors(self, statusCode, statusText, url, method, responseHeaders, responseBody, response, requestHeaders, requestBody): # it is a stub method that must be overrided in the derived exchange classes # raise NotSupported(self.id + ' handleErrors() not implemented yet') pass def calculate_rate_limiter_cost(self, api, method, path, params, config={}, context={}): return self.safe_value(config, 'cost', 1) def fetch_ticker(self, symbol, params={}): if self.has['fetchTickers']: tickers = self.fetch_tickers([symbol], params) ticker = self.safe_value(tickers, symbol) if ticker is None: raise NullResponse(self.id + ' fetchTickers() could not find a ticker for ' + symbol) else: return ticker else: raise NotSupported(self.id + ' fetchTicker() is not supported yet') def fetch_tickers(self, symbols=None, params={}): raise NotSupported(self.id + ' fetchTickers() is not supported yet') def fetch_order(self, id, symbol=None, params={}): raise NotSupported(self.id + ' fetchOrder() is not supported yet') def fetch_order_status(self, id, symbol=None, params={}): order = self.fetch_order(id, symbol, params) return order['status'] def fetch_unified_order(self, order, params={}): return self.fetch_order(self.safe_value(order, 'id'), self.safe_value(order, 'symbol'), params) def create_order(self, symbol, type, side, amount, price=None, params={}): raise NotSupported(self.id + ' createOrder() is not supported yet') def cancel_order(self, id, symbol=None, params={}): raise NotSupported(self.id + ' cancelOrder() is not supported yet') def cancel_unified_order(self, order, params={}): return self.cancelOrder(self.safe_value(order, 'id'), self.safe_value(order, 'symbol'), params) def fetch_orders(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchOrders() is not supported yet') def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchOpenOrders() is not supported yet') def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchClosedOrders() is not supported yet') def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchMyTrades() is not supported yet') def fetch_transactions(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchTransactions() is not supported yet') def fetch_deposits(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchDeposits() is not supported yet') def fetch_withdrawals(self, symbol=None, since=None, limit=None, params={}): raise NotSupported(self.id + ' fetchWithdrawals() is not supported yet') def fetch_deposit_address(self, code, params={}): if self.has['fetchDepositAddresses']: depositAddresses = self.fetchDepositAddresses([code], params) depositAddress = self.safe_value(depositAddresses, code) if depositAddress is None: raise InvalidAddress(self.id + ' fetchDepositAddress() could not find a deposit address for ' + code + ', make sure you have created a corresponding deposit address in your wallet on the exchange website') else: return depositAddress else: raise NotSupported(self.id + ' fetchDepositAddress() is not supported yet') def account(self): return { 'free': None, 'used': None, 'total': None, } def common_currency_code(self, currency): if not self.substituteCommonCurrencyCodes: return currency return self.safe_string(self.commonCurrencies, currency, currency) def currency(self, code): if self.currencies is None: raise ExchangeError(self.id + ' currencies not loaded') if isinstance(code, str): if code in self.currencies: return self.currencies[code] elif code in self.currencies_by_id: return self.currencies_by_id[code] raise ExchangeError(self.id + ' does not have currency code ' + code) def market(self, symbol): if self.markets is None: raise ExchangeError(self.id + ' markets not loaded') if self.markets_by_id is None: raise ExchangeError(self.id + ' markets not loaded') if isinstance(symbol, str): if symbol in self.markets: return self.markets[symbol] elif symbol in self.markets_by_id: return self.markets_by_id[symbol] raise BadSymbol(self.id + ' does not have market symbol ' + symbol) def handle_withdraw_tag_and_params(self, tag, params): if isinstance(tag, dict): params = self.extend(tag, params) tag = None if tag is None: tag = self.safe_string(params, 'tag') if tag is not None: params = self.omit(params, 'tag') return [tag, params] def create_limit_order(self, symbol, side, amount, price, params={}): return self.create_order(symbol, 'limit', side, amount, price, params) def create_market_order(self, symbol, side, amount, price=None, params={}): return self.create_order(symbol, 'market', side, amount, price, params) def create_limit_buy_order(self, symbol, amount, price, params={}): return self.create_order(symbol, 'limit', 'buy', amount, price, params) def create_limit_sell_order(self, symbol, amount, price, params={}): return self.create_order(symbol, 'limit', 'sell', amount, price, params) def create_market_buy_order(self, symbol, amount, params={}): return self.create_order(symbol, 'market', 'buy', amount, None, params) def create_market_sell_order(self, symbol, amount, params={}): return self.create_order(symbol, 'market', 'sell', amount, None, params) def cost_to_precision(self, symbol, cost): market = self.market(symbol) return self.decimal_to_precision(cost, TRUNCATE, market['precision']['price'], self.precisionMode, self.paddingMode) def price_to_precision(self, symbol, price): market = self.market(symbol) return self.decimal_to_precision(price, ROUND, market['precision']['price'], self.precisionMode, self.paddingMode) def amount_to_precision(self, symbol, amount): market = self.market(symbol) return self.decimal_to_precision(amount, TRUNCATE, market['precision']['amount'], self.precisionMode, self.paddingMode) def fee_to_precision(self, symbol, fee): market = self.market(symbol) return self.decimal_to_precision(fee, ROUND, market['precision']['price'], self.precisionMode, self.paddingMode) def currency_to_precision(self, code, fee, networkCode=None): currency = self.currencies[code] precision = self.safe_value(currency, 'precision') if networkCode is not None: networks = self.safe_value(currency, 'networks', {}) networkItem = self.safe_value(networks, networkCode, {}) precision = self.safe_value(networkItem, 'precision', precision) if precision is None: return fee else: return self.decimal_to_precision(fee, ROUND, precision, self.precisionMode, self.paddingMode) def safe_number(self, object, key, d=None): value = self.safe_string(object, key) return self.parse_number(value, d) def safe_number_n(self, object, arr, d=None): value = self.safe_string_n(object, arr) return self.parse_number(value, d) def parse_precision(self, precision): if precision is None: return None return '1e' + Precise.string_neg(precision) def load_time_difference(self, params={}): serverTime = self.fetchTime(params) after = self.milliseconds() self.options['timeDifference'] = after - serverTime return self.options['timeDifference'] def implode_hostname(self, url): return self.implode_params(url, {'hostname': self.hostname}) def fetch_market_leverage_tiers(self, symbol, params={}): if self.has['fetchLeverageTiers']: market = self.market(symbol) if not market['contract']: raise BadSymbol(self.id + ' fetchMarketLeverageTiers() supports contract markets only') tiers = self.fetch_leverage_tiers([symbol]) return self.safe_value(tiers, symbol) else: raise NotSupported(self.id + ' fetchMarketLeverageTiers() is not supported yet') def create_post_only_order(self, symbol, type, side, amount, price, params={}): if not self.has['createPostOnlyOrder']: raise NotSupported(self.id + 'createPostOnlyOrder() is not supported yet') query = self.extend(params, {'postOnly': True}) return self.create_order(symbol, type, side, amount, price, query) def create_reduce_only_order(self, symbol, type, side, amount, price, params={}): if not self.has['createReduceOnlyOrder']: raise NotSupported(self.id + 'createReduceOnlyOrder() is not supported yet') query = self.extend(params, {'reduceOnly': True}) return self.create_order(symbol, type, side, amount, price, query) def create_stop_order(self, symbol, type, side, amount, price=None, stopPrice=None, params={}): if not self.has['createStopOrder']: raise NotSupported(self.id + ' createStopOrder() is not supported yet') if stopPrice is None: raise ArgumentsRequired(self.id + ' create_stop_order() requires a stopPrice argument') query = self.extend(params, {'stopPrice': stopPrice}) return self.create_order(symbol, type, side, amount, price, query) def create_stop_limit_order(self, symbol, side, amount, price, stopPrice, params={}): if not self.has['createStopLimitOrder']: raise NotSupported(self.id + ' createStopLimitOrder() is not supported yet') query = self.extend(params, {'stopPrice': stopPrice}) return self.create_order(symbol, 'limit', side, amount, price, query) def create_stop_market_order(self, symbol, side, amount, stopPrice, params={}): if not self.has['createStopMarketOrder']: raise NotSupported(self.id + ' createStopMarketOrder() is not supported yet') query = self.extend(params, {'stopPrice': stopPrice}) return self.create_order(symbol, 'market', side, amount, None, query) def safe_currency_code(self, currencyId, currency=None): currency = self.safe_currency(currencyId, currency) return currency['code'] def filter_by_symbol_since_limit(self, array, symbol=None, since=None, limit=None, tail=False): return self.filter_by_value_since_limit(array, 'symbol', symbol, since, limit, 'timestamp', tail) def filter_by_currency_since_limit(self, array, code=None, since=None, limit=None, tail=False): return self.filter_by_value_since_limit(array, 'currency', code, since, limit, 'timestamp', tail) def parse_tickers(self, tickers, symbols=None, params={}): # # the value of tickers is either a dict or a list # # dict # # { # 'marketId1': {...}, # 'marketId2': {...}, # 'marketId3': {...}, # ... # } # # list # # [ # {'market': 'marketId1', ...}, # {'market': 'marketId2', ...}, # {'market': 'marketId3', ...}, # ... # ] # results = [] if isinstance(tickers, list): for i in range(0, len(tickers)): ticker = self.extend(self.parse_ticker(tickers[i]), params) results.append(ticker) else: marketIds = list(tickers.keys()) for i in range(0, len(marketIds)): marketId = marketIds[i] market = self.safe_market(marketId) ticker = self.extend(self.parse_ticker(tickers[marketId], market), params) results.append(ticker) symbols = self.market_symbols(symbols) return self.filter_by_array(results, 'symbol', symbols) def parse_deposit_addresses(self, addresses, codes=None, indexed=True, params={}): result = [] for i in range(0, len(addresses)): address = self.extend(self.parse_deposit_address(addresses[i]), params) result.append(address) if codes is not None: result = self.filter_by_array(result, 'currency', codes, False) result = self.index_by(result, 'currency') if indexed else result return result def parse_borrow_interests(self, response, market=None): interests = [] for i in range(0, len(response)): row = response[i] interests.append(self.parse_borrow_interest(row, market)) return interests def parse_funding_rate_histories(self, response, market=None, since=None, limit=None): rates = [] for i in range(0, len(response)): entry = response[i] rates.append(self.parse_funding_rate_history(entry, market)) sorted = self.sort_by(rates, 'timestamp') symbol = None if (market is None) else market['symbol'] return self.filter_by_symbol_since_limit(sorted, symbol, since, limit) def safe_symbol(self, marketId, market=None, delimiter=None): market = self.safe_market(marketId, market, delimiter) return market['symbol'] def parse_funding_rate(self, contract, market=None): raise NotSupported(self.id + ' parseFundingRate() is not supported yet') def parse_funding_rates(self, response, market=None): result = {} for i in range(0, len(response)): parsed = self.parse_funding_rate(response[i], market) result[parsed['symbol']] = parsed return result def is_trigger_order(self, params): isTrigger = self.safe_value_2(params, 'trigger', 'stop') if isTrigger: params = self.omit(params, ['trigger', 'stop']) return [isTrigger, params] def is_post_only(self, isMarketOrder, exchangeSpecificParam, params={}): """ * @ignore :param str type: Order type :param boolean exchangeSpecificParam: exchange specific postOnly :param dict params: exchange specific params :returns boolean: True if a post only order, False otherwise """ timeInForce = self.safe_string_upper(params, 'timeInForce') postOnly = self.safe_value_2(params, 'postOnly', 'post_only', False) # we assume timeInForce is uppercase from safeStringUpper(params, 'timeInForce') ioc = timeInForce == 'IOC' fok = timeInForce == 'FOK' timeInForcePostOnly = timeInForce == 'PO' postOnly = postOnly or timeInForcePostOnly or exchangeSpecificParam if postOnly: if ioc or fok: raise InvalidOrder(self.id + ' postOnly orders cannot have timeInForce equal to ' + timeInForce) elif isMarketOrder: raise InvalidOrder(self.id + ' market orders cannot be postOnly') else: return True else: return False def fetch_trading_fees(self, params={}): raise NotSupported(self.id + ' fetchTradingFees() is not supported yet') def fetch_trading_fee(self, symbol, params={}): if not self.has['fetchTradingFees']: raise NotSupported(self.id + ' fetchTradingFee() is not supported yet') return self.fetch_trading_fees(params) def parse_open_interest(self, interest, market=None): raise NotSupported(self.id + ' parseOpenInterest() is not supported yet') def parse_open_interests(self, response, market=None, since=None, limit=None): interests = [] for i in range(0, len(response)): entry = response[i] interest = self.parse_open_interest(entry, market) interests.append(interest) sorted = self.sort_by(interests, 'timestamp') symbol = self.safe_string(market, 'symbol') return self.filter_by_symbol_since_limit(sorted, symbol, since, limit) def fetch_funding_rate(self, symbol, params={}): if self.has['fetchFundingRates']: self.load_markets() market = self.market(symbol) if not market['contract']: raise BadSymbol(self.id + ' fetchFundingRate() supports contract markets only') rates = self.fetchFundingRates([symbol], params) rate = self.safe_value(rates, symbol) if rate is None: raise NullResponse(self.id + ' fetchFundingRate() returned no data for ' + symbol) else: return rate else: raise NotSupported(self.id + ' fetchFundingRate() is not supported yet') def fetch_mark_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): """ fetches historical mark price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int|None since: timestamp in ms of the earliest candle to fetch :param int|None limit: the maximum amount of candles to fetch :param dict params: extra parameters specific to the exchange api endpoint :returns [[int|float]]: A list of candles ordered as timestamp, open, high, low, close, None """ if self.has['fetchMarkOHLCV']: request = { 'price': 'mark', } return self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params)) else: raise NotSupported(self.id + ' fetchMarkOHLCV() is not supported yet') def fetch_index_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): """ fetches historical index price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int|None since: timestamp in ms of the earliest candle to fetch :param int|None limit: the maximum amount of candles to fetch :param dict params: extra parameters specific to the exchange api endpoint :returns [[int|float]]: A list of candles ordered as timestamp, open, high, low, close, None """ if self.has['fetchIndexOHLCV']: request = { 'price': 'index', } return self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params)) else: raise NotSupported(self.id + ' fetchIndexOHLCV() is not supported yet') def fetch_premium_index_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): """ fetches historical premium index price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int|None since: timestamp in ms of the earliest candle to fetch :param int|None limit: the maximum amount of candles to fetch :param dict params: extra parameters specific to the exchange api endpoint :returns [[int|float]]: A list of candles ordered as timestamp, open, high, low, close, None """ if self.has['fetchPremiumIndexOHLCV']: request = { 'price': 'premiumIndex', } return self.fetch_ohlcv(symbol, timeframe, since, limit, self.extend(request, params)) else: raise NotSupported(self.id + ' fetchPremiumIndexOHLCV() is not supported yet') def handle_time_in_force(self, params={}): """ * @ignore * * Must add timeInForce to self.options to use self method :return string returns: the exchange specific value for timeInForce """ timeInForce = self.safe_string_upper(params, 'timeInForce') # supported values GTC, IOC, PO if timeInForce is not None: exchangeValue = self.safe_string(self.options['timeInForce'], timeInForce) if exchangeValue is None: raise ExchangeError(self.id + ' does not support timeInForce "' + timeInForce + '"') return exchangeValue return None def convert_type_to_account(self, account): """ * @ignore * * Must add accountsByType to self.options to use self method :param str account: key for account name in self.options['accountsByType'] :returns: the exchange specific account name or the isolated margin id for transfers """ accountsByType = self.safe_value(self.options, 'accountsByType', {}) lowercaseAccount = account.lower() if lowercaseAccount in accountsByType: return accountsByType[lowercaseAccount] elif (account in self.markets) or (account in self.markets_by_id): market = self.market(account) return market['id'] else: return account def check_required_argument(self, methodName, argument, argumentName, options=[]): """ * @ignore :param str argument: the argument to check :param str argumentName: the name of the argument to check :param str methodName: the name of the method that the argument is being checked for :param [str] options: a list of options that the argument can be :returns None: """ if (argument is None) or ((len(options) > 0) and (not(self.in_array(argument, options)))): messageOptions = ', '.join(options) message = self.id + ' ' + methodName + '() requires a ' + argumentName + ' argument' if messageOptions != '': message += ', one of ' + '(' + messageOptions + ')' raise ArgumentsRequired(message) def check_required_margin_argument(self, methodName, symbol, marginMode): """ * @ignore :param str symbol: unified symbol of the market :param str methodName: name of the method that requires a symbol :param str marginMode: is either 'isolated' or 'cross' """ if (marginMode == 'isolated') and (symbol is None): raise ArgumentsRequired(self.id + ' ' + methodName + '() requires a symbol argument for isolated margin') elif (marginMode == 'cross') and (symbol is not None): raise ArgumentsRequired(self.id + ' ' + methodName + '() cannot have a symbol argument for cross margin') def check_required_symbol(self, methodName, symbol): """ * @ignore :param str symbol: unified symbol of the market :param str methodName: name of the method that requires a symbol """ self.checkRequiredArgument(methodName, symbol, 'symbol')
mit
1b4693ad56613f6f4afe9b65002a7a26
41.600459
249
0.571075
4.069312
false
false
false
false
opps/opps
opps/articles/models.py
3
4855
# -*- coding: utf-8 -*- import warnings from urlparse import urlparse from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from django.core.cache import cache from .signals import redirect_generate from opps.containers.models import Container, ContainerImage from opps.core.cache import _cache_key from opps.core.managers import PublishableManager class Article(Container): headline = models.TextField( _(u"Headline"), blank=True, null=True) short_title = models.CharField( _(u"Short title"), max_length=140, null=True, blank=True) class Meta: abstract = True class Post(Article): content = models.TextField(_(u"Content")) albums = models.ManyToManyField( 'articles.Album', null=True, blank=True, related_name='post_albums', verbose_name=_(u"Albums") ) objects = PublishableManager() class Meta: verbose_name = _('Post') verbose_name_plural = _('Posts') ordering = ['-date_available'] def all_images(self, check_published=True): cachekey = _cache_key( '{0}main-all_images'.format(self.__class__.__name__), self.__class__, self.site_domain, u"{0}-{1}".format(self.channel_long_slug, self.slug)) getcache = cache.get(cachekey) if getcache and check_published: return getcache imgs = super(Post, self).all_images() albums = self.albums.filter(date_available__lte=timezone.now()) if check_published: albums = albums.filter(published=True) for album in albums: images = album.images.filter( date_available__lte=timezone.now(), ).exclude( pk__in=[i.pk for i in imgs] ).order_by('containerimage__order') if check_published: images = images.filter(published=True) captions = dict([ (ci.image_id, ci.caption) for ci in ContainerImage.objects.filter( container_id=album.pk ) ]) for image in images: caption = captions.get(image.pk) if caption: image.description = caption imgs.append(image) cache.set(cachekey, imgs) return imgs def ordered_related(self, field='order'): """ used in template """ return self.related_posts.filter( published=True, date_available__lte=timezone.now() ).order_by( 'postrelated_related__order' ).distinct() @property def related_posts(self): warn = "related_posts will be removed, must use related_containers." warnings.warn(warn, DeprecationWarning) return self.related_containers class PostRelated(models.Model): post = models.ForeignKey( 'articles.Post', verbose_name=_(u'Post'), null=True, blank=True, related_name='postrelated_post', on_delete=models.SET_NULL ) related = models.ForeignKey( 'containers.Container', verbose_name=_(u'Related Post'), null=True, blank=True, related_name='postrelated_related', on_delete=models.SET_NULL ) order = models.PositiveIntegerField(_(u'Order'), default=0) class Meta: verbose_name = _('Related content') verbose_name_plural = _('Related contents') ordering = ('order',) def __unicode__(self): return u"{0}->{1}".format(self.related.slug, self.post.slug) class Album(Article): class Meta: verbose_name = _('Album') verbose_name_plural = _('Albums') ordering = ['-date_available'] class Link(Article): url = models.URLField(_(u"URL"), null=True, blank=True) container = models.ForeignKey( 'containers.Container', null=True, blank=True, related_name='link_containers' ) class Meta: verbose_name = _('Link') verbose_name_plural = _('Links') ordering = ['-date_available'] def is_local(self): try: url = urlparse(self.url) return url.netloc.replace('www', '') == self.site_domain except: return False def is_subdomain(self): return self.site_domain in self.url def clean(self): if not self.url and not self.container: raise ValidationError(_('URL field is required.')) self.url = self.url if self.container: self.url = self.container.get_absolute_url() models.signals.post_save.connect(redirect_generate, sender=Link)
mit
e402c2c692e62d720b29f272cca89594
27.063584
76
0.584758
4.146029
false
false
false
false
sqlalchemy/alembic
alembic/runtime/environment.py
2
39148
from __future__ import annotations from typing import Any from typing import Callable from typing import ContextManager from typing import Dict from typing import List from typing import Optional from typing import overload from typing import TextIO from typing import Tuple from typing import TYPE_CHECKING from typing import Union from .migration import _ProxyTransaction from .migration import MigrationContext from .. import util from ..operations import Operations if TYPE_CHECKING: from typing import Literal from sqlalchemy.engine.base import Connection from sqlalchemy.sql.elements import ClauseElement from sqlalchemy.sql.schema import MetaData from ..config import Config from ..ddl import DefaultImpl from ..operations.ops import MigrateOperation from ..script.base import ScriptDirectory _RevNumber = Optional[Union[str, Tuple[str, ...]]] ProcessRevisionDirectiveFn = Callable[ [MigrationContext, Tuple[str, str], List["MigrateOperation"]], None ] class EnvironmentContext(util.ModuleClsProxy): """A configurational facade made available in an ``env.py`` script. The :class:`.EnvironmentContext` acts as a *facade* to the more nuts-and-bolts objects of :class:`.MigrationContext` as well as certain aspects of :class:`.Config`, within the context of the ``env.py`` script that is invoked by most Alembic commands. :class:`.EnvironmentContext` is normally instantiated when a command in :mod:`alembic.command` is run. It then makes itself available in the ``alembic.context`` module for the scope of the command. From within an ``env.py`` script, the current :class:`.EnvironmentContext` is available by importing this module. :class:`.EnvironmentContext` also supports programmatic usage. At this level, it acts as a Python context manager, that is, is intended to be used using the ``with:`` statement. A typical use of :class:`.EnvironmentContext`:: from alembic.config import Config from alembic.script import ScriptDirectory config = Config() config.set_main_option("script_location", "myapp:migrations") script = ScriptDirectory.from_config(config) def my_function(rev, context): '''do something with revision "rev", which will be the current database revision, and "context", which is the MigrationContext that the env.py will create''' with EnvironmentContext( config, script, fn = my_function, as_sql = False, starting_rev = 'base', destination_rev = 'head', tag = "sometag" ): script.run_env() The above script will invoke the ``env.py`` script within the migration environment. If and when ``env.py`` calls :meth:`.MigrationContext.run_migrations`, the ``my_function()`` function above will be called by the :class:`.MigrationContext`, given the context itself as well as the current revision in the database. .. note:: For most API usages other than full blown invocation of migration scripts, the :class:`.MigrationContext` and :class:`.ScriptDirectory` objects can be created and used directly. The :class:`.EnvironmentContext` object is *only* needed when you need to actually invoke the ``env.py`` module present in the migration environment. """ _migration_context: Optional["MigrationContext"] = None config: "Config" = None # type:ignore[assignment] """An instance of :class:`.Config` representing the configuration file contents as well as other variables set programmatically within it.""" script: "ScriptDirectory" = None # type:ignore[assignment] """An instance of :class:`.ScriptDirectory` which provides programmatic access to version files within the ``versions/`` directory. """ def __init__( self, config: Config, script: ScriptDirectory, **kw: Any ) -> None: r"""Construct a new :class:`.EnvironmentContext`. :param config: a :class:`.Config` instance. :param script: a :class:`.ScriptDirectory` instance. :param \**kw: keyword options that will be ultimately passed along to the :class:`.MigrationContext` when :meth:`.EnvironmentContext.configure` is called. """ self.config = config self.script = script self.context_opts = kw def __enter__(self) -> EnvironmentContext: """Establish a context which provides a :class:`.EnvironmentContext` object to env.py scripts. The :class:`.EnvironmentContext` will be made available as ``from alembic import context``. """ self._install_proxy() return self def __exit__(self, *arg: Any, **kw: Any) -> None: self._remove_proxy() def is_offline_mode(self) -> bool: """Return True if the current migrations environment is running in "offline mode". This is ``True`` or ``False`` depending on the ``--sql`` flag passed. This function does not require that the :class:`.MigrationContext` has been configured. """ return self.context_opts.get("as_sql", False) def is_transactional_ddl(self): """Return True if the context is configured to expect a transactional DDL capable backend. This defaults to the type of database in use, and can be overridden by the ``transactional_ddl`` argument to :meth:`.configure` This function requires that a :class:`.MigrationContext` has first been made available via :meth:`.configure`. """ return self.get_context().impl.transactional_ddl def requires_connection(self) -> bool: return not self.is_offline_mode() def get_head_revision(self) -> _RevNumber: """Return the hex identifier of the 'head' script revision. If the script directory has multiple heads, this method raises a :class:`.CommandError`; :meth:`.EnvironmentContext.get_head_revisions` should be preferred. This function does not require that the :class:`.MigrationContext` has been configured. .. seealso:: :meth:`.EnvironmentContext.get_head_revisions` """ return self.script.as_revision_number("head") def get_head_revisions(self) -> _RevNumber: """Return the hex identifier of the 'heads' script revision(s). This returns a tuple containing the version number of all heads in the script directory. This function does not require that the :class:`.MigrationContext` has been configured. """ return self.script.as_revision_number("heads") def get_starting_revision_argument(self) -> _RevNumber: """Return the 'starting revision' argument, if the revision was passed using ``start:end``. This is only meaningful in "offline" mode. Returns ``None`` if no value is available or was configured. This function does not require that the :class:`.MigrationContext` has been configured. """ if self._migration_context is not None: return self.script.as_revision_number( self.get_context()._start_from_rev ) elif "starting_rev" in self.context_opts: return self.script.as_revision_number( self.context_opts["starting_rev"] ) else: # this should raise only in the case that a command # is being run where the "starting rev" is never applicable; # this is to catch scripts which rely upon this in # non-sql mode or similar raise util.CommandError( "No starting revision argument is available." ) def get_revision_argument(self) -> _RevNumber: """Get the 'destination' revision argument. This is typically the argument passed to the ``upgrade`` or ``downgrade`` command. If it was specified as ``head``, the actual version number is returned; if specified as ``base``, ``None`` is returned. This function does not require that the :class:`.MigrationContext` has been configured. """ return self.script.as_revision_number( self.context_opts["destination_rev"] ) def get_tag_argument(self) -> Optional[str]: """Return the value passed for the ``--tag`` argument, if any. The ``--tag`` argument is not used directly by Alembic, but is available for custom ``env.py`` configurations that wish to use it; particularly for offline generation scripts that wish to generate tagged filenames. This function does not require that the :class:`.MigrationContext` has been configured. .. seealso:: :meth:`.EnvironmentContext.get_x_argument` - a newer and more open ended system of extending ``env.py`` scripts via the command line. """ return self.context_opts.get("tag", None) @overload def get_x_argument( # type:ignore[misc] self, as_dictionary: Literal[False] = ... ) -> List[str]: ... @overload def get_x_argument( # type:ignore[misc] self, as_dictionary: Literal[True] = ... ) -> Dict[str, str]: ... def get_x_argument( self, as_dictionary: bool = False ) -> Union[List[str], Dict[str, str]]: """Return the value(s) passed for the ``-x`` argument, if any. The ``-x`` argument is an open ended flag that allows any user-defined value or values to be passed on the command line, then available here for consumption by a custom ``env.py`` script. The return value is a list, returned directly from the ``argparse`` structure. If ``as_dictionary=True`` is passed, the ``x`` arguments are parsed using ``key=value`` format into a dictionary that is then returned. For example, to support passing a database URL on the command line, the standard ``env.py`` script can be modified like this:: cmd_line_url = context.get_x_argument( as_dictionary=True).get('dbname') if cmd_line_url: engine = create_engine(cmd_line_url) else: engine = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', poolclass=pool.NullPool) This then takes effect by running the ``alembic`` script as:: alembic -x dbname=postgresql://user:pass@host/dbname upgrade head This function does not require that the :class:`.MigrationContext` has been configured. .. seealso:: :meth:`.EnvironmentContext.get_tag_argument` :attr:`.Config.cmd_opts` """ if self.config.cmd_opts is not None: value = self.config.cmd_opts.x or [] else: value = [] if as_dictionary: value = dict(arg.split("=", 1) for arg in value) return value def configure( self, connection: Optional[Connection] = None, url: Optional[str] = None, dialect_name: Optional[str] = None, dialect_opts: Optional[Dict[str, Any]] = None, transactional_ddl: Optional[bool] = None, transaction_per_migration: bool = False, output_buffer: Optional[TextIO] = None, starting_rev: Optional[str] = None, tag: Optional[str] = None, template_args: Optional[Dict[str, Any]] = None, render_as_batch: bool = False, target_metadata: Optional[MetaData] = None, include_name: Optional[Callable[..., bool]] = None, include_object: Optional[Callable[..., bool]] = None, include_schemas: bool = False, process_revision_directives: Optional[ ProcessRevisionDirectiveFn ] = None, compare_type: bool = False, compare_server_default: bool = False, render_item: Optional[Callable[..., bool]] = None, literal_binds: bool = False, upgrade_token: str = "upgrades", downgrade_token: str = "downgrades", alembic_module_prefix: str = "op.", sqlalchemy_module_prefix: str = "sa.", user_module_prefix: Optional[str] = None, on_version_apply: Optional[Callable[..., None]] = None, **kw: Any, ) -> None: """Configure a :class:`.MigrationContext` within this :class:`.EnvironmentContext` which will provide database connectivity and other configuration to a series of migration scripts. Many methods on :class:`.EnvironmentContext` require that this method has been called in order to function, as they ultimately need to have database access or at least access to the dialect in use. Those which do are documented as such. The important thing needed by :meth:`.configure` is a means to determine what kind of database dialect is in use. An actual connection to that database is needed only if the :class:`.MigrationContext` is to be used in "online" mode. If the :meth:`.is_offline_mode` function returns ``True``, then no connection is needed here. Otherwise, the ``connection`` parameter should be present as an instance of :class:`sqlalchemy.engine.Connection`. This function is typically called from the ``env.py`` script within a migration environment. It can be called multiple times for an invocation. The most recent :class:`~sqlalchemy.engine.Connection` for which it was called is the one that will be operated upon by the next call to :meth:`.run_migrations`. General parameters: :param connection: a :class:`~sqlalchemy.engine.Connection` to use for SQL execution in "online" mode. When present, is also used to determine the type of dialect in use. :param url: a string database url, or a :class:`sqlalchemy.engine.url.URL` object. The type of dialect to be used will be derived from this if ``connection`` is not passed. :param dialect_name: string name of a dialect, such as "postgresql", "mssql", etc. The type of dialect to be used will be derived from this if ``connection`` and ``url`` are not passed. :param dialect_opts: dictionary of options to be passed to dialect constructor. .. versionadded:: 1.0.12 :param transactional_ddl: Force the usage of "transactional" DDL on or off; this otherwise defaults to whether or not the dialect in use supports it. :param transaction_per_migration: if True, nest each migration script in a transaction rather than the full series of migrations to run. :param output_buffer: a file-like object that will be used for textual output when the ``--sql`` option is used to generate SQL scripts. Defaults to ``sys.stdout`` if not passed here and also not present on the :class:`.Config` object. The value here overrides that of the :class:`.Config` object. :param output_encoding: when using ``--sql`` to generate SQL scripts, apply this encoding to the string output. :param literal_binds: when using ``--sql`` to generate SQL scripts, pass through the ``literal_binds`` flag to the compiler so that any literal values that would ordinarily be bound parameters are converted to plain strings. .. warning:: Dialects can typically only handle simple datatypes like strings and numbers for auto-literal generation. Datatypes like dates, intervals, and others may still require manual formatting, typically using :meth:`.Operations.inline_literal`. .. note:: the ``literal_binds`` flag is ignored on SQLAlchemy versions prior to 0.8 where this feature is not supported. .. seealso:: :meth:`.Operations.inline_literal` :param starting_rev: Override the "starting revision" argument when using ``--sql`` mode. :param tag: a string tag for usage by custom ``env.py`` scripts. Set via the ``--tag`` option, can be overridden here. :param template_args: dictionary of template arguments which will be added to the template argument environment when running the "revision" command. Note that the script environment is only run within the "revision" command if the --autogenerate option is used, or if the option "revision_environment=true" is present in the alembic.ini file. :param version_table: The name of the Alembic version table. The default is ``'alembic_version'``. :param version_table_schema: Optional schema to place version table within. :param version_table_pk: boolean, whether the Alembic version table should use a primary key constraint for the "value" column; this only takes effect when the table is first created. Defaults to True; setting to False should not be necessary and is here for backwards compatibility reasons. :param on_version_apply: a callable or collection of callables to be run for each migration step. The callables will be run in the order they are given, once for each migration step, after the respective operation has been applied but before its transaction is finalized. Each callable accepts no positional arguments and the following keyword arguments: * ``ctx``: the :class:`.MigrationContext` running the migration, * ``step``: a :class:`.MigrationInfo` representing the step currently being applied, * ``heads``: a collection of version strings representing the current heads, * ``run_args``: the ``**kwargs`` passed to :meth:`.run_migrations`. Parameters specific to the autogenerate feature, when ``alembic revision`` is run with the ``--autogenerate`` feature: :param target_metadata: a :class:`sqlalchemy.schema.MetaData` object, or a sequence of :class:`~sqlalchemy.schema.MetaData` objects, that will be consulted during autogeneration. The tables present in each :class:`~sqlalchemy.schema.MetaData` will be compared against what is locally available on the target :class:`~sqlalchemy.engine.Connection` to produce candidate upgrade/downgrade operations. :param compare_type: Indicates type comparison behavior during an autogenerate operation. Defaults to ``False`` which disables type comparison. Set to ``True`` to turn on default type comparison, which has varied accuracy depending on backend. See :ref:`compare_types` for an example as well as information on other type comparison options. .. seealso:: :ref:`compare_types` :paramref:`.EnvironmentContext.configure.compare_server_default` :param compare_server_default: Indicates server default comparison behavior during an autogenerate operation. Defaults to ``False`` which disables server default comparison. Set to ``True`` to turn on server default comparison, which has varied accuracy depending on backend. To customize server default comparison behavior, a callable may be specified which can filter server default comparisons during an autogenerate operation. defaults during an autogenerate operation. The format of this callable is:: def my_compare_server_default(context, inspected_column, metadata_column, inspected_default, metadata_default, rendered_metadata_default): # return True if the defaults are different, # False if not, or None to allow the default implementation # to compare these defaults return None context.configure( # ... compare_server_default = my_compare_server_default ) ``inspected_column`` is a dictionary structure as returned by :meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas ``metadata_column`` is a :class:`sqlalchemy.schema.Column` from the local model environment. A return value of ``None`` indicates to allow default server default comparison to proceed. Note that some backends such as Postgresql actually execute the two defaults on the database side to compare for equivalence. .. seealso:: :paramref:`.EnvironmentContext.configure.compare_type` :param include_name: A callable function which is given the chance to return ``True`` or ``False`` for any database reflected object based on its name, including database schema names when the :paramref:`.EnvironmentContext.configure.include_schemas` flag is set to ``True``. The function accepts the following positional arguments: * ``name``: the name of the object, such as schema name or table name. Will be ``None`` when indicating the default schema name of the database connection. * ``type``: a string describing the type of object; currently ``"schema"``, ``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``, or ``"foreign_key_constraint"`` * ``parent_names``: a dictionary of "parent" object names, that are relative to the name being given. Keys in this dictionary may include: ``"schema_name"``, ``"table_name"``. E.g.:: def include_name(name, type_, parent_names): if type_ == "schema": return name in ["schema_one", "schema_two"] else: return True context.configure( # ... include_schemas = True, include_name = include_name ) .. versionadded:: 1.5 .. seealso:: :ref:`autogenerate_include_hooks` :paramref:`.EnvironmentContext.configure.include_object` :paramref:`.EnvironmentContext.configure.include_schemas` :param include_object: A callable function which is given the chance to return ``True`` or ``False`` for any object, indicating if the given object should be considered in the autogenerate sweep. The function accepts the following positional arguments: * ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such as a :class:`~sqlalchemy.schema.Table`, :class:`~sqlalchemy.schema.Column`, :class:`~sqlalchemy.schema.Index` :class:`~sqlalchemy.schema.UniqueConstraint`, or :class:`~sqlalchemy.schema.ForeignKeyConstraint` object * ``name``: the name of the object. This is typically available via ``object.name``. * ``type``: a string describing the type of object; currently ``"table"``, ``"column"``, ``"index"``, ``"unique_constraint"``, or ``"foreign_key_constraint"`` * ``reflected``: ``True`` if the given object was produced based on table reflection, ``False`` if it's from a local :class:`.MetaData` object. * ``compare_to``: the object being compared against, if available, else ``None``. E.g.:: def include_object(object, name, type_, reflected, compare_to): if (type_ == "column" and not reflected and object.info.get("skip_autogenerate", False)): return False else: return True context.configure( # ... include_object = include_object ) For the use case of omitting specific schemas from a target database when :paramref:`.EnvironmentContext.configure.include_schemas` is set to ``True``, the :attr:`~sqlalchemy.schema.Table.schema` attribute can be checked for each :class:`~sqlalchemy.schema.Table` object passed to the hook, however it is much more efficient to filter on schemas before reflection of objects takes place using the :paramref:`.EnvironmentContext.configure.include_name` hook. .. seealso:: :ref:`autogenerate_include_hooks` :paramref:`.EnvironmentContext.configure.include_name` :paramref:`.EnvironmentContext.configure.include_schemas` :param render_as_batch: if True, commands which alter elements within a table will be placed under a ``with batch_alter_table():`` directive, so that batch migrations will take place. .. seealso:: :ref:`batch_migrations` :param include_schemas: If True, autogenerate will scan across all schemas located by the SQLAlchemy :meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names` method, and include all differences in tables found across all those schemas. When using this option, you may want to also use the :paramref:`.EnvironmentContext.configure.include_name` parameter to specify a callable which can filter the tables/schemas that get included. .. seealso:: :ref:`autogenerate_include_hooks` :paramref:`.EnvironmentContext.configure.include_name` :paramref:`.EnvironmentContext.configure.include_object` :param render_item: Callable that can be used to override how any schema item, i.e. column, constraint, type, etc., is rendered for autogenerate. The callable receives a string describing the type of object, the object, and the autogen context. If it returns False, the default rendering method will be used. If it returns None, the item will not be rendered in the context of a Table construct, that is, can be used to skip columns or constraints within op.create_table():: def my_render_column(type_, col, autogen_context): if type_ == "column" and isinstance(col, MySpecialCol): return repr(col) else: return False context.configure( # ... render_item = my_render_column ) Available values for the type string include: ``"column"``, ``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``, ``"type"``, ``"server_default"``. .. seealso:: :ref:`autogen_render_types` :param upgrade_token: When autogenerate completes, the text of the candidate upgrade operations will be present in this template variable when ``script.py.mako`` is rendered. Defaults to ``upgrades``. :param downgrade_token: When autogenerate completes, the text of the candidate downgrade operations will be present in this template variable when ``script.py.mako`` is rendered. Defaults to ``downgrades``. :param alembic_module_prefix: When autogenerate refers to Alembic :mod:`alembic.operations` constructs, this prefix will be used (i.e. ``op.create_table``) Defaults to "``op.``". Can be ``None`` to indicate no prefix. :param sqlalchemy_module_prefix: When autogenerate refers to SQLAlchemy :class:`~sqlalchemy.schema.Column` or type classes, this prefix will be used (i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``". Can be ``None`` to indicate no prefix. Note that when dialect-specific types are rendered, autogenerate will render them using the dialect module name, i.e. ``mssql.BIT()``, ``postgresql.UUID()``. :param user_module_prefix: When autogenerate refers to a SQLAlchemy type (e.g. :class:`.TypeEngine`) where the module name is not under the ``sqlalchemy`` namespace, this prefix will be used within autogenerate. If left at its default of ``None``, the ``__module__`` attribute of the type is used to render the import module. It's a good practice to set this and to have all custom types be available from a fixed module space, in order to future-proof migration files against reorganizations in modules. .. seealso:: :ref:`autogen_module_prefix` :param process_revision_directives: a callable function that will be passed a structure representing the end result of an autogenerate or plain "revision" operation, which can be manipulated to affect how the ``alembic revision`` command ultimately outputs new revision scripts. The structure of the callable is:: def process_revision_directives(context, revision, directives): pass The ``directives`` parameter is a Python list containing a single :class:`.MigrationScript` directive, which represents the revision file to be generated. This list as well as its contents may be freely modified to produce any set of commands. The section :ref:`customizing_revision` shows an example of doing this. The ``context`` parameter is the :class:`.MigrationContext` in use, and ``revision`` is a tuple of revision identifiers representing the current revision of the database. The callable is invoked at all times when the ``--autogenerate`` option is passed to ``alembic revision``. If ``--autogenerate`` is not passed, the callable is invoked only if the ``revision_environment`` variable is set to True in the Alembic configuration, in which case the given ``directives`` collection will contain empty :class:`.UpgradeOps` and :class:`.DowngradeOps` collections for ``.upgrade_ops`` and ``.downgrade_ops``. The ``--autogenerate`` option itself can be inferred by inspecting ``context.config.cmd_opts.autogenerate``. The callable function may optionally be an instance of a :class:`.Rewriter` object. This is a helper object that assists in the production of autogenerate-stream rewriter functions. .. seealso:: :ref:`customizing_revision` :ref:`autogen_rewriter` :paramref:`.command.revision.process_revision_directives` Parameters specific to individual backends: :param mssql_batch_separator: The "batch separator" which will be placed between each statement when generating offline SQL Server migrations. Defaults to ``GO``. Note this is in addition to the customary semicolon ``;`` at the end of each statement; SQL Server considers the "batch separator" to denote the end of an individual statement execution, and cannot group certain dependent operations in one step. :param oracle_batch_separator: The "batch separator" which will be placed between each statement when generating offline Oracle migrations. Defaults to ``/``. Oracle doesn't add a semicolon between statements like most other backends. """ opts = self.context_opts if transactional_ddl is not None: opts["transactional_ddl"] = transactional_ddl if output_buffer is not None: opts["output_buffer"] = output_buffer elif self.config.output_buffer is not None: opts["output_buffer"] = self.config.output_buffer if starting_rev: opts["starting_rev"] = starting_rev if tag: opts["tag"] = tag if template_args and "template_args" in opts: opts["template_args"].update(template_args) opts["transaction_per_migration"] = transaction_per_migration opts["target_metadata"] = target_metadata opts["include_name"] = include_name opts["include_object"] = include_object opts["include_schemas"] = include_schemas opts["render_as_batch"] = render_as_batch opts["upgrade_token"] = upgrade_token opts["downgrade_token"] = downgrade_token opts["sqlalchemy_module_prefix"] = sqlalchemy_module_prefix opts["alembic_module_prefix"] = alembic_module_prefix opts["user_module_prefix"] = user_module_prefix opts["literal_binds"] = literal_binds opts["process_revision_directives"] = process_revision_directives opts["on_version_apply"] = util.to_tuple(on_version_apply, default=()) if render_item is not None: opts["render_item"] = render_item if compare_type is not None: opts["compare_type"] = compare_type if compare_server_default is not None: opts["compare_server_default"] = compare_server_default opts["script"] = self.script opts.update(kw) self._migration_context = MigrationContext.configure( connection=connection, url=url, dialect_name=dialect_name, environment_context=self, dialect_opts=dialect_opts, opts=opts, ) def run_migrations(self, **kw: Any) -> None: """Run migrations as determined by the current command line configuration as well as versioning information present (or not) in the current database connection (if one is present). The function accepts optional ``**kw`` arguments. If these are passed, they are sent directly to the ``upgrade()`` and ``downgrade()`` functions within each target revision file. By modifying the ``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()`` functions accept arguments, parameters can be passed here so that contextual information, usually information to identify a particular database in use, can be passed from a custom ``env.py`` script to the migration functions. This function requires that a :class:`.MigrationContext` has first been made available via :meth:`.configure`. """ assert self._migration_context is not None with Operations.context(self._migration_context): self.get_context().run_migrations(**kw) def execute( self, sql: Union[ClauseElement, str], execution_options: Optional[dict] = None, ) -> None: """Execute the given SQL using the current change context. The behavior of :meth:`.execute` is the same as that of :meth:`.Operations.execute`. Please see that function's documentation for full detail including caveats and limitations. This function requires that a :class:`.MigrationContext` has first been made available via :meth:`.configure`. """ self.get_context().execute(sql, execution_options=execution_options) def static_output(self, text: str) -> None: """Emit text directly to the "offline" SQL stream. Typically this is for emitting comments that start with --. The statement is not treated as a SQL execution, no ; or batch separator is added, etc. """ self.get_context().impl.static_output(text) def begin_transaction( self, ) -> Union[_ProxyTransaction, ContextManager]: """Return a context manager that will enclose an operation within a "transaction", as defined by the environment's offline and transactional DDL settings. e.g.:: with context.begin_transaction(): context.run_migrations() :meth:`.begin_transaction` is intended to "do the right thing" regardless of calling context: * If :meth:`.is_transactional_ddl` is ``False``, returns a "do nothing" context manager which otherwise produces no transactional state or directives. * If :meth:`.is_offline_mode` is ``True``, returns a context manager that will invoke the :meth:`.DefaultImpl.emit_begin` and :meth:`.DefaultImpl.emit_commit` methods, which will produce the string directives ``BEGIN`` and ``COMMIT`` on the output stream, as rendered by the target backend (e.g. SQL Server would emit ``BEGIN TRANSACTION``). * Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin` on the current online connection, which returns a :class:`sqlalchemy.engine.Transaction` object. This object demarcates a real transaction and is itself a context manager, which will roll back if an exception is raised. Note that a custom ``env.py`` script which has more specific transactional needs can of course manipulate the :class:`~sqlalchemy.engine.Connection` directly to produce transactional state in "online" mode. """ return self.get_context().begin_transaction() def get_context(self) -> MigrationContext: """Return the current :class:`.MigrationContext` object. If :meth:`.EnvironmentContext.configure` has not been called yet, raises an exception. """ if self._migration_context is None: raise Exception("No context has been configured yet.") return self._migration_context def get_bind(self) -> Connection: """Return the current 'bind'. In "online" mode, this is the :class:`sqlalchemy.engine.Connection` currently being used to emit SQL to the database. This function requires that a :class:`.MigrationContext` has first been made available via :meth:`.configure`. """ return self.get_context().bind # type: ignore[return-value] def get_impl(self) -> DefaultImpl: return self.get_context().impl
mit
5e9f702822215ff7eafa7b413d53414a
39.358763
79
0.627286
4.733736
false
true
false
false
marshmallow-code/marshmallow
performance/benchmark.py
2
3928
"""Simple benchmark for Marshmallow serialization of a moderately complex object. Uses the `timeit` module to benchmark serializing an object through Marshmallow. """ import argparse import cProfile import gc import timeit import datetime from marshmallow import Schema, fields, ValidationError, post_dump # Custom validator def must_not_be_blank(data): if not data: raise ValidationError("Data not provided.") class AuthorSchema(Schema): id = fields.Int(dump_only=True) first = fields.Str() last = fields.Str() book_count = fields.Float() age = fields.Float() address = fields.Str() full_name = fields.Method("get_full_name") def get_full_name(self, author): return f"{author.last}, {author.first}" class QuoteSchema(Schema): id = fields.Int(dump_only=True) author = fields.Nested(AuthorSchema, validate=must_not_be_blank) content = fields.Str(required=True, validate=must_not_be_blank) posted_at = fields.DateTime(dump_only=True) book_name = fields.Str() page_number = fields.Float() line_number = fields.Float() col_number = fields.Float() @post_dump def add_full_name(self, data, **kwargs): data["author_full"] = "{}, {}".format( data["author"]["last"], data["author"]["first"] ) return data class Author: def __init__(self, id, first, last, book_count, age, address): self.id = id self.first = first self.last = last self.book_count = book_count self.age = age self.address = address class Quote: def __init__( self, id, author, content, posted_at, book_name, page_number, line_number, col_number, ): self.id = id self.author = author self.content = content self.posted_at = posted_at self.book_name = book_name self.page_number = page_number self.line_number = line_number self.col_number = col_number def run_timeit(quotes, iterations, repeat, profile=False): quotes_schema = QuoteSchema(many=True) if profile: profile = cProfile.Profile() profile.enable() gc.collect() best = min( timeit.repeat( lambda: quotes_schema.dump(quotes), "gc.enable()", number=iterations, repeat=repeat, ) ) if profile: profile.disable() profile.dump_stats("marshmallow.pprof") usec = best * 1e6 / iterations return usec def main(): parser = argparse.ArgumentParser(description="Runs a benchmark of Marshmallow.") parser.add_argument( "--iterations", type=int, default=1000, help="Number of iterations to run per test.", ) parser.add_argument( "--repeat", type=int, default=5, help="Number of times to repeat the performance test. The minimum will " "be used.", ) parser.add_argument( "--object-count", type=int, default=20, help="Number of objects to dump." ) parser.add_argument( "--profile", action="store_true", help="Whether or not to profile Marshmallow while running the benchmark.", ) args = parser.parse_args() quotes = [] for i in range(args.object_count): quotes.append( Quote( i, Author(i, "Foo", "Bar", 42, 66, "123 Fake St"), "Hello World", datetime.datetime(2019, 7, 4, tzinfo=datetime.timezone.utc), "The World", 34, 3, 70, ) ) print( "Benchmark Result: {:.2f} usec/dump".format( run_timeit(quotes, args.iterations, args.repeat, profile=args.profile) ) ) if __name__ == "__main__": main()
mit
94f03097f329c3ba2d14c3fd0766be44
24.341935
84
0.574084
3.892963
false
false
false
false
marshmallow-code/marshmallow
src/marshmallow/schema.py
2
49206
"""The :class:`Schema` class, including its metaclass and options (class Meta).""" from __future__ import annotations from collections import defaultdict, OrderedDict from collections.abc import Mapping from functools import lru_cache import datetime as dt import uuid import decimal import copy import inspect import json import typing import warnings from marshmallow import base, fields as ma_fields, class_registry, types from marshmallow.error_store import ErrorStore from marshmallow.exceptions import ValidationError, StringNotCollectionError from marshmallow.orderedset import OrderedSet from marshmallow.decorators import ( POST_DUMP, POST_LOAD, PRE_DUMP, PRE_LOAD, VALIDATES, VALIDATES_SCHEMA, ) from marshmallow.utils import ( RAISE, EXCLUDE, INCLUDE, missing, set_value, get_value, is_collection, is_instance_or_subclass, validate_unknown_parameter_value, ) from marshmallow.warnings import RemovedInMarshmallow4Warning _T = typing.TypeVar("_T") def _get_fields(attrs, ordered=False): """Get fields from a class. If ordered=True, fields will sorted by creation index. :param attrs: Mapping of class attributes :param bool ordered: Sort fields by creation index """ fields = [ (field_name, field_value) for field_name, field_value in attrs.items() if is_instance_or_subclass(field_value, base.FieldABC) ] if ordered: fields.sort(key=lambda pair: pair[1]._creation_index) return fields # This function allows Schemas to inherit from non-Schema classes and ensures # inheritance according to the MRO def _get_fields_by_mro(klass, ordered=False): """Collect fields from a class, following its method resolution order. The class itself is excluded from the search; only its parents are checked. Get fields from ``_declared_fields`` if available, else use ``__dict__``. :param type klass: Class whose fields to retrieve """ mro = inspect.getmro(klass) # Loop over mro in reverse to maintain correct order of fields return sum( ( _get_fields( getattr(base, "_declared_fields", base.__dict__), ordered=ordered, ) for base in mro[:0:-1] ), [], ) class SchemaMeta(type): """Metaclass for the Schema class. Binds the declared fields to a ``_declared_fields`` attribute, which is a dictionary mapping attribute names to field objects. Also sets the ``opts`` class attribute, which is the Schema class's ``class Meta`` options. """ def __new__(mcs, name, bases, attrs): meta = attrs.get("Meta") ordered = getattr(meta, "ordered", False) if not ordered: # Inherit 'ordered' option # Warning: We loop through bases instead of MRO because we don't # yet have access to the class object # (i.e. can't call super before we have fields) for base_ in bases: if hasattr(base_, "Meta") and hasattr(base_.Meta, "ordered"): ordered = base_.Meta.ordered break else: ordered = False cls_fields = _get_fields(attrs, ordered=ordered) # Remove fields from list of class attributes to avoid shadowing # Schema attributes/methods in case of name conflict for field_name, _ in cls_fields: del attrs[field_name] klass = super().__new__(mcs, name, bases, attrs) inherited_fields = _get_fields_by_mro(klass, ordered=ordered) meta = klass.Meta # Set klass.opts in __new__ rather than __init__ so that it is accessible in # get_declared_fields klass.opts = klass.OPTIONS_CLASS(meta, ordered=ordered) # Add fields specified in the `include` class Meta option cls_fields += list(klass.opts.include.items()) dict_cls = OrderedDict if ordered else dict # Assign _declared_fields on class klass._declared_fields = mcs.get_declared_fields( klass=klass, cls_fields=cls_fields, inherited_fields=inherited_fields, dict_cls=dict_cls, ) return klass @classmethod def get_declared_fields( mcs, klass: type, cls_fields: list, inherited_fields: list, dict_cls: type, ): """Returns a dictionary of field_name => `Field` pairs declared on the class. This is exposed mainly so that plugins can add additional fields, e.g. fields computed from class Meta options. :param klass: The class object. :param cls_fields: The fields declared on the class, including those added by the ``include`` class Meta option. :param inherited_fields: Inherited fields. :param dict_cls: Either `dict` or `OrderedDict`, depending on whether the user specified `ordered=True`. """ return dict_cls(inherited_fields + cls_fields) def __init__(cls, name, bases, attrs): super().__init__(name, bases, attrs) if name and cls.opts.register: class_registry.register(name, cls) cls._hooks = cls.resolve_hooks() def resolve_hooks(cls) -> dict[types.Tag, list[str]]: """Add in the decorated processors By doing this after constructing the class, we let standard inheritance do all the hard work. """ mro = inspect.getmro(cls) hooks = defaultdict(list) # type: typing.Dict[types.Tag, typing.List[str]] for attr_name in dir(cls): # Need to look up the actual descriptor, not whatever might be # bound to the class. This needs to come from the __dict__ of the # declaring class. for parent in mro: try: attr = parent.__dict__[attr_name] except KeyError: continue else: break else: # In case we didn't find the attribute and didn't break above. # We should never hit this - it's just here for completeness # to exclude the possibility of attr being undefined. continue try: hook_config = attr.__marshmallow_hook__ except AttributeError: pass else: for key in hook_config.keys(): # Use name here so we can get the bound method later, in # case the processor was a descriptor or something. hooks[key].append(attr_name) return hooks class SchemaOpts: """class Meta options for the :class:`Schema`. Defines defaults.""" def __init__(self, meta, ordered: bool = False): self.fields = getattr(meta, "fields", ()) if not isinstance(self.fields, (list, tuple)): raise ValueError("`fields` option must be a list or tuple.") self.additional = getattr(meta, "additional", ()) if not isinstance(self.additional, (list, tuple)): raise ValueError("`additional` option must be a list or tuple.") if self.fields and self.additional: raise ValueError( "Cannot set both `fields` and `additional` options" " for the same Schema." ) self.exclude = getattr(meta, "exclude", ()) if not isinstance(self.exclude, (list, tuple)): raise ValueError("`exclude` must be a list or tuple.") self.dateformat = getattr(meta, "dateformat", None) self.datetimeformat = getattr(meta, "datetimeformat", None) self.timeformat = getattr(meta, "timeformat", None) if hasattr(meta, "json_module"): warnings.warn( "The json_module class Meta option is deprecated. Use render_module instead.", RemovedInMarshmallow4Warning, ) render_module = getattr(meta, "json_module", json) else: render_module = json self.render_module = getattr(meta, "render_module", render_module) self.ordered = getattr(meta, "ordered", ordered) self.index_errors = getattr(meta, "index_errors", True) self.include = getattr(meta, "include", {}) self.load_only = getattr(meta, "load_only", ()) self.dump_only = getattr(meta, "dump_only", ()) self.unknown = validate_unknown_parameter_value(getattr(meta, "unknown", RAISE)) self.register = getattr(meta, "register", True) class Schema(base.SchemaABC, metaclass=SchemaMeta): """Base schema class with which to define custom schemas. Example usage: .. code-block:: python import datetime as dt from dataclasses import dataclass from marshmallow import Schema, fields @dataclass class Album: title: str release_date: dt.date class AlbumSchema(Schema): title = fields.Str() release_date = fields.Date() album = Album("Beggars Banquet", dt.date(1968, 12, 6)) schema = AlbumSchema() data = schema.dump(album) data # {'release_date': '1968-12-06', 'title': 'Beggars Banquet'} :param only: Whitelist of the declared fields to select when instantiating the Schema. If None, all fields are used. Nested fields can be represented with dot delimiters. :param exclude: Blacklist of the declared fields to exclude when instantiating the Schema. If a field appears in both `only` and `exclude`, it is not used. Nested fields can be represented with dot delimiters. :param many: Should be set to `True` if ``obj`` is a collection so that the object will be serialized to a list. :param context: Optional context passed to :class:`fields.Method` and :class:`fields.Function` fields. :param load_only: Fields to skip during serialization (write-only fields) :param dump_only: Fields to skip during deserialization (read-only fields) :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. .. versionchanged:: 3.0.0 `prefix` parameter removed. .. versionchanged:: 2.0.0 `__validators__`, `__preprocessors__`, and `__data_handlers__` are removed in favor of `marshmallow.decorators.validates_schema`, `marshmallow.decorators.pre_load` and `marshmallow.decorators.post_dump`. `__accessor__` and `__error_handler__` are deprecated. Implement the `handle_error` and `get_attribute` methods instead. """ TYPE_MAPPING = { str: ma_fields.String, bytes: ma_fields.String, dt.datetime: ma_fields.DateTime, float: ma_fields.Float, bool: ma_fields.Boolean, tuple: ma_fields.Raw, list: ma_fields.Raw, set: ma_fields.Raw, int: ma_fields.Integer, uuid.UUID: ma_fields.UUID, dt.time: ma_fields.Time, dt.date: ma_fields.Date, dt.timedelta: ma_fields.TimeDelta, decimal.Decimal: ma_fields.Decimal, } # type: typing.Dict[type, typing.Type[ma_fields.Field]] #: Overrides for default schema-level error messages error_messages = {} # type: typing.Dict[str, str] _default_error_messages = { "type": "Invalid input type.", "unknown": "Unknown field.", } # type: typing.Dict[str, str] OPTIONS_CLASS = SchemaOpts # type: type # These get set by SchemaMeta opts = None # type: SchemaOpts _declared_fields = {} # type: typing.Dict[str, ma_fields.Field] _hooks = {} # type: typing.Dict[types.Tag, typing.List[str]] class Meta: """Options object for a Schema. Example usage: :: class Meta: fields = ("id", "email", "date_created") exclude = ("password", "secret_attribute") Available options: - ``fields``: Tuple or list of fields to include in the serialized result. - ``additional``: Tuple or list of fields to include *in addition* to the explicitly declared fields. ``additional`` and ``fields`` are mutually-exclusive options. - ``include``: Dictionary of additional fields to include in the schema. It is usually better to define fields as class variables, but you may need to use this option, e.g., if your fields are Python keywords. May be an `OrderedDict`. - ``exclude``: Tuple or list of fields to exclude in the serialized result. Nested fields can be represented with dot delimiters. - ``dateformat``: Default format for `Date <fields.Date>` fields. - ``datetimeformat``: Default format for `DateTime <fields.DateTime>` fields. - ``timeformat``: Default format for `Time <fields.Time>` fields. - ``render_module``: Module to use for `loads <Schema.loads>` and `dumps <Schema.dumps>`. Defaults to `json` from the standard library. - ``ordered``: If `True`, order serialization output according to the order in which fields were declared. Output of `Schema.dump` will be a `collections.OrderedDict`. - ``index_errors``: If `True`, errors dictionaries will include the index of invalid items in a collection. - ``load_only``: Tuple or list of fields to exclude from serialized results. - ``dump_only``: Tuple or list of fields to exclude from deserialization - ``unknown``: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. - ``register``: Whether to register the `Schema` with marshmallow's internal class registry. Must be `True` if you intend to refer to this `Schema` by class name in `Nested` fields. Only set this to `False` when memory usage is critical. Defaults to `True`. """ def __init__( self, *, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, context: dict | None = None, load_only: types.StrSequenceOrSet = (), dump_only: types.StrSequenceOrSet = (), partial: bool | types.StrSequenceOrSet = False, unknown: str | None = None, ): # Raise error if only or exclude is passed as string, not list of strings if only is not None and not is_collection(only): raise StringNotCollectionError('"only" should be a list of strings') if not is_collection(exclude): raise StringNotCollectionError('"exclude" should be a list of strings') # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.many = many self.only = only self.exclude = set(self.opts.exclude) | set(exclude) self.ordered = self.opts.ordered self.load_only = set(load_only) or set(self.opts.load_only) self.dump_only = set(dump_only) or set(self.opts.dump_only) self.partial = partial self.unknown = ( self.opts.unknown if unknown is None else validate_unknown_parameter_value(unknown) ) self.context = context or {} self._normalize_nested_options() #: Dictionary mapping field_names -> :class:`Field` objects self.fields = {} # type: typing.Dict[str, ma_fields.Field] self.load_fields = {} # type: typing.Dict[str, ma_fields.Field] self.dump_fields = {} # type: typing.Dict[str, ma_fields.Field] self._init_fields() messages = {} messages.update(self._default_error_messages) for cls in reversed(self.__class__.__mro__): messages.update(getattr(cls, "error_messages", {})) messages.update(self.error_messages or {}) self.error_messages = messages def __repr__(self) -> str: return "<{ClassName}(many={self.many})>".format( ClassName=self.__class__.__name__, self=self ) @property def dict_class(self) -> type: return OrderedDict if self.ordered else dict @property def set_class(self) -> type: return OrderedSet if self.ordered else set @classmethod def from_dict( cls, fields: dict[str, ma_fields.Field | type], *, name: str = "GeneratedSchema", ) -> type: """Generate a `Schema` class given a dictionary of fields. .. code-block:: python from marshmallow import Schema, fields PersonSchema = Schema.from_dict({"name": fields.Str()}) print(PersonSchema().load({"name": "David"})) # => {'name': 'David'} Generated schemas are not added to the class registry and therefore cannot be referred to by name in `Nested` fields. :param dict fields: Dictionary mapping field names to field instances. :param str name: Optional name for the class, which will appear in the ``repr`` for the class. .. versionadded:: 3.0.0 """ attrs = fields.copy() attrs["Meta"] = type( "GeneratedMeta", (getattr(cls, "Meta", object),), {"register": False} ) schema_cls = type(name, (cls,), attrs) return schema_cls ##### Override-able methods ##### def handle_error( self, error: ValidationError, data: typing.Any, *, many: bool, **kwargs ): """Custom error handler function for the schema. :param error: The `ValidationError` raised during (de)serialization. :param data: The original input data. :param many: Value of ``many`` on dump or load. :param partial: Value of ``partial`` on load. .. versionadded:: 2.0.0 .. versionchanged:: 3.0.0rc9 Receives `many` and `partial` (on deserialization) as keyword arguments. """ pass def get_attribute(self, obj: typing.Any, attr: str, default: typing.Any): """Defines how to pull values from an object to serialize. .. versionadded:: 2.0.0 .. versionchanged:: 3.0.0a1 Changed position of ``obj`` and ``attr``. """ return get_value(obj, attr, default) ##### Serialization/Deserialization API ##### @staticmethod def _call_and_store(getter_func, data, *, field_name, error_store, index=None): """Call ``getter_func`` with ``data`` as its argument, and store any `ValidationErrors`. :param callable getter_func: Function for getting the serialized/deserialized value from ``data``. :param data: The data passed to ``getter_func``. :param str field_name: Field name. :param int index: Index of the item being validated, if validating a collection, otherwise `None`. """ try: value = getter_func(data) except ValidationError as error: error_store.store_error(error.messages, field_name, index=index) # When a Nested field fails validation, the marshalled data is stored # on the ValidationError's valid_data attribute return error.valid_data or missing return value def _serialize(self, obj: _T | typing.Iterable[_T], *, many: bool = False): """Serialize ``obj``. :param obj: The object(s) to serialize. :param bool many: `True` if ``data`` should be serialized as a collection. :return: A dictionary of the serialized data .. versionchanged:: 1.0.0 Renamed from ``marshal``. """ if many and obj is not None: return [ self._serialize(d, many=False) for d in typing.cast(typing.Iterable[_T], obj) ] ret = self.dict_class() for attr_name, field_obj in self.dump_fields.items(): value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute) if value is missing: continue key = field_obj.data_key if field_obj.data_key is not None else attr_name ret[key] = value return ret def dump(self, obj: typing.Any, *, many: bool | None = None): """Serialize an object to native Python data types according to this Schema's fields. :param obj: The object to serialize. :param many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: Serialized data .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the serialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if ``obj`` is invalid. .. versionchanged:: 3.0.0rc9 Validation no longer occurs upon serialization. """ many = self.many if many is None else bool(many) if self._has_processors(PRE_DUMP): processed_obj = self._invoke_dump_processors( PRE_DUMP, obj, many=many, original_data=obj ) else: processed_obj = obj result = self._serialize(processed_obj, many=many) if self._has_processors(POST_DUMP): result = self._invoke_dump_processors( POST_DUMP, result, many=many, original_data=obj ) return result def dumps(self, obj: typing.Any, *args, many: bool | None = None, **kwargs): """Same as :meth:`dump`, except return a JSON-encoded string. :param obj: The object to serialize. :param many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A ``json`` string .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the serialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if ``obj`` is invalid. """ serialized = self.dump(obj, many=many) return self.opts.render_module.dumps(serialized, *args, **kwargs) def _deserialize( self, data: ( typing.Mapping[str, typing.Any] | typing.Iterable[typing.Mapping[str, typing.Any]] ), *, error_store: ErrorStore, many: bool = False, partial=False, unknown=RAISE, index=None, ) -> _T | list[_T]: """Deserialize ``data``. :param dict data: The data to deserialize. :param ErrorStore error_store: Structure to store errors. :param bool many: `True` if ``data`` should be deserialized as a collection. :param bool|tuple partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. :param int index: Index of the item being serialized (for storing errors) if serializing a collection, otherwise `None`. :return: A dictionary of the deserialized data. """ index_errors = self.opts.index_errors index = index if index_errors else None if many: if not is_collection(data): error_store.store_error([self.error_messages["type"]], index=index) ret_l = [] # type: typing.List[_T] else: ret_l = [ typing.cast( _T, self._deserialize( typing.cast(typing.Mapping[str, typing.Any], d), error_store=error_store, many=False, partial=partial, unknown=unknown, index=idx, ), ) for idx, d in enumerate(data) ] return ret_l ret_d = self.dict_class() # Check data is a dict if not isinstance(data, Mapping): error_store.store_error([self.error_messages["type"]], index=index) else: partial_is_collection = is_collection(partial) for attr_name, field_obj in self.load_fields.items(): field_name = ( field_obj.data_key if field_obj.data_key is not None else attr_name ) raw_value = data.get(field_name, missing) if raw_value is missing: # Ignore missing field if we're allowed to. if partial is True or ( partial_is_collection and attr_name in partial ): continue d_kwargs = {} # Allow partial loading of nested schemas. if partial_is_collection: prefix = field_name + "." len_prefix = len(prefix) sub_partial = [ f[len_prefix:] for f in partial if f.startswith(prefix) ] d_kwargs["partial"] = sub_partial else: d_kwargs["partial"] = partial getter = lambda val: field_obj.deserialize( val, field_name, data, **d_kwargs ) value = self._call_and_store( getter_func=getter, data=raw_value, field_name=field_name, error_store=error_store, index=index, ) if value is not missing: key = field_obj.attribute or attr_name set_value(ret_d, key, value) if unknown != EXCLUDE: fields = { field_obj.data_key if field_obj.data_key is not None else field_name for field_name, field_obj in self.load_fields.items() } for key in set(data) - fields: value = data[key] if unknown == INCLUDE: ret_d[key] = value elif unknown == RAISE: error_store.store_error( [self.error_messages["unknown"]], key, (index if index_errors else None), ) return ret_d def load( self, data: ( typing.Mapping[str, typing.Any] | typing.Iterable[typing.Mapping[str, typing.Any]] ), *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, ): """Deserialize a data structure to an object defined by this Schema's fields. :param data: The data to deserialize. :param many: Whether to deserialize `data` as a collection. If `None`, the value for `self.many` is used. :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. If `None`, the value for `self.unknown` is used. :return: Deserialized data .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the deserialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if invalid data are passed. """ return self._do_load( data, many=many, partial=partial, unknown=unknown, postprocess=True ) def loads( self, json_data: str, *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, **kwargs, ): """Same as :meth:`load`, except it takes a JSON string as input. :param json_data: A JSON string of the data to deserialize. :param many: Whether to deserialize `obj` as a collection. If `None`, the value for `self.many` is used. :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. If `None`, the value for `self.unknown` is used. :return: Deserialized data .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the deserialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if invalid data are passed. """ data = self.opts.render_module.loads(json_data, **kwargs) return self.load(data, many=many, partial=partial, unknown=unknown) def _run_validator( self, validator_func, output, *, original_data, error_store, many, partial, pass_original, index=None, ): try: if pass_original: # Pass original, raw data (before unmarshalling) validator_func(output, original_data, partial=partial, many=many) else: validator_func(output, partial=partial, many=many) except ValidationError as err: error_store.store_error(err.messages, err.field_name, index=index) def validate( self, data: ( typing.Mapping[str, typing.Any] | typing.Iterable[typing.Mapping[str, typing.Any]] ), *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, ) -> dict[str, list[str]]: """Validate `data` against the schema, returning a dictionary of validation errors. :param data: The data to validate. :param many: Whether to validate `data` as a collection. If `None`, the value for `self.many` is used. :param partial: Whether to ignore missing fields and not require any fields declared. Propagates down to ``Nested`` fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields. :return: A dictionary of validation errors. .. versionadded:: 1.1.0 """ try: self._do_load(data, many=many, partial=partial, postprocess=False) except ValidationError as exc: return typing.cast(typing.Dict[str, typing.List[str]], exc.messages) return {} ##### Private Helpers ##### def _do_load( self, data: ( typing.Mapping[str, typing.Any] | typing.Iterable[typing.Mapping[str, typing.Any]] ), *, many: bool | None = None, partial: bool | types.StrSequenceOrSet | None = None, unknown: str | None = None, postprocess: bool = True, ): """Deserialize `data`, returning the deserialized result. This method is private API. :param data: The data to deserialize. :param many: Whether to deserialize `data` as a collection. If `None`, the value for `self.many` is used. :param partial: Whether to validate required fields. If its value is an iterable, only fields listed in that iterable will be ignored will be allowed missing. If `True`, all fields will be allowed missing. If `None`, the value for `self.partial` is used. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. If `None`, the value for `self.unknown` is used. :param postprocess: Whether to run post_load methods.. :return: Deserialized data """ error_store = ErrorStore() errors = {} # type: dict[str, list[str]] many = self.many if many is None else bool(many) unknown = ( self.unknown if unknown is None else validate_unknown_parameter_value(unknown) ) if partial is None: partial = self.partial # Run preprocessors if self._has_processors(PRE_LOAD): try: processed_data = self._invoke_load_processors( PRE_LOAD, data, many=many, original_data=data, partial=partial ) except ValidationError as err: errors = err.normalized_messages() result = None # type: list | dict | None else: processed_data = data if not errors: # Deserialize data result = self._deserialize( processed_data, error_store=error_store, many=many, partial=partial, unknown=unknown, ) # Run field-level validation self._invoke_field_validators( error_store=error_store, data=result, many=many ) # Run schema-level validation if self._has_processors(VALIDATES_SCHEMA): field_errors = bool(error_store.errors) self._invoke_schema_validators( error_store=error_store, pass_many=True, data=result, original_data=data, many=many, partial=partial, field_errors=field_errors, ) self._invoke_schema_validators( error_store=error_store, pass_many=False, data=result, original_data=data, many=many, partial=partial, field_errors=field_errors, ) errors = error_store.errors # Run post processors if not errors and postprocess and self._has_processors(POST_LOAD): try: result = self._invoke_load_processors( POST_LOAD, result, many=many, original_data=data, partial=partial, ) except ValidationError as err: errors = err.normalized_messages() if errors: exc = ValidationError(errors, data=data, valid_data=result) self.handle_error(exc, data, many=many, partial=partial) raise exc return result def _normalize_nested_options(self) -> None: """Apply then flatten nested schema options. This method is private API. """ if self.only is not None: # Apply the only option to nested fields. self.__apply_nested_option("only", self.only, "intersection") # Remove the child field names from the only option. self.only = self.set_class([field.split(".", 1)[0] for field in self.only]) if self.exclude: # Apply the exclude option to nested fields. self.__apply_nested_option("exclude", self.exclude, "union") # Remove the parent field names from the exclude option. self.exclude = self.set_class( [field for field in self.exclude if "." not in field] ) def __apply_nested_option(self, option_name, field_names, set_operation) -> None: """Apply nested options to nested fields""" # Split nested field names on the first dot. nested_fields = [name.split(".", 1) for name in field_names if "." in name] # Partition the nested field names by parent field. nested_options = defaultdict(list) # type: defaultdict for parent, nested_names in nested_fields: nested_options[parent].append(nested_names) # Apply the nested field options. for key, options in iter(nested_options.items()): new_options = self.set_class(options) original_options = getattr(self.declared_fields[key], option_name, ()) if original_options: if set_operation == "union": new_options |= self.set_class(original_options) if set_operation == "intersection": new_options &= self.set_class(original_options) setattr(self.declared_fields[key], option_name, new_options) def _init_fields(self) -> None: """Update self.fields, self.load_fields, and self.dump_fields based on schema options. This method is private API. """ if self.opts.fields: available_field_names = self.set_class(self.opts.fields) else: available_field_names = self.set_class(self.declared_fields.keys()) if self.opts.additional: available_field_names |= self.set_class(self.opts.additional) invalid_fields = self.set_class() if self.only is not None: # Return only fields specified in only option field_names = self.set_class(self.only) invalid_fields |= field_names - available_field_names else: field_names = available_field_names # If "exclude" option or param is specified, remove those fields. if self.exclude: # Note that this isn't available_field_names, since we want to # apply "only" for the actual calculation. field_names = field_names - self.exclude invalid_fields |= self.exclude - available_field_names if invalid_fields: message = f"Invalid fields for {self}: {invalid_fields}." raise ValueError(message) fields_dict = self.dict_class() for field_name in field_names: field_obj = self.declared_fields.get(field_name, ma_fields.Inferred()) self._bind_field(field_name, field_obj) fields_dict[field_name] = field_obj load_fields, dump_fields = self.dict_class(), self.dict_class() for field_name, field_obj in fields_dict.items(): if not field_obj.dump_only: load_fields[field_name] = field_obj if not field_obj.load_only: dump_fields[field_name] = field_obj dump_data_keys = [ field_obj.data_key if field_obj.data_key is not None else name for name, field_obj in dump_fields.items() ] if len(dump_data_keys) != len(set(dump_data_keys)): data_keys_duplicates = { x for x in dump_data_keys if dump_data_keys.count(x) > 1 } raise ValueError( "The data_key argument for one or more fields collides " "with another field's name or data_key argument. " "Check the following field names and " "data_key arguments: {}".format(list(data_keys_duplicates)) ) load_attributes = [obj.attribute or name for name, obj in load_fields.items()] if len(load_attributes) != len(set(load_attributes)): attributes_duplicates = { x for x in load_attributes if load_attributes.count(x) > 1 } raise ValueError( "The attribute argument for one or more fields collides " "with another field's name or attribute argument. " "Check the following field names and " "attribute arguments: {}".format(list(attributes_duplicates)) ) self.fields = fields_dict self.dump_fields = dump_fields self.load_fields = load_fields def on_bind_field(self, field_name: str, field_obj: ma_fields.Field) -> None: """Hook to modify a field when it is bound to the `Schema`. No-op by default. """ return None def _bind_field(self, field_name: str, field_obj: ma_fields.Field) -> None: """Bind field to the schema, setting any necessary attributes on the field (e.g. parent and name). Also set field load_only and dump_only values if field_name was specified in ``class Meta``. """ if field_name in self.load_only: field_obj.load_only = True if field_name in self.dump_only: field_obj.dump_only = True try: field_obj._bind_to_schema(field_name, self) except TypeError as error: # Field declared as a class, not an instance. Ignore type checking because # we handle unsupported arg types, i.e. this is dead code from # the type checker's perspective. if isinstance(field_obj, type) and issubclass(field_obj, base.FieldABC): msg = ( 'Field for "{}" must be declared as a ' "Field instance, not a class. " 'Did you mean "fields.{}()"?'.format(field_name, field_obj.__name__) ) raise TypeError(msg) from error raise error self.on_bind_field(field_name, field_obj) @lru_cache(maxsize=8) def _has_processors(self, tag) -> bool: return bool(self._hooks[(tag, True)] or self._hooks[(tag, False)]) def _invoke_dump_processors( self, tag: str, data, *, many: bool, original_data=None ): # The pass_many post-dump processors may do things like add an envelope, so # invoke those after invoking the non-pass_many processors which will expect # to get a list of items. data = self._invoke_processors( tag, pass_many=False, data=data, many=many, original_data=original_data ) data = self._invoke_processors( tag, pass_many=True, data=data, many=many, original_data=original_data ) return data def _invoke_load_processors( self, tag: str, data, *, many: bool, original_data, partial: bool | types.StrSequenceOrSet, ): # This has to invert the order of the dump processors, so run the pass_many # processors first. data = self._invoke_processors( tag, pass_many=True, data=data, many=many, original_data=original_data, partial=partial, ) data = self._invoke_processors( tag, pass_many=False, data=data, many=many, original_data=original_data, partial=partial, ) return data def _invoke_field_validators(self, *, error_store: ErrorStore, data, many: bool): for attr_name in self._hooks[VALIDATES]: validator = getattr(self, attr_name) validator_kwargs = validator.__marshmallow_hook__[VALIDATES] field_name = validator_kwargs["field_name"] try: field_obj = self.fields[field_name] except KeyError as error: if field_name in self.declared_fields: continue raise ValueError(f'"{field_name}" field does not exist.') from error data_key = ( field_obj.data_key if field_obj.data_key is not None else field_name ) if many: for idx, item in enumerate(data): try: value = item[field_obj.attribute or field_name] except KeyError: pass else: validated_value = self._call_and_store( getter_func=validator, data=value, field_name=data_key, error_store=error_store, index=(idx if self.opts.index_errors else None), ) if validated_value is missing: data[idx].pop(field_name, None) else: try: value = data[field_obj.attribute or field_name] except KeyError: pass else: validated_value = self._call_and_store( getter_func=validator, data=value, field_name=data_key, error_store=error_store, ) if validated_value is missing: data.pop(field_name, None) def _invoke_schema_validators( self, *, error_store: ErrorStore, pass_many: bool, data, original_data, many: bool, partial: bool | types.StrSequenceOrSet, field_errors: bool = False, ): for attr_name in self._hooks[(VALIDATES_SCHEMA, pass_many)]: validator = getattr(self, attr_name) validator_kwargs = validator.__marshmallow_hook__[ (VALIDATES_SCHEMA, pass_many) ] if field_errors and validator_kwargs["skip_on_field_errors"]: continue pass_original = validator_kwargs.get("pass_original", False) if many and not pass_many: for idx, (item, orig) in enumerate(zip(data, original_data)): self._run_validator( validator, item, original_data=orig, error_store=error_store, many=many, partial=partial, index=idx, pass_original=pass_original, ) else: self._run_validator( validator, data, original_data=original_data, error_store=error_store, many=many, pass_original=pass_original, partial=partial, ) def _invoke_processors( self, tag: str, *, pass_many: bool, data, many: bool, original_data=None, **kwargs, ): key = (tag, pass_many) for attr_name in self._hooks[key]: # This will be a bound method. processor = getattr(self, attr_name) processor_kwargs = processor.__marshmallow_hook__[key] pass_original = processor_kwargs.get("pass_original", False) if many and not pass_many: if pass_original: data = [ processor(item, original, many=many, **kwargs) for item, original in zip(data, original_data) ] else: data = [processor(item, many=many, **kwargs) for item in data] else: if pass_original: data = processor(data, original_data, many=many, **kwargs) else: data = processor(data, many=many, **kwargs) return data BaseSchema = Schema # for backwards compatibility
mit
775398daad2bdbc4e7aa577404a02bad
39.037429
97
0.564951
4.473273
false
false
false
false
cupy/cupy
cupyx/scipy/ndimage/_spline_prefilter_core.py
1
8827
""" Spline poles and boundary handling implemented as in SciPy https://github.com/scipy/scipy/blob/master/scipy/ndimage/src/ni_splines.c """ import functools import math import operator import textwrap import cupy def get_poles(order): if order == 2: # sqrt(8.0) - 3.0 return (-0.171572875253809902396622551580603843,) elif order == 3: # sqrt(3.0) - 2.0 return (-0.267949192431122706472553658494127633,) elif order == 4: # sqrt(664.0 - sqrt(438976.0)) + sqrt(304.0) - 19.0 # sqrt(664.0 + sqrt(438976.0)) - sqrt(304.0) - 19.0 return (-0.361341225900220177092212841325675255, -0.013725429297339121360331226939128204) elif order == 5: # sqrt(67.5 - sqrt(4436.25)) + sqrt(26.25) - 6.5 # sqrt(67.5 + sqrt(4436.25)) - sqrt(26.25) - 6.5 return (-0.430575347099973791851434783493520110, -0.043096288203264653822712376822550182) else: raise ValueError('only order 2-5 supported') def get_gain(poles): return functools.reduce(operator.mul, [(1.0 - z) * (1.0 - 1.0 / z) for z in poles]) def _causal_init_code(mode): """Code for causal initialization step of IIR filtering. c is a 1d array of length n and z is a filter pole """ code = f''' // causal init for mode={mode}''' if mode == 'mirror': code += ''' z_i = z; z_n_1 = pow(z, (P)(n - 1)); c[0] = c[0] + z_n_1 * c[(n - 1) * element_stride]; for (i = 1; i < min(n - 1, static_cast<idx_t>({n_boundary})); ++i) {{ c[0] += z_i * (c[i * element_stride] + z_n_1 * c[(n - 1 - i) * element_stride]); z_i *= z; }} c[0] /= 1 - z_n_1 * z_n_1;''' elif mode == 'grid-wrap': code += ''' z_i = z; for (i = 1; i < min(n, static_cast<idx_t>({n_boundary})); ++i) {{ c[0] += z_i * c[(n - i) * element_stride]; z_i *= z; }} c[0] /= 1 - z_i; /* z_i = pow(z, n) */''' elif mode == 'reflect': code += ''' z_i = z; z_n = pow(z, (P)n); c0 = c[0]; c[0] = c[0] + z_n * c[(n - 1) * element_stride]; for (i = 1; i < min(n, static_cast<idx_t>({n_boundary})); ++i) {{ c[0] += z_i * (c[i * element_stride] + z_n * c[(n - 1 - i) * element_stride]); z_i *= z; }} c[0] *= z / (1 - z_n * z_n); c[0] += c0;''' else: raise ValueError('invalid mode: {}'.format(mode)) return code def _anticausal_init_code(mode): """Code for the anti-causal initialization step of IIR filtering. c is a 1d array of length n and z is a filter pole """ code = f''' // anti-causal init for mode={mode}''' if mode == 'mirror': code += ''' c[(n - 1) * element_stride] = ( z * c[(n - 2) * element_stride] + c[(n - 1) * element_stride]) * z / (z * z - 1);''' elif mode == 'grid-wrap': code += ''' z_i = z; for (i = 0; i < min(n - 1, static_cast<idx_t>({n_boundary})); ++i) {{ c[(n - 1) * element_stride] += z_i * c[i * element_stride]; z_i *= z; }} c[(n - 1) * element_stride] *= z / (z_i - 1); /* z_i = pow(z, n) */''' elif mode == 'reflect': code += ''' c[(n - 1) * element_stride] *= z / (z - 1);''' else: raise ValueError('invalid mode: {}'.format(mode)) return code def _get_spline_mode(mode): """spline boundary mode for interpolation with order >= 2.""" if mode in ['mirror', 'reflect', 'grid-wrap']: # exact analytic boundary conditions exist for these modes. return mode elif mode == 'grid-mirror': # grid-mirror is a synonym for 'reflect' return 'reflect' # No exact analytical spline boundary condition implemented. Reflect gives # lower error than using mirror or wrap for mode 'nearest'. Otherwise, a # mirror spline boundary condition is used. return 'reflect' if mode == 'nearest' else 'mirror' def _get_spline1d_code(mode, poles, n_boundary): """Generates the code required for IIR filtering of a single 1d signal. Prefiltering is done by causal filtering followed by anti-causal filtering. Multiple boundary conditions have been implemented. """ code = [''' __device__ void spline_prefilter1d( T* __restrict__ c, idx_t signal_length, idx_t element_stride) {{'''] # variables common to all boundary modes code.append(''' idx_t i, n = signal_length; P z, z_i;''') # retrieve the spline boundary extension mode to use mode = _get_spline_mode(mode) if mode == 'mirror': # variables specific to mirror boundary mode code.append(''' P z_n_1;''') elif mode == 'reflect': # variables specific to reflect boundary mode code.append(''' P z_n; T c0;''') for pole in poles: code.append(f''' // select the current pole z = {pole};''') # initialize and apply the causal filter code.append(_causal_init_code(mode)) code.append(''' // apply the causal filter for the current pole for (i = 1; i < n; ++i) {{ c[i * element_stride] += z * c[(i - 1) * element_stride]; }}''') code.append(''' #ifdef __HIP_DEVICE_COMPILE__ __syncthreads(); #endif ''') # initialize and apply the anti-causal filter code.append(_anticausal_init_code(mode)) code.append(''' // apply the anti-causal filter for the current pole for (i = n - 2; i >= 0; --i) {{ c[i * element_stride] = z * (c[(i + 1) * element_stride] - c[i * element_stride]); }}''') code += [''' }}'''] return textwrap.dedent('\n'.join(code)).format(n_boundary=n_boundary) _FILTER_GENERAL = ''' #include "cupy/carray.cuh" #include "cupy/complex.cuh" typedef {data_type} T; typedef {pole_type} P; typedef {index_type} idx_t; template <typename T> __device__ T* row( T* ptr, idx_t i, idx_t axis, idx_t ndim, const idx_t* shape) {{ idx_t index = 0, stride = 1; for (idx_t a = ndim - 1; a > 0; --a) {{ if (a != axis) {{ index += (i % shape[a]) * stride; i /= shape[a]; }} stride *= shape[a]; }} return ptr + index + stride * i; }} ''' _batch_spline1d_strided_template = """ extern "C" __global__ __launch_bounds__({block_size}) void {kernel_name}(T* __restrict__ y, const idx_t* __restrict__ info) {{ const idx_t n_signals = info[0], n_samples = info[1], * __restrict__ shape = info+2; idx_t y_elem_stride = 1; for (int a = {ndim} - 1; a > {axis}; --a) {{ y_elem_stride *= shape[a]; }} idx_t unraveled_idx = blockDim.x * blockIdx.x + threadIdx.x; idx_t batch_idx = unraveled_idx; if (batch_idx < n_signals) {{ T* __restrict__ y_i = row(y, batch_idx, {axis}, {ndim}, shape); spline_prefilter1d(y_i, n_samples, y_elem_stride); }} }} """ @cupy.memoize(for_each_device=True) def get_raw_spline1d_kernel(axis, ndim, mode, order, index_type='int', data_type='double', pole_type='double', block_size=128): """Generate a kernel for applying a spline prefilter along a given axis.""" poles = get_poles(order) # determine number of samples for the boundary approximation # (SciPy uses n_boundary = n_samples but this is excessive) largest_pole = max([abs(p) for p in poles]) # tol < 1e-7 fails test cases comparing to SciPy at atol = rtol = 1e-5 tol = 1e-10 if pole_type == 'float' else 1e-18 n_boundary = math.ceil(math.log(tol, largest_pole)) # headers and general utility function for extracting rows of data code = _FILTER_GENERAL.format(index_type=index_type, data_type=data_type, pole_type=pole_type) # generate source for a 1d function for a given boundary mode and poles code += _get_spline1d_code(mode, poles, n_boundary) # generate code handling batch operation of the 1d filter mode_str = mode.replace('-', '_') # cannot have '-' in kernel name kernel_name = (f'cupyx_scipy_ndimage_spline_filter_{ndim}d_ord{order}_' f'axis{axis}_{mode_str}') code += _batch_spline1d_strided_template.format(ndim=ndim, axis=axis, block_size=block_size, kernel_name=kernel_name) return cupy.RawKernel(code, kernel_name)
mit
281e56d742b6bb2453ea3a74748bf0cf
32.819923
79
0.529852
3.238078
false
false
false
false
cupy/cupy
cupyx/_scatter.py
1
5008
def scatter_add(a, slices, value): """Adds given values to specified elements of an array. It adds ``value`` to the specified elements of ``a``. If all of the indices target different locations, the operation of :func:`scatter_add` is equivalent to ``a[slices] = a[slices] + value``. If there are multiple elements targeting the same location, :func:`scatter_add` uses all of these values for addition. On the other hand, ``a[slices] = a[slices] + value`` only adds the contribution from one of the indices targeting the same location. Note that just like an array indexing, negative indices are interpreted as counting from the end of an array. Also note that :func:`scatter_add` behaves identically to :func:`numpy.add.at`. Example ------- >>> import cupy >>> import cupyx >>> a = cupy.zeros((6,), dtype=cupy.float32) >>> i = cupy.array([1, 0, 1]) >>> v = cupy.array([1., 1., 1.]) >>> cupyx.scatter_add(a, i, v); >>> a array([1., 2., 0., 0., 0., 0.], dtype=float32) Args: a (ndarray): An array that gets added. slices: It is integer, slices, ellipsis, numpy.newaxis, integer array-like, boolean array-like or tuple of them. It works for slices used for :func:`cupy.ndarray.__getitem__` and :func:`cupy.ndarray.__setitem__`. v (array-like): Values to increment ``a`` at referenced locations. .. note:: It only supports types that are supported by CUDA's atomicAdd when an integer array is included in ``slices``. The supported types are ``numpy.float32``, ``numpy.int32``, ``numpy.uint32``, ``numpy.uint64`` and ``numpy.ulonglong``. .. note:: :func:`scatter_add` does not raise an error when indices exceed size of axes. Instead, it wraps indices. .. seealso:: :meth:`numpy.ufunc.at`. """ a.scatter_add(slices, value) def scatter_max(a, slices, value): """Stores a maximum value of elements specified by indices to an array. It stores the maximum value of elements in ``value`` array indexed by ``slices`` to ``a``. If all of the indices target different locations, the operation of :func:`scatter_max` is equivalent to ``a[slices] = cupy.maximum(a[slices], value)``. If there are multiple elements targeting the same location, :func:`scatter_max` stores the maximum of all of these values to the given index of ``a``, the initial element of ``a`` is also taken in account. Note that just like an array indexing, negative indices are interpreted as counting from the end of an array. Also note that :func:`scatter_max` behaves identically to :func:`numpy.maximum.at`. Example ------- >>> import numpy >>> import cupy >>> a = cupy.zeros((6,), dtype=numpy.float32) >>> i = cupy.array([1, 0, 1, 2]) >>> v = cupy.array([1., 2., 3., -1.]) >>> cupyx.scatter_max(a, i, v); >>> a array([2., 3., 0., 0., 0., 0.], dtype=float32) Args: a (ndarray): An array to store the results. slices: It is integer, slices, ellipsis, numpy.newaxis, integer array-like, boolean array-like or tuple of them. It works for slices used for :func:`cupy.ndarray.__getitem__` and :func:`cupy.ndarray.__setitem__`. v (array-like): An array used for reference. """ a.scatter_max(slices, value) def scatter_min(a, slices, value): """Stores a minimum value of elements specified by indices to an array. It stores the minimum value of elements in ``value`` array indexed by ``slices`` to ``a``. If all of the indices target different locations, the operation of :func:`scatter_min` is equivalent to ``a[slices] = cupy.minimum(a[slices], value)``. If there are multiple elements targeting the same location, :func:`scatter_min` stores the minimum of all of these values to the given index of ``a``, the initial element of ``a`` is also taken in account. Note that just like an array indexing, negative indices are interpreted as counting from the end of an array. Also note that :func:`scatter_min` behaves identically to :func:`numpy.minimum.at`. Example ------- >>> import numpy >>> import cupy >>> a = cupy.zeros((6,), dtype=numpy.float32) >>> i = cupy.array([1, 0, 1, 2]) >>> v = cupy.array([1., 2., 3., -1.]) >>> cupyx.scatter_min(a, i, v); >>> a array([ 0., 0., -1., 0., 0., 0.], dtype=float32) Args: a (ndarray): An array to store the results. slices: It is integer, slices, ellipsis, numpy.newaxis, integer array-like, boolean array-like or tuple of them. It works for slices used for :func:`cupy.ndarray.__getitem__` and :func:`cupy.ndarray.__setitem__`. v (array-like): An array used for reference. """ a.scatter_min(slices, value)
mit
e075fe01c5015b8ab3feeedb1c1c5c75
37.229008
79
0.618011
3.834609
false
false
false
false
cupy/cupy
cupy/lib/stride_tricks.py
1
1183
import cupy as _cupy def as_strided(x, shape=None, strides=None): """ Create a view into the array with the given shape and strides. .. warning:: This function has to be used with extreme care, see notes. Parameters ---------- x : ndarray Array to create a new. shape : sequence of int, optional The shape of the new array. Defaults to ``x.shape``. strides : sequence of int, optional The strides of the new array. Defaults to ``x.strides``. Returns ------- view : ndarray See also -------- numpy.lib.stride_tricks.as_strided reshape : reshape an array. Notes ----- ``as_strided`` creates a view into the array given the exact strides and shape. This means it manipulates the internal data structure of ndarray and, if done incorrectly, the array elements can point to invalid memory and can corrupt results or crash your program. """ shape = x.shape if shape is None else tuple(shape) strides = x.strides if strides is None else tuple(strides) return _cupy.ndarray(shape=shape, dtype=x.dtype, memptr=x.data, strides=strides)
mit
72117e8dc906b22dfc1b4d5a50d6ef56
29.333333
75
0.641589
4.255396
false
false
false
false
cupy/cupy
cupy/array_api/_sorting_functions.py
1
1844
# mypy: ignore-errors from __future__ import annotations from ._array_object import Array import cupy as np # Note: the descending keyword argument is new in this function def argsort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`. See its docstring for more information. """ # Note: Unlike in NumPy we only support kind={None, 'stable'}, but the standard # does *not* require we need to support unstable sort. kind = None if not descending: res = np.argsort(x._array, axis=axis, kind=kind) else: # As NumPy has no native descending sort, we imitate it here. Note that # simply flipping the results of np.argsort(x._array, ...) would not # respect the relative order like it would in native descending sorts. res = np.flip( np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind), axis=axis, ) # Rely on flip()/argsort() to validate axis normalised_axis = axis if axis >= 0 else x.ndim + axis max_i = x.shape[normalised_axis] - 1 res = max_i - res return Array._new(res) # Note: the descending keyword argument is new in this function def sort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`. See its docstring for more information. """ # Note: Unlike in NumPy we only support kind={None, 'stable'}, but the standard # does *not* require we need to support unstable sort. kind = None res = np.sort(x._array, axis=axis, kind=kind) if descending: res = np.flip(res, axis=axis) return Array._new(res)
mit
d2d310f8dcc5707eb4beb7f1a246df03
33.792453
83
0.632863
3.725253
false
false
false
false
cupy/cupy
tests/cupy_tests/testing_tests/test_array.py
1
3501
import copy import unittest import numpy import cupy from cupy import testing @testing.parameterize( *testing.product({ 'assertion': ['assert_allclose', 'assert_array_almost_equal', 'assert_array_almost_equal_nulp', 'assert_array_max_ulp', 'assert_array_equal'], 'array_module_x': [numpy, cupy], 'array_module_y': [numpy, cupy] }) ) @testing.gpu class TestEqualityAssertion(unittest.TestCase): def setUp(self): self.assertion = getattr(testing, self.assertion) val = numpy.random.uniform(-1, 1, (2, 3)) self.x = self.array_module_x.array(val, val.dtype, copy=True) self.y = self.array_module_y.array(val, val.dtype, copy=True) def test_equality(self): self.assertion(self.x, self.y) def test_inequality(self): self.y += 1 with self.assertRaises(AssertionError): self.assertion(self.x, self.y) def _convert_array(xs, array_module): if array_module == 'all_numpy': return xs elif array_module == 'all_cupy': return [ cupy.asarray(x) for x in xs ] else: return [ cupy.asarray(x) if numpy.random.randint(0, 2) else x for x in xs ] @testing.parameterize( *testing.product({ 'array_module_x': ['all_numpy', 'all_cupy', 'random'], 'array_module_y': ['all_numpy', 'all_cupy', 'random'] }) ) @testing.gpu class TestListEqualityAssertion(unittest.TestCase): def setUp(self): xs = [numpy.random.uniform(-1, 1, (2, 3)) for _ in range(10)] ys = copy.deepcopy(xs) self.xs = _convert_array(xs, self.array_module_x) self.ys = _convert_array(ys, self.array_module_y) def test_equality_numpy(self): testing.assert_array_list_equal(self.xs, self.ys) def test_inequality_numpy(self): self.xs[0] += 1 with self.assertRaisesRegex( AssertionError, '^\nArrays are not equal'): testing.assert_array_list_equal(self.xs, self.ys) @testing.parameterize( *testing.product({ 'array_module_x': [numpy, cupy], 'array_module_y': [numpy, cupy] }) ) @testing.gpu class TestStridesEqualityAssertion(unittest.TestCase): def setUp(self): val = numpy.random.uniform(-1, 1, (2, 3)) self.x = self.array_module_x.array(val, val.dtype, copy=True) self.y = self.array_module_y.array(val, val.dtype, copy=True) def test_equality_numpy(self): testing.assert_array_equal(self.x, self.y, strides_check=True) def test_inequality_numpy(self): self.y = self.array_module_y.asfortranarray(self.y) with self.assertRaises(AssertionError): testing.assert_array_equal(self.x, self.y, strides_check=True) @testing.parameterize( *testing.product({ 'array_module_x': [numpy, cupy], 'array_module_y': [numpy, cupy] }) ) @testing.gpu class TestLessAssertion(unittest.TestCase): def setUp(self): val = numpy.random.uniform(-1, 1, (2, 3)) self.x = self.array_module_x.array(val, val.dtype, copy=True) self.y = self.array_module_y.array(val + 1, val.dtype, copy=True) def test_equality_numpy(self): testing.assert_array_less(self.x, self.y) def test_inequality_numpy(self): self.x[0] += 100 with self.assertRaises(AssertionError): testing.assert_array_less(self.x, self.y)
mit
badd7b1ce19423c1b6fa4dc9db52485c
28.175
74
0.607541
3.315341
false
true
false
false
cupy/cupy
cupy/lib/_routines_poly.py
1
12381
import functools import warnings import numpy import cupy import cupyx.scipy.fft def _wraps_polyroutine(func): def _get_coeffs(x): if isinstance(x, cupy.poly1d): return x._coeffs if cupy.isscalar(x): return cupy.atleast_1d(x) if isinstance(x, cupy.ndarray): x = cupy.atleast_1d(x) if x.ndim == 1: return x raise ValueError('Multidimensional inputs are not supported') raise TypeError('Unsupported type') def wrapper(*args): coeffs = [_get_coeffs(x) for x in args] out = func(*coeffs) if all(not isinstance(x, cupy.poly1d) for x in args): return out if isinstance(out, cupy.ndarray): return cupy.poly1d(out) if isinstance(out, tuple): return tuple([cupy.poly1d(x) for x in out]) assert False # Never reach return functools.update_wrapper(wrapper, func) def poly(seq_of_zeros): """Computes the coefficients of a polynomial with the given roots sequence. Args: seq_of_zeros (cupy.ndarray): a sequence of polynomial roots. Returns: cupy.ndarray: polynomial coefficients from highest to lowest degree. .. warning:: This function doesn't support general 2d square arrays currently. Only complex Hermitian and real symmetric 2d arrays are allowed. .. seealso:: :func:`numpy.poly` """ x = seq_of_zeros if x.ndim == 2 and x.shape[0] == x.shape[1] and x.shape[0] != 0: if cupy.array_equal(x, x.conj().T): x = cupy.linalg.eigvalsh(x) else: raise NotImplementedError('Only complex Hermitian and real ' 'symmetric 2d arrays are supported ' 'currently') elif x.ndim == 1: x = x.astype(cupy.mintypecode(x.dtype.char), copy=False) else: raise ValueError('Input must be 1d or non-empty square 2d array.') if x.size == 0: return 1.0 size = 2 ** (x.size - 1).bit_length() a = cupy.zeros((size, 2), x.dtype) a[:, 0].fill(1) cupy.negative(x, out=a[:x.size, 1]) while size > 1: size = size // 2 a = cupy._math.misc._fft_convolve(a[:size], a[size:], 'full') return a[0, :x.size + 1] @_wraps_polyroutine def polyadd(a1, a2): """Computes the sum of two polynomials. Args: a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial. a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial. Returns: cupy.ndarray or cupy.poly1d: The sum of the inputs. .. seealso:: :func:`numpy.polyadd` """ if a1.size < a2.size: a1, a2 = a2, a1 out = cupy.pad(a2, (a1.size - a2.size, 0)) out = out.astype(cupy.result_type(a1, a2), copy=False) out += a1 return out @_wraps_polyroutine def polysub(a1, a2): """Computes the difference of two polynomials. Args: a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial. a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial. Returns: cupy.ndarray or cupy.poly1d: The difference of the inputs. .. seealso:: :func:`numpy.polysub` """ if a1.shape[0] <= a2.shape[0]: out = cupy.pad(a1, (a2.shape[0] - a1.shape[0], 0)) out = out.astype(cupy.result_type(a1, a2), copy=False) out -= a2 else: out = cupy.pad(a2, (a1.shape[0] - a2.shape[0], 0)) out = out.astype(cupy.result_type(a1, a2), copy=False) out -= 2 * out - a1 return out @_wraps_polyroutine def polymul(a1, a2): """Computes the product of two polynomials. Args: a1 (scalar, cupy.ndarray or cupy.poly1d): first input polynomial. a2 (scalar, cupy.ndarray or cupy.poly1d): second input polynomial. Returns: cupy.ndarray or cupy.poly1d: The product of the inputs. .. seealso:: :func:`numpy.polymul` """ a1 = cupy.trim_zeros(a1, trim='f') a2 = cupy.trim_zeros(a2, trim='f') if a1.size == 0: a1 = cupy.array([0.], a1.dtype) if a2.size == 0: a2 = cupy.array([0.], a2.dtype) return cupy.convolve(a1, a2) def _polypow_direct(x, n): if n == 0: return 1 if n == 1: return x if n % 2 == 0: return _polypow(cupy.convolve(x, x), n // 2) return cupy.convolve(x, _polypow(cupy.convolve(x, x), (n - 1) // 2)) def _polypow(x, n): if n == 0: return 1 if n == 1: return x method = cupy._math.misc._choose_conv_method(x, x, 'full') if method == 'direct': return _polypow_direct(x, n) elif method == 'fft': if x.dtype.kind == 'c': fft, ifft = cupy.fft.fft, cupy.fft.ifft else: fft, ifft = cupy.fft.rfft, cupy.fft.irfft out_size = (x.size - 1) * n + 1 size = cupyx.scipy.fft.next_fast_len(out_size) fx = fft(x, size) fy = cupy.power(fx, n, fx) y = ifft(fy, size) return y[:out_size] else: assert False def _polyfit_typecast(x): if x.dtype.kind == 'c': return x.astype(numpy.complex128, copy=False) return x.astype(numpy.float64, copy=False) def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): """Returns the least squares fit of polynomial of degree deg to the data y sampled at x. Args: x (cupy.ndarray): x-coordinates of the sample points of shape (M,). y (cupy.ndarray): y-coordinates of the sample points of shape (M,) or (M, K). deg (int): degree of the fitting polynomial. rcond (float, optional): relative condition number of the fit. The default value is ``len(x) * eps``. full (bool, optional): indicator of the return value nature. When False (default), only the coefficients are returned. When True, diagnostic information is also returned. w (cupy.ndarray, optional): weights applied to the y-coordinates of the sample points of shape (M,). cov (bool or str, optional): if given, returns the coefficients along with the covariance matrix. Returns: cupy.ndarray or tuple: p (cupy.ndarray of shape (deg + 1,) or (deg + 1, K)): Polynomial coefficients from highest to lowest degree residuals, rank, singular_values, rcond \ (cupy.ndarray, int, cupy.ndarray, float): Present only if ``full=True``. Sum of squared residuals of the least-squares fit, rank of the scaled Vandermonde coefficient matrix, its singular values, and the specified value of ``rcond``. V (cupy.ndarray of shape (M, M) or (M, M, K)): Present only if ``full=False`` and ``cov=True``. The covariance matrix of the polynomial coefficient estimates. .. warning:: numpy.RankWarning: The rank of the coefficient matrix in the least-squares fit is deficient. It is raised if ``full=False``. .. seealso:: :func:`numpy.polyfit` """ if x.dtype.char == 'e' and y.dtype.kind == 'b': raise NotImplementedError('float16 x and bool y are not' ' currently supported') if y.dtype == numpy.float16: raise TypeError('float16 y are not supported') x = _polyfit_typecast(x) y = _polyfit_typecast(y) deg = int(deg) if deg < 0: raise ValueError('expected deg >= 0') if x.ndim != 1: raise TypeError('expected 1D vector for x') if x.size == 0: raise TypeError('expected non-empty vector for x') if y.ndim < 1 or y.ndim > 2: raise TypeError('expected 1D or 2D array for y') if x.size != y.shape[0]: raise TypeError('expected x and y to have same length') lhs = cupy.polynomial.polynomial.polyvander(x, deg)[:, ::-1] rhs = y if w is not None: w = _polyfit_typecast(w) if w.ndim != 1: raise TypeError('expected a 1-d array for weights') if w.size != x.size: raise TypeError('expected w and y to have the same length') lhs *= w[:, None] if rhs.ndim == 2: w = w[:, None] rhs *= w if rcond is None: rcond = x.size * cupy.finfo(x.dtype).eps scale = cupy.sqrt((cupy.square(lhs)).sum(axis=0)) lhs /= scale c, resids, rank, s = cupy.linalg.lstsq(lhs, rhs, rcond) if y.ndim > 1: scale = scale.reshape(-1, 1) c /= scale order = deg + 1 if rank != order and not full: msg = 'Polyfit may be poorly conditioned' warnings.warn(msg, numpy.RankWarning, stacklevel=4) if full: if resids.dtype.kind == 'c': resids = cupy.absolute(resids) return c, resids, rank, s, rcond if cov: base = cupy.linalg.inv(cupy.dot(lhs.T, lhs)) base /= cupy.outer(scale, scale) if cov == 'unscaled': factor = 1 elif x.size > order: factor = resids / (x.size - order) else: raise ValueError('the number of data points must exceed order' ' to scale the covariance matrix') if y.ndim != 1: base = base[..., None] return c, base * factor return c def polyval(p, x): """Evaluates a polynomial at specific values. Args: p (cupy.ndarray or cupy.poly1d): input polynomial. x (scalar, cupy.ndarray): values at which the polynomial is evaluated. Returns: cupy.ndarray or cupy.poly1d: polynomial evaluated at x. .. warning:: This function doesn't currently support poly1d values to evaluate. .. seealso:: :func:`numpy.polyval` """ if isinstance(p, cupy.poly1d): p = p.coeffs if not isinstance(p, cupy.ndarray) or p.ndim == 0: raise TypeError('p must be 1d ndarray or poly1d object') if p.ndim > 1: raise ValueError('p must be 1d array') if isinstance(x, cupy.poly1d): # TODO(asi1024): Needs performance improvement. dtype = numpy.result_type(x.coeffs, 1) res = cupy.poly1d(cupy.array([0], dtype=dtype)) prod = cupy.poly1d(cupy.array([1], dtype=dtype)) for c in p[::-1]: res = res + prod * c prod = prod * x return res dtype = numpy.result_type(p.dtype.type(0), x) p = p.astype(dtype, copy=False) if p.size == 0: return cupy.zeros(x.shape, dtype) if dtype == numpy.bool_: return p.any() * x + p[-1] if not cupy.isscalar(x): x = cupy.asarray(x, dtype=dtype)[..., None] x = x ** cupy.arange(p.size, dtype=dtype) return (p[::-1] * x).sum(axis=-1, dtype=dtype) def roots(p): """Computes the roots of a polynomial with given coefficients. Args: p (cupy.ndarray or cupy.poly1d): polynomial coefficients. Returns: cupy.ndarray: polynomial roots. .. warning:: This function doesn't support currently polynomial coefficients whose companion matrices are general 2d square arrays. Only those with complex Hermitian or real symmetric 2d arrays are allowed. The current `cupy.roots` doesn't guarantee the order of results. .. seealso:: :func:`numpy.roots` """ if isinstance(p, cupy.poly1d): p = p.coeffs if p.dtype.kind == 'b': raise NotImplementedError('boolean inputs are not supported') if p.ndim == 0: raise TypeError('0-dimensional input is not allowed') if p.size < 2: return cupy.array([]) [p] = cupy.polynomial.polyutils.as_series([p[::-1]]) if p.size < 2: return cupy.array([]) if p.size == 2: out = (-p[0] / p[1])[None] if p[0] == 0: out = out.real.astype(numpy.float64) return out cmatrix = cupy.polynomial.polynomial.polycompanion(p) # TODO(Dahlia-Chehata): Support after cupy.linalg.eigvals is supported if cupy.array_equal(cmatrix, cmatrix.conj().T): out = cupy.linalg.eigvalsh(cmatrix) else: raise NotImplementedError('Only complex Hermitian and real ' 'symmetric 2d arrays are supported ' 'currently') return out.astype(p.dtype)
mit
5e03d02d2acbae18dfbea4c0bb007a2d
30.265152
79
0.579679
3.492525
false
false
false
false
cupy/cupy
tests/cupy_tests/linalg_tests/test_einsum.py
1
19857
import warnings import numpy import pytest import cupy from cupy import testing rng = numpy.random.default_rng(seed=0) def _dec_shape(shape, dec): # Test smaller shape return tuple(1 if s == 1 else max(0, s - dec) for s in shape) def _rand1_shape(shape, prob): # Test broadcast # If diagonals are "broadcasted" we can simply: # return tuple(1 if rng.uniform() < prob else s for s in shape) table = {} new_shape = [] for s in shape: if s not in table: table[s] = 1 if rng.uniform() < prob else s new_shape.append(table[s]) return tuple(new_shape) def augment_einsum_testcases(*params): """Modify shapes in einsum tests Shape parameter should be starts with 'shape_'. The original parameter is stored as '_raw_params'. Args: params (sequence of dicts) Yields: dict: parameter with modified shapes. """ for dec in range(3): for drop in [False, True]: for param in params: param_new = param.copy() for k in param.keys(): if k.startswith('shape_'): new_shape = _dec_shape(param[k], dec) if drop: prob = rng.uniform() new_shape = _rand1_shape(new_shape, prob) param_new[k] = new_shape param_new['_raw_params'] = { 'orig': param, 'dec': dec, 'drop': drop, } yield param_new class TestEinSumError: def test_irregular_ellipsis1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('..', xp.zeros((2, 2, 2))) def test_irregular_ellipsis2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('...i...', xp.zeros((2, 2, 2))) def test_irregular_ellipsis3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i...->...i...', xp.zeros((2, 2, 2))) def test_irregular_ellipsis4(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('...->', xp.zeros((2, 2, 2))) def test_no_arguments(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum() def test_one_argument(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('') def test_not_string_subject(self): for xp in (numpy, cupy): with pytest.raises(TypeError): xp.einsum(0, 0) def test_bad_argument(self): for xp in (numpy, cupy): with pytest.raises(TypeError): xp.einsum('', 0, bad_arg=0) def test_too_many_operands1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('', 0, 0) def test_too_many_operands2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum( 'i,j', xp.array([0, 0]), xp.array([0, 0]), xp.array([0, 0])) def test_too_few_operands1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(',', 0) def test_too_many_dimension1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i', 0) def test_too_many_dimension2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ij', xp.array([0, 0])) def test_too_many_dimension3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ijk...->...', xp.arange(6).reshape(2, 3)) def test_too_few_dimension(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i->i', xp.arange(6).reshape(2, 3)) def test_invalid_char1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i%', xp.array([0, 0])) def test_invalid_char2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('j$', xp.array([0, 0])) def test_invalid_char3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i->&', xp.array([0, 0])) # output subscripts must appear in inumpy.t def test_invalid_output_subscripts1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i->ij', xp.array([0, 0])) # output subscripts may only be specified once def test_invalid_output_subscripts2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ij->jij', xp.array([[0, 0], [0, 0]])) # output subscripts must not incrudes comma def test_invalid_output_subscripts3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ij->i,j', xp.array([[0, 0], [0, 0]])) # dimensions much match when being collapsed def test_invalid_diagonal1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ii', xp.arange(6).reshape(2, 3)) def test_invalid_diagonal2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ii->', xp.arange(6).reshape(2, 3)) def test_invalid_diagonal3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('ii', xp.arange(3).reshape(1, 3)) def test_dim_mismatch_char1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i,i', xp.arange(2), xp.arange(3)) def test_dim_mismatch_ellipsis1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('...,...', xp.arange(2), xp.arange(3)) def test_dim_mismatch_ellipsis2(self): for xp in (numpy, cupy): a = xp.arange(12).reshape(2, 3, 2) with pytest.raises(ValueError): xp.einsum('i...,...i', a, a) def test_dim_mismatch_ellipsis3(self): for xp in (numpy, cupy): a = xp.arange(12).reshape(2, 3, 2) with pytest.raises(ValueError): xp.einsum('...,...', a, a[:, :2]) # invalid -> operator def test_invalid_arrow1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i-i', xp.array([0, 0])) def test_invalid_arrow2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i>i', xp.array([0, 0])) def test_invalid_arrow3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i->->i', xp.array([0, 0])) def test_invalid_arrow4(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum('i-', xp.array([0, 0])) class TestListArgEinSumError: @testing.with_requires('numpy>=1.19') def test_invalid_sub1(self): for xp in (numpy, cupy): with pytest.raises(TypeError): xp.einsum(xp.arange(2), [None]) def test_invalid_sub2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(2), [0], [1]) def test_invalid_sub3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(2), [Ellipsis, 0, Ellipsis]) def test_dim_mismatch1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(2), [0], xp.arange(3), [0]) def test_dim_mismatch2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(2), [0], xp.arange(3), [0], [0]) def test_dim_mismatch3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(6).reshape(2, 3), [0, 0]) def test_too_many_dims1(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(3, [0]) def test_too_many_dims2(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(2), [0, 1]) def test_too_many_dims3(self): for xp in (numpy, cupy): with pytest.raises(ValueError): xp.einsum(xp.arange(6).reshape(2, 3), [Ellipsis, 0, 1, 2]) @pytest.mark.parametrize('do_opt', [False, True]) class TestListArgEinSum: # numpy/numpy#15961: should accept int64 type in subscript list @testing.with_requires('numpy>=1.19') @testing.numpy_cupy_allclose() def test_numpy_15961_array(self, xp, do_opt): n = 3 a = testing.shaped_arange((n, n), xp) sub = numpy.array([0, 0]) return xp.einsum(a, sub, optimize=do_opt) @testing.with_requires('numpy>=1.19') @testing.numpy_cupy_allclose() def test_numpy_15961_list(self, xp, do_opt): n = 3 a = testing.shaped_arange((n, n), xp) sub = list(numpy.array([0, 0])) return xp.einsum(a, sub, optimize=do_opt) @testing.parameterize(*augment_einsum_testcases( {'shape_a': (2, 3), 'subscripts': 'ij'}, # do nothing {'shape_a': (2, 3), 'subscripts': '...'}, # do nothing {'shape_a': (2, 3), 'subscripts': 'ji'}, # transpose {'shape_a': (3, 3), 'subscripts': 'ii->i'}, # diagonal 2d {'shape_a': (3, 3, 3), 'subscripts': 'jii->ij'}, # partial diagonal 3d {'shape_a': (3, 3, 3), 'subscripts': 'iji->ij'}, # partial diagonal 3d {'shape_a': (3, 3, 3), 'subscripts': '...ii->...i'}, # partial diagonal 3d {'shape_a': (3, 3, 3), 'subscripts': 'iii->i'}, # diagonal 3d {'shape_a': (2, 3, 4), 'subscripts': 'ijk->jik'}, # swap axes {'shape_a': (2, 3, 4), 'subscripts': 'ijk->kij'}, # swap axes {'shape_a': (2, 3, 4), 'subscripts': 'ijk->ikj'}, # swap axes {'shape_a': (2, 3, 4), 'subscripts': 'kji->ikj'}, # swap axes {'shape_a': (2, 3, 4), 'subscripts': 'j...i->i...j'}, # swap axes {'shape_a': (3,), 'subscripts': 'i->'}, # sum {'shape_a': (3, 3), 'subscripts': 'ii'}, # trace {'shape_a': (2, 2, 2, 2), 'subscripts': 'ijkj->kij'}, {'shape_a': (2, 2, 2, 2), 'subscripts': 'ijij->ij'}, {'shape_a': (2, 2, 2, 2), 'subscripts': 'jiji->ij'}, {'shape_a': (2, 2, 2, 2), 'subscripts': 'ii...->...'}, # trace {'shape_a': (2, 2, 2, 2), 'subscripts': 'i...i->...'}, # trace {'shape_a': (2, 2, 2, 2), 'subscripts': '...ii->...'}, # trace {'shape_a': (2, 2, 2, 2), 'subscripts': 'j...i->...'}, # sum {'shape_a': (2, 3), 'subscripts': 'ij->ij...'}, # do nothing {'shape_a': (2, 3), 'subscripts': 'ij->i...j'}, # do nothing {'shape_a': (2, 3), 'subscripts': 'ij->...ij'}, # do nothing {'shape_a': (2, 3), 'subscripts': 'ij...->ij'}, # do nothing {'shape_a': (2, 3), 'subscripts': 'i...j->ij'}, # do nothing {'shape_a': (), 'subscripts': ''}, # do nothing {'shape_a': (), 'subscripts': '->'}, # do nothing )) class TestEinSumUnaryOperation: @testing.for_all_dtypes(no_bool=False) @testing.numpy_cupy_allclose(contiguous_check=False) def test_einsum_unary(self, xp, dtype): a = testing.shaped_arange(self.shape_a, xp, dtype) out = xp.einsum(self.subscripts, a) if xp is not numpy: optimized_out = xp.einsum(self.subscripts, a, optimize=True) testing.assert_allclose(optimized_out, out) return out @testing.for_all_dtypes(no_bool=False) @testing.numpy_cupy_equal() def test_einsum_unary_views(self, xp, dtype): a = testing.shaped_arange(self.shape_a, xp, dtype) b = xp.einsum(self.subscripts, a) return b.ndim == 0 or b.base is a @testing.for_all_dtypes_combination( ['dtype_a', 'dtype_out'], no_bool=False, no_complex=True) # avoid ComplexWarning @testing.numpy_cupy_allclose(contiguous_check=False) def test_einsum_unary_dtype(self, xp, dtype_a, dtype_out): if not numpy.can_cast(dtype_a, dtype_out): pytest.skip() a = testing.shaped_arange(self.shape_a, xp, dtype_a) return xp.einsum(self.subscripts, a, dtype=dtype_out) class TestEinSumUnaryOperationWithScalar: @testing.for_all_dtypes() @testing.numpy_cupy_allclose() def test_scalar_int(self, xp, dtype): return xp.asarray(xp.einsum('->', 2, dtype=dtype)) @testing.for_all_dtypes() @testing.numpy_cupy_allclose() def test_scalar_float(self, xp, dtype): return xp.asarray(xp.einsum('', 2.0, dtype=dtype)) @testing.parameterize(*augment_einsum_testcases( # dot vecvec {'shape_a': (3,), 'shape_b': (3,), 'subscripts': 'i,i'}, # outer {'shape_a': (2,), 'shape_b': (3,), 'subscripts': 'i,j'}, # dot matvec {'shape_a': (2, 3), 'shape_b': (3,), 'subscripts': 'ij,j'}, {'shape_a': (2, 3), 'shape_b': (2,), 'subscripts': 'ij,i'}, # dot matmat {'shape_a': (2, 3), 'shape_b': (3, 4), 'subscripts': 'ij,jk'}, # tensordot {'shape_a': (3, 4, 2), 'shape_b': (4, 3, 2), 'subscripts': 'ijk, jil -> kl'}, {'shape_a': (3, 4, 2), 'shape_b': (4, 2, 3), 'subscripts': 'i...,...k->ki...'}, {'shape_a': (3, 4, 2), 'shape_b': (4, 3, 2), 'subscripts': 'ij...,ji...->i...'}, # trace and tensordot and diagonal {'shape_a': (2, 3, 2, 4), 'shape_b': (3, 2, 2), 'subscripts': 'ijil,jkk->kj'}, {'shape_a': (2, 4, 2, 3), 'shape_b': (3, 2, 4), 'subscripts': 'i...ij,ji...->...j'}, # broadcast {'shape_a': (2, 3, 4), 'shape_b': (3,), 'subscripts': 'ij...,j...->ij...'}, {'shape_a': (2, 3, 4), 'shape_b': (3,), 'subscripts': 'ij...,...j->ij...'}, {'shape_a': (2, 3, 4), 'shape_b': (3,), 'subscripts': 'ij...,j->ij...'}, {'shape_a': (4, 3), 'shape_b': (3, 2), 'subscripts': 'ik...,k...->i...'}, {'shape_a': (4, 3), 'shape_b': (3, 2), 'subscripts': 'ik...,...kj->i...j'}, {'shape_a': (4, 3), 'shape_b': (3, 2), 'subscripts': '...k,kj'}, {'shape_a': (4, 3), 'shape_b': (3, 2), 'subscripts': 'ik,k...->i...'}, {'shape_a': (2, 3, 4, 5), 'shape_b': (4,), 'subscripts': 'ijkl,k'}, {'shape_a': (2, 3, 4, 5), 'shape_b': (4,), 'subscripts': '...kl,k'}, {'shape_a': (2, 3, 4, 5), 'shape_b': (4,), 'subscripts': '...kl,k...'}, {'shape_a': (1, 1, 1, 2, 3, 2), 'shape_b': (2, 3, 2, 2), 'subscripts': '...lmn,lmno->...o'}, )) class TestEinSumBinaryOperation: @testing.for_all_dtypes_combination( ['dtype_a', 'dtype_b'], no_bool=False, no_float16=False) @testing.numpy_cupy_allclose(contiguous_check=False) def test_einsum_binary(self, xp, dtype_a, dtype_b): a = testing.shaped_arange(self.shape_a, xp, dtype_a) b = testing.shaped_arange(self.shape_b, xp, dtype_b) return xp.einsum(self.subscripts, a, b) class TestEinSumBinaryOperationWithScalar: @testing.for_all_dtypes() @testing.numpy_cupy_allclose(contiguous_check=False) def test_scalar_1(self, xp, dtype): shape_a = (2,) a = testing.shaped_arange(shape_a, xp, dtype) return xp.asarray(xp.einsum(',i->', 3, a)) @testing.for_all_dtypes() @testing.numpy_cupy_allclose(contiguous_check=False) def test_scalar_2(self, xp, dtype): shape_a = (2,) a = testing.shaped_arange(shape_a, xp, dtype) return xp.asarray(xp.einsum('i,->', a, 4)) @testing.parameterize(*augment_einsum_testcases( {'shape_a': (2, 3), 'shape_b': (3, 4), 'shape_c': (4, 5), 'subscripts': 'ij,jk,kl'}, {'shape_a': (2, 4), 'shape_b': (2, 3), 'shape_c': (2,), 'subscripts': 'ij,ik,i->ijk'}, {'shape_a': (2, 4), 'shape_b': (3, 2), 'shape_c': (2,), 'subscripts': 'ij,ki,i->jk'}, {'shape_a': (2, 3, 4), 'shape_b': (2,), 'shape_c': (3, 4, 2), 'subscripts': 'i...,i,...i->...i'}, {'shape_a': (2, 3, 4), 'shape_b': (4, 3), 'shape_c': (3, 3, 4), 'subscripts': 'a...,...b,c...->abc...'}, {'shape_a': (2, 3, 4), 'shape_b': (3, 4), 'shape_c': (3, 3, 4), 'subscripts': 'a...,...,c...->ac...'}, {'shape_a': (3, 3, 4), 'shape_b': (4, 3), 'shape_c': (2, 3, 4), 'subscripts': 'a...,...b,c...->abc...'}, {'shape_a': (3, 3, 4), 'shape_b': (3, 4), 'shape_c': (2, 3, 4), 'subscripts': 'a...,...,c...->ac...'}, )) class TestEinSumTernaryOperation: @testing.for_all_dtypes_combination( ['dtype_a', 'dtype_b', 'dtype_c'], no_bool=False, no_float16=False) @testing.numpy_cupy_allclose(contiguous_check=False) def test_einsum_ternary(self, xp, dtype_a, dtype_b, dtype_c): a = testing.shaped_arange(self.shape_a, xp, dtype_a) b = testing.shaped_arange(self.shape_b, xp, dtype_b) c = testing.shaped_arange(self.shape_c, xp, dtype_c) try: out = xp.einsum(self.subscripts, a, b, c, optimize=False) except TypeError: assert xp is numpy out = xp.einsum(self.subscripts, a, b, c) if xp is not numpy: # Avoid numpy issues #11059, #11060 for optimize in [ True, # 'greedy' 'optimal', ['einsum_path', (0, 1), (0, 1)], ['einsum_path', (0, 2), (0, 1)], ['einsum_path', (1, 2), (0, 1)], ]: optimized_out = xp.einsum( self.subscripts, a, b, c, optimize=optimize) testing.assert_allclose(optimized_out, out) return out @testing.parameterize(*([ # memory constraint {'subscript': 'a,b,c->abc', 'opt': ('greedy', 0)}, {'subscript': 'acdf,jbje,gihb,hfac', 'opt': ('greedy', 0)}, ] + testing.product({'subscript': [ # long paths 'acdf,jbje,gihb,hfac,gfac,gifabc,hfac', 'chd,bde,agbc,hiad,bdi,cgh,agdb', # edge cases 'eb,cb,fb->cef', 'dd,fb,be,cdb->cef', 'bca,cdb,dbf,afc->', 'dcc,fce,ea,dbf->ab', 'a,ac,ab,ad,cd,bd,bc->', ], 'opt': ['greedy', 'optimal'], }))) class TestEinSumLarge: chars = 'abcdefghij' sizes = (2, 3, 4, 5, 4, 3, 2, 6, 5, 4, 3) size_dict = {} for size, char in zip(sizes, chars): size_dict[char] = size @pytest.fixture() def shapes(self): size_dict = self.size_dict terms = self.subscript.split('->')[0].split(',') return tuple([ tuple([size_dict[x] for x in term]) for term in terms ]) @testing.numpy_cupy_allclose(contiguous_check=False) def test_einsum(self, xp, shapes): arrays = [ testing.shaped_random(shape, xp, float, scale=1) for shape in shapes ] # TODO(kataoka): support memory efficient cupy.einsum with warnings.catch_warnings(record=True) as ws: # I hope there's no problem with np.einsum for these cases... out = xp.einsum(self.subscript, *arrays, optimize=self.opt) if xp is not numpy and \ isinstance(self.opt, tuple): # with memory limit for w in ws: assert 'memory' in str(w.message) else: assert len(ws) == 0 return out
mit
ba52b4468e50397e3f4e94bdde4d7619
34.458929
79
0.522687
3.154909
false
true
false
false
marshmallow-code/marshmallow
src/marshmallow/fields.py
1
73412
"""Field classes for various types of data.""" from __future__ import annotations import collections import copy import datetime as dt import numbers import uuid import ipaddress import decimal import math import typing import warnings from enum import Enum as EnumType from collections.abc import Mapping as _Mapping from marshmallow import validate, utils, class_registry, types from marshmallow.base import FieldABC, SchemaABC from marshmallow.utils import ( is_collection, missing as missing_, resolve_field_instance, is_aware, ) from marshmallow.exceptions import ( ValidationError, StringNotCollectionError, FieldInstanceResolutionError, ) from marshmallow.validate import And, Length from marshmallow.warnings import RemovedInMarshmallow4Warning __all__ = [ "Field", "Raw", "Nested", "Mapping", "Dict", "List", "Tuple", "String", "UUID", "Number", "Integer", "Decimal", "Boolean", "Float", "DateTime", "NaiveDateTime", "AwareDateTime", "Time", "Date", "TimeDelta", "Url", "URL", "Email", "IP", "IPv4", "IPv6", "IPInterface", "IPv4Interface", "IPv6Interface", "Enum", "Method", "Function", "Str", "Bool", "Int", "Constant", "Pluck", ] _T = typing.TypeVar("_T") class Field(FieldABC): """Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned. :param dump_default: If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable. :param load_default: Default deserialization value for the field if the field is not found in the input data. May be a value or a callable. :param data_key: The name of the dict key in the external representation, i.e. the input of `load` and the output of `dump`. If `None`, the key will match the name of the field. :param attribute: The name of the attribute to get the value from when serializing. If `None`, assumes the attribute has the same name as the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use ``data_key`` instead. :param validate: Validator or collection of validators that are called during deserialization. Validator takes a field's input value as its only parameter and returns a boolean. If it returns `False`, an :exc:`ValidationError` is raised. :param required: Raise a :exc:`ValidationError` if the field value is not supplied during deserialization. :param allow_none: Set this to `True` if `None` should be considered a valid value during validation/deserialization. If ``load_default=None`` and ``allow_none`` is unset, will default to ``True``. Otherwise, the default is ``False``. :param load_only: If `True` skip this field during serialization, otherwise its value will be present in the serialized data. :param dump_only: If `True` skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as "read-only". :param dict error_messages: Overrides for `Field.default_error_messages`. :param metadata: Extra information to be stored as field metadata. .. versionchanged:: 2.0.0 Removed `error` parameter. Use ``error_messages`` instead. .. versionchanged:: 2.0.0 Added `allow_none` parameter, which makes validation/deserialization of `None` consistent across fields. .. versionchanged:: 2.0.0 Added `load_only` and `dump_only` parameters, which allow field skipping during the (de)serialization process. .. versionchanged:: 2.0.0 Added `missing` parameter, which indicates the value for a field if the field is not found during deserialization. .. versionchanged:: 2.0.0 ``default`` value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output. .. versionchanged:: 3.0.0b8 Add ``data_key`` parameter for the specifying the key in the input and output data. This parameter replaced both ``load_from`` and ``dump_to``. """ # Some fields, such as Method fields and Function fields, are not expected # to exist as attributes on the objects to serialize. Set this to False # for those fields _CHECK_ATTRIBUTE = True _creation_index = 0 # Used for sorting #: Default error messages for various kinds of errors. The keys in this dictionary #: are passed to `Field.make_error`. The values are error messages passed to #: :exc:`marshmallow.exceptions.ValidationError`. default_error_messages = { "required": "Missing data for required field.", "null": "Field may not be null.", "validator_failed": "Invalid value.", } def __init__( self, *, load_default: typing.Any = missing_, missing: typing.Any = missing_, dump_default: typing.Any = missing_, default: typing.Any = missing_, data_key: str | None = None, attribute: str | None = None, validate: None | ( typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]] ) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata, ) -> None: # handle deprecated `default` and `missing` parameters if default is not missing_: warnings.warn( "The 'default' argument to fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) if dump_default is missing_: dump_default = default if missing is not missing_: warnings.warn( "The 'missing' argument to fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) if load_default is missing_: load_default = missing self.dump_default = dump_default self.load_default = load_default self.attribute = attribute self.data_key = data_key self.validate = validate if validate is None: self.validators = [] elif callable(validate): self.validators = [validate] elif utils.is_iterable_but_not_string(validate): self.validators = list(validate) else: raise ValueError( "The 'validate' parameter must be a callable " "or a collection of callables." ) # If allow_none is None and load_default is None # None should be considered valid by default self.allow_none = load_default is None if allow_none is None else allow_none self.load_only = load_only self.dump_only = dump_only if required is True and load_default is not missing_: raise ValueError("'load_default' must not be set for required fields.") self.required = required metadata = metadata or {} self.metadata = {**metadata, **additional_metadata} if additional_metadata: warnings.warn( "Passing field metadata as keyword arguments is deprecated. Use the " "explicit `metadata=...` argument instead. " f"Additional metadata: {additional_metadata}", RemovedInMarshmallow4Warning, stacklevel=2, ) self._creation_index = Field._creation_index Field._creation_index += 1 # Collect default error message from self and parent classes messages = {} # type: dict[str, str] for cls in reversed(self.__class__.__mro__): messages.update(getattr(cls, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages def __repr__(self) -> str: return ( "<fields.{ClassName}(dump_default={self.dump_default!r}, " "attribute={self.attribute!r}, " "validate={self.validate}, required={self.required}, " "load_only={self.load_only}, dump_only={self.dump_only}, " "load_default={self.load_default}, allow_none={self.allow_none}, " "error_messages={self.error_messages})>".format( ClassName=self.__class__.__name__, self=self ) ) def __deepcopy__(self, memo): return copy.copy(self) def get_value(self, obj, attr, accessor=None, default=missing_): """Return the value for a given key from an object. :param object obj: The object to get the value from. :param str attr: The attribute/key in `obj` to get the value from. :param callable accessor: A callable used to retrieve the value of `attr` from the object `obj`. Defaults to `marshmallow.utils.get_value`. """ accessor_func = accessor or utils.get_value check_key = attr if self.attribute is None else self.attribute return accessor_func(obj, check_key, default) def _validate(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ self._validate_all(value) @property def _validate_all(self): return And(*self.validators, error=self.error_messages["validator_failed"]) def make_error(self, key: str, **kwargs) -> ValidationError: """Helper method to make a `ValidationError` with an error message from ``self.error_messages``. """ try: msg = self.error_messages[key] except KeyError as error: class_name = self.__class__.__name__ message = ( "ValidationError raised by `{class_name}`, but error key `{key}` does " "not exist in the `error_messages` dictionary." ).format(class_name=class_name, key=key) raise AssertionError(message) from error if isinstance(msg, (str, bytes)): msg = msg.format(**kwargs) return ValidationError(msg) def fail(self, key: str, **kwargs): """Helper method that raises a `ValidationError` with an error message from ``self.error_messages``. .. deprecated:: 3.0.0 Use `make_error <marshmallow.fields.Field.make_error>` instead. """ warnings.warn( '`Field.fail` is deprecated. Use `raise self.make_error("{}", ...)` instead.'.format( key ), RemovedInMarshmallow4Warning, stacklevel=2, ) raise self.make_error(key=key, **kwargs) def _validate_missing(self, value): """Validate missing values. Raise a :exc:`ValidationError` if `value` should be considered missing. """ if value is missing_ and self.required: raise self.make_error("required") if value is None and not self.allow_none: raise self.make_error("null") def serialize( self, attr: str, obj: typing.Any, accessor: typing.Callable[[typing.Any, str, typing.Any], typing.Any] | None = None, **kwargs, ): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. :param attr: The attribute/key to get from the object. :param obj: The object to access the attribute/key from. :param accessor: Function used to access values from ``obj``. :param kwargs: Field-specific keyword arguments. """ if self._CHECK_ATTRIBUTE: value = self.get_value(obj, attr, accessor=accessor) if value is missing_: default = self.dump_default value = default() if callable(default) else default if value is missing_: return value else: value = None return self._serialize(value, attr, obj, **kwargs) def deserialize( self, value: typing.Any, attr: str | None = None, data: typing.Mapping[str, typing.Any] | None = None, **kwargs, ): """Deserialize ``value``. :param value: The value to deserialize. :param attr: The attribute/key in `data` to deserialize. :param data: The raw input data passed to `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: If an invalid value is passed or if a required value is missing. """ # Validate required fields, deserialize, then validate # deserialized value self._validate_missing(value) if value is missing_: _miss = self.load_default return _miss() if callable(_miss) else _miss if self.allow_none and value is None: return None output = self._deserialize(value, attr, data, **kwargs) self._validate(output) return output # Methods for concrete classes to override. def _bind_to_schema(self, field_name, schema): """Update field with values from its parent schema. Called by :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema|Field schema: Parent object. """ self.parent = self.parent or schema self.name = self.name or field_name self.root = self.root or ( self.parent.root if isinstance(self.parent, FieldABC) else self.parent ) def _serialize( self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs ): """Serializes ``value`` to a basic Python datatype. Noop by default. Concrete :class:`Field` classes should implement this method. Example: :: class TitleCase(Field): def _serialize(self, value, attr, obj, **kwargs): if not value: return '' return str(value).title() :param value: The value to be serialized. :param str attr: The attribute or key on the object to be serialized. :param object obj: The object the value was pulled from. :param dict kwargs: Field-specific keyword arguments. :return: The serialized value """ return value def _deserialize( self, value: typing.Any, attr: str | None, data: typing.Mapping[str, typing.Any] | None, **kwargs, ): """Deserialize value. Concrete :class:`Field` classes should implement this method. :param value: The value to be deserialized. :param attr: The attribute/key in `data` to be deserialized. :param data: The raw input data passed to the `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: In case of formatting or validation failure. :return: The deserialized value. .. versionchanged:: 2.0.0 Added ``attr`` and ``data`` parameters. .. versionchanged:: 3.0.0 Added ``**kwargs`` to signature. """ return value # Properties @property def context(self): """The context dictionary for the parent :class:`Schema`.""" return self.parent.context # the default and missing properties are provided for compatibility and # emit warnings when they are accessed and set @property def default(self): warnings.warn( "The 'default' attribute of fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) return self.dump_default @default.setter def default(self, value): warnings.warn( "The 'default' attribute of fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) self.dump_default = value @property def missing(self): warnings.warn( "The 'missing' attribute of fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) return self.load_default @missing.setter def missing(self, value): warnings.warn( "The 'missing' attribute of fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) self.load_default = value class Raw(Field): """Field that applies no formatting.""" class Nested(Field): """Allows you to nest a :class:`Schema <marshmallow.Schema>` inside a field. Examples: :: class ChildSchema(Schema): id = fields.Str() name = fields.Str() # Use lambda functions when you need two-way nesting or self-nesting parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) class ParentSchema(Schema): id = fields.Str() children = fields.List( fields.Nested(ChildSchema(only=("id", "parent", "siblings"))) ) spouse = fields.Nested(lambda: ParentSchema(only=("id",))) When passing a `Schema <marshmallow.Schema>` instance as the first argument, the instance's ``exclude``, ``only``, and ``many`` attributes will be respected. Therefore, when passing the ``exclude``, ``only``, or ``many`` arguments to `fields.Nested`, you should pass a `Schema <marshmallow.Schema>` class (not an instance) as the first argument. :: # Yes author = fields.Nested(UserSchema, only=('id', 'name')) # No author = fields.Nested(UserSchema(), only=('id', 'name')) :param nested: `Schema` instance, class, class name (string), dictionary, or callable that returns a `Schema` or dictionary. Dictionaries are converted with `Schema.from_dict`. :param exclude: A list or tuple of fields to exclude. :param only: A list or tuple of fields to marshal. If `None`, all fields are marshalled. This parameter takes precedence over ``exclude``. :param many: Whether the field is a collection of objects. :param unknown: Whether to exclude, include, or raise an error for unknown fields in the data. Use `EXCLUDE`, `INCLUDE` or `RAISE`. :param kwargs: The same keyword arguments that :class:`Field` receives. """ #: Default error messages. default_error_messages = {"type": "Invalid type."} def __init__( self, nested: SchemaABC | type | str | dict[str, Field | type] | typing.Callable[[], SchemaABC | dict[str, Field | type]], *, dump_default: typing.Any = missing_, default: typing.Any = missing_, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: str | None = None, **kwargs, ): # Raise error if only or exclude is passed as string, not list of strings if only is not None and not is_collection(only): raise StringNotCollectionError('"only" should be a collection of strings.') if not is_collection(exclude): raise StringNotCollectionError( '"exclude" should be a collection of strings.' ) if nested == "self": warnings.warn( "Passing 'self' to `Nested` is deprecated. " "Use `Nested(lambda: MySchema(...))` instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) self.nested = nested self.only = only self.exclude = exclude self.many = many self.unknown = unknown self._schema = None # Cached Schema instance super().__init__(default=default, dump_default=dump_default, **kwargs) @property def schema(self): """The nested Schema object. .. versionchanged:: 1.0.0 Renamed from `serializer` to `schema`. """ if not self._schema: # Inherit context from parent. context = getattr(self.parent, "context", {}) if callable(self.nested) and not isinstance(self.nested, type): nested = self.nested() else: nested = self.nested if isinstance(nested, dict): # defer the import of `marshmallow.schema` to avoid circular imports from marshmallow.schema import Schema nested = Schema.from_dict(nested) if isinstance(nested, SchemaABC): self._schema = copy.copy(nested) self._schema.context.update(context) # Respect only and exclude passed from parent and re-initialize fields set_class = self._schema.set_class if self.only is not None: if self._schema.only is not None: original = self._schema.only else: # only=None -> all fields original = self._schema.fields.keys() self._schema.only = set_class(self.only) & set_class(original) if self.exclude: original = self._schema.exclude self._schema.exclude = set_class(self.exclude) | set_class(original) self._schema._init_fields() else: if isinstance(nested, type) and issubclass(nested, SchemaABC): schema_class = nested elif not isinstance(nested, (str, bytes)): raise ValueError( "`Nested` fields must be passed a " "`Schema`, not {}.".format(nested.__class__) ) elif nested == "self": schema_class = self.root.__class__ else: schema_class = class_registry.get_class(nested) self._schema = schema_class( many=self.many, only=self.only, exclude=self.exclude, context=context, load_only=self._nested_normalized_option("load_only"), dump_only=self._nested_normalized_option("dump_only"), ) return self._schema def _nested_normalized_option(self, option_name: str) -> list[str]: nested_field = "%s." % self.name return [ field.split(nested_field, 1)[1] for field in getattr(self.root, option_name, set()) if field.startswith(nested_field) ] def _serialize(self, nested_obj, attr, obj, **kwargs): # Load up the schema first. This allows a RegistryError to be raised # if an invalid schema name was passed schema = self.schema if nested_obj is None: return None many = schema.many or self.many return schema.dump(nested_obj, many=many) def _test_collection(self, value): many = self.schema.many or self.many if many and not utils.is_collection(value): raise self.make_error("type", input=value, type=value.__class__.__name__) def _load(self, value, data, partial=None): try: valid_data = self.schema.load(value, unknown=self.unknown, partial=partial) except ValidationError as error: raise ValidationError( error.messages, valid_data=error.valid_data ) from error return valid_data def _deserialize(self, value, attr, data, partial=None, **kwargs): """Same as :meth:`Field._deserialize` with additional ``partial`` argument. :param bool|tuple partial: For nested schemas, the ``partial`` parameter passed to `Schema.load`. .. versionchanged:: 3.0.0 Add ``partial`` parameter. """ self._test_collection(value) return self._load(value, data, partial=partial) class Pluck(Nested): """Allows you to replace nested data with one of the data's fields. Example: :: from marshmallow import Schema, fields class ArtistSchema(Schema): id = fields.Int() name = fields.Str() class AlbumSchema(Schema): artist = fields.Pluck(ArtistSchema, 'id') in_data = {'artist': 42} loaded = AlbumSchema().load(in_data) # => {'artist': {'id': 42}} dumped = AlbumSchema().dump(loaded) # => {'artist': 42} :param Schema nested: The Schema class or class name (string) to nest, or ``"self"`` to nest the :class:`Schema` within itself. :param str field_name: The key to pluck a value from. :param kwargs: The same keyword arguments that :class:`Nested` receives. """ def __init__( self, nested: SchemaABC | type | str | typing.Callable[[], SchemaABC], field_name: str, **kwargs, ): super().__init__(nested, only=(field_name,), **kwargs) self.field_name = field_name @property def _field_data_key(self): only_field = self.schema.fields[self.field_name] return only_field.data_key or self.field_name def _serialize(self, nested_obj, attr, obj, **kwargs): ret = super()._serialize(nested_obj, attr, obj, **kwargs) if ret is None: return None if self.many: return utils.pluck(ret, key=self._field_data_key) return ret[self._field_data_key] def _deserialize(self, value, attr, data, partial=None, **kwargs): self._test_collection(value) if self.many: value = [{self._field_data_key: v} for v in value] else: value = {self._field_data_key: value} return self._load(value, data, partial=partial) class List(Field): """A list field, composed with another `Field` class or instance. Example: :: numbers = fields.List(fields.Float()) :param cls_or_instance: A field class or instance. :param kwargs: The same keyword arguments that :class:`Field` receives. .. versionchanged:: 2.0.0 The ``allow_none`` parameter now applies to deserialization and has the same semantics as the other fields. .. versionchanged:: 3.0.0rc9 Does not serialize scalar values to single-item lists. """ #: Default error messages. default_error_messages = {"invalid": "Not a valid list."} def __init__(self, cls_or_instance: Field | type, **kwargs): super().__init__(**kwargs) try: self.inner = resolve_field_instance(cls_or_instance) except FieldInstanceResolutionError as error: raise ValueError( "The list elements must be a subclass or instance of " "marshmallow.base.FieldABC." ) from error if isinstance(self.inner, Nested): self.only = self.inner.only self.exclude = self.inner.exclude def _bind_to_schema(self, field_name, schema): super()._bind_to_schema(field_name, schema) self.inner = copy.deepcopy(self.inner) self.inner._bind_to_schema(field_name, self) if isinstance(self.inner, Nested): self.inner.only = self.only self.inner.exclude = self.exclude def _serialize(self, value, attr, obj, **kwargs) -> list[typing.Any] | None: if value is None: return None return [self.inner._serialize(each, attr, obj, **kwargs) for each in value] def _deserialize(self, value, attr, data, **kwargs) -> list[typing.Any]: if not utils.is_collection(value): raise self.make_error("invalid") result = [] errors = {} for idx, each in enumerate(value): try: result.append(self.inner.deserialize(each, **kwargs)) except ValidationError as error: if error.valid_data is not None: result.append(error.valid_data) errors.update({idx: error.messages}) if errors: raise ValidationError(errors, valid_data=result) return result class Tuple(Field): """A tuple field, composed of a fixed number of other `Field` classes or instances Example: :: row = Tuple((fields.String(), fields.Integer(), fields.Float())) .. note:: Because of the structured nature of `collections.namedtuple` and `typing.NamedTuple`, using a Schema within a Nested field for them is more appropriate than using a `Tuple` field. :param Iterable[Field] tuple_fields: An iterable of field classes or instances. :param kwargs: The same keyword arguments that :class:`Field` receives. .. versionadded:: 3.0.0rc4 """ #: Default error messages. default_error_messages = {"invalid": "Not a valid tuple."} def __init__(self, tuple_fields, *args, **kwargs): super().__init__(*args, **kwargs) if not utils.is_collection(tuple_fields): raise ValueError( "tuple_fields must be an iterable of Field classes or " "instances." ) try: self.tuple_fields = [ resolve_field_instance(cls_or_instance) for cls_or_instance in tuple_fields ] except FieldInstanceResolutionError as error: raise ValueError( 'Elements of "tuple_fields" must be subclasses or ' "instances of marshmallow.base.FieldABC." ) from error self.validate_length = Length(equal=len(self.tuple_fields)) def _bind_to_schema(self, field_name, schema): super()._bind_to_schema(field_name, schema) new_tuple_fields = [] for field in self.tuple_fields: field = copy.deepcopy(field) field._bind_to_schema(field_name, self) new_tuple_fields.append(field) self.tuple_fields = new_tuple_fields def _serialize(self, value, attr, obj, **kwargs) -> tuple | None: if value is None: return None return tuple( field._serialize(each, attr, obj, **kwargs) for field, each in zip(self.tuple_fields, value) ) def _deserialize(self, value, attr, data, **kwargs) -> tuple: if not utils.is_collection(value): raise self.make_error("invalid") self.validate_length(value) result = [] errors = {} for idx, (field, each) in enumerate(zip(self.tuple_fields, value)): try: result.append(field.deserialize(each, **kwargs)) except ValidationError as error: if error.valid_data is not None: result.append(error.valid_data) errors.update({idx: error.messages}) if errors: raise ValidationError(errors, valid_data=result) return tuple(result) class String(Field): """A string field. :param kwargs: The same keyword arguments that :class:`Field` receives. """ #: Default error messages. default_error_messages = { "invalid": "Not a valid string.", "invalid_utf8": "Not a valid utf-8 string.", } def _serialize(self, value, attr, obj, **kwargs) -> str | None: if value is None: return None return utils.ensure_text_type(value) def _deserialize(self, value, attr, data, **kwargs) -> typing.Any: if not isinstance(value, (str, bytes)): raise self.make_error("invalid") try: return utils.ensure_text_type(value) except UnicodeDecodeError as error: raise self.make_error("invalid_utf8") from error class UUID(String): """A UUID field.""" #: Default error messages. default_error_messages = {"invalid_uuid": "Not a valid UUID."} def _validated(self, value) -> uuid.UUID | None: """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None if isinstance(value, uuid.UUID): return value try: if isinstance(value, bytes) and len(value) == 16: return uuid.UUID(bytes=value) else: return uuid.UUID(value) except (ValueError, AttributeError, TypeError) as error: raise self.make_error("invalid_uuid") from error def _deserialize(self, value, attr, data, **kwargs) -> uuid.UUID | None: return self._validated(value) class Number(Field): """Base class for number fields. :param bool as_string: If `True`, format the serialized value as a string. :param kwargs: The same keyword arguments that :class:`Field` receives. """ num_type = float # type: typing.Type #: Default error messages. default_error_messages = { "invalid": "Not a valid number.", "too_large": "Number too large.", } def __init__(self, *, as_string: bool = False, **kwargs): self.as_string = as_string super().__init__(**kwargs) def _format_num(self, value) -> typing.Any: """Return the number value for value, given this field's `num_type`.""" return self.num_type(value) def _validated(self, value) -> _T | None: """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None # (value is True or value is False) is ~5x faster than isinstance(value, bool) if value is True or value is False: raise self.make_error("invalid", input=value) try: return self._format_num(value) except (TypeError, ValueError) as error: raise self.make_error("invalid", input=value) from error except OverflowError as error: raise self.make_error("too_large", input=value) from error def _to_string(self, value) -> str: return str(value) def _serialize(self, value, attr, obj, **kwargs) -> str | _T | None: """Return a string if `self.as_string=True`, otherwise return this field's `num_type`.""" if value is None: return None ret = self._format_num(value) # type: _T return self._to_string(ret) if self.as_string else ret def _deserialize(self, value, attr, data, **kwargs) -> _T | None: return self._validated(value) class Integer(Number): """An integer field. :param strict: If `True`, only integer types are valid. Otherwise, any value castable to `int` is valid. :param kwargs: The same keyword arguments that :class:`Number` receives. """ num_type = int #: Default error messages. default_error_messages = {"invalid": "Not a valid integer."} def __init__(self, *, strict: bool = False, **kwargs): self.strict = strict super().__init__(**kwargs) # override Number def _validated(self, value): if self.strict and not isinstance(value, numbers.Integral): raise self.make_error("invalid", input=value) return super()._validated(value) class Float(Number): """A double as an IEEE-754 double precision string. :param bool allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification. :param bool as_string: If `True`, format the value as a string. :param kwargs: The same keyword arguments that :class:`Number` receives. """ num_type = float #: Default error messages. default_error_messages = { "special": "Special numeric values (nan or infinity) are not permitted." } def __init__(self, *, allow_nan: bool = False, as_string: bool = False, **kwargs): self.allow_nan = allow_nan super().__init__(as_string=as_string, **kwargs) def _validated(self, value): num = super()._validated(value) if self.allow_nan is False: if math.isnan(num) or num == float("inf") or num == float("-inf"): raise self.make_error("special") return num class Decimal(Number): """A field that (de)serializes to the Python ``decimal.Decimal`` type. It's safe to use when dealing with money values, percentages, ratios or other numbers where precision is critical. .. warning:: This field serializes to a `decimal.Decimal` object by default. If you need to render your data as JSON, keep in mind that the `json` module from the standard library does not encode `decimal.Decimal`. Therefore, you must use a JSON library that can handle decimals, such as `simplejson`, or serialize to a string by passing ``as_string=True``. .. warning:: If a JSON `float` value is passed to this field for deserialization it will first be cast to its corresponding `string` value before being deserialized to a `decimal.Decimal` object. The default `__str__` implementation of the built-in Python `float` type may apply a destructive transformation upon its input data and therefore cannot be relied upon to preserve precision. To avoid this, you can instead pass a JSON `string` to be deserialized directly. :param places: How many decimal places to quantize the value. If `None`, does not quantize the value. :param rounding: How to round the value during quantize, for example `decimal.ROUND_UP`. If `None`, uses the rounding value from the current thread's context. :param allow_nan: If `True`, `NaN`, `Infinity` and `-Infinity` are allowed, even though they are illegal according to the JSON specification. :param as_string: If `True`, serialize to a string instead of a Python `decimal.Decimal` type. :param kwargs: The same keyword arguments that :class:`Number` receives. .. versionadded:: 1.2.0 """ num_type = decimal.Decimal #: Default error messages. default_error_messages = { "special": "Special numeric values (nan or infinity) are not permitted." } def __init__( self, places: int | None = None, rounding: str | None = None, *, allow_nan: bool = False, as_string: bool = False, **kwargs, ): self.places = ( decimal.Decimal((0, (1,), -places)) if places is not None else None ) self.rounding = rounding self.allow_nan = allow_nan super().__init__(as_string=as_string, **kwargs) # override Number def _format_num(self, value): num = decimal.Decimal(str(value)) if self.allow_nan: if num.is_nan(): return decimal.Decimal("NaN") # avoid sNaN, -sNaN and -NaN if self.places is not None and num.is_finite(): num = num.quantize(self.places, rounding=self.rounding) return num # override Number def _validated(self, value): try: num = super()._validated(value) except decimal.InvalidOperation as error: raise self.make_error("invalid") from error if not self.allow_nan and (num.is_nan() or num.is_infinite()): raise self.make_error("special") return num # override Number def _to_string(self, value): return format(value, "f") class Boolean(Field): """A boolean field. :param truthy: Values that will (de)serialize to `True`. If an empty set, any non-falsy value will deserialize to `True`. If `None`, `marshmallow.fields.Boolean.truthy` will be used. :param falsy: Values that will (de)serialize to `False`. If `None`, `marshmallow.fields.Boolean.falsy` will be used. :param kwargs: The same keyword arguments that :class:`Field` receives. """ #: Default truthy values. truthy = { "t", "T", "true", "True", "TRUE", "on", "On", "ON", "y", "Y", "yes", "Yes", "YES", "1", 1, True, } #: Default falsy values. falsy = { "f", "F", "false", "False", "FALSE", "off", "Off", "OFF", "n", "N", "no", "No", "NO", "0", 0, 0.0, False, } #: Default error messages. default_error_messages = {"invalid": "Not a valid boolean."} def __init__( self, *, truthy: set | None = None, falsy: set | None = None, **kwargs, ): super().__init__(**kwargs) if truthy is not None: self.truthy = set(truthy) if falsy is not None: self.falsy = set(falsy) def _serialize(self, value, attr, obj, **kwargs): if value is None: return None try: if value in self.truthy: return True if value in self.falsy: return False except TypeError: pass return bool(value) def _deserialize(self, value, attr, data, **kwargs): if not self.truthy: return bool(value) try: if value in self.truthy: return True if value in self.falsy: return False except TypeError as error: raise self.make_error("invalid", input=value) from error raise self.make_error("invalid", input=value) class DateTime(Field): """A formatted datetime string. Example: ``'2014-12-22T03:12:58.019077+00:00'`` :param format: Either ``"rfc"`` (for RFC822), ``"iso"`` (for ISO8601), ``"timestamp"``, ``"timestamp_ms"`` (for a POSIX timestamp) or a date format string. If `None`, defaults to "iso". :param kwargs: The same keyword arguments that :class:`Field` receives. .. versionchanged:: 3.0.0rc9 Does not modify timezone information on (de)serialization. .. versionchanged:: 3.19 Add timestamp as a format. """ SERIALIZATION_FUNCS = { "iso": utils.isoformat, "iso8601": utils.isoformat, "rfc": utils.rfcformat, "rfc822": utils.rfcformat, "timestamp": utils.timestamp, "timestamp_ms": utils.timestamp_ms, } # type: typing.Dict[str, typing.Callable[[typing.Any], str | float]] DESERIALIZATION_FUNCS = { "iso": utils.from_iso_datetime, "iso8601": utils.from_iso_datetime, "rfc": utils.from_rfc, "rfc822": utils.from_rfc, "timestamp": utils.from_timestamp, "timestamp_ms": utils.from_timestamp_ms, } # type: typing.Dict[str, typing.Callable[[str], typing.Any]] DEFAULT_FORMAT = "iso" OBJ_TYPE = "datetime" SCHEMA_OPTS_VAR_NAME = "datetimeformat" #: Default error messages. default_error_messages = { "invalid": "Not a valid {obj_type}.", "invalid_awareness": "Not a valid {awareness} {obj_type}.", "format": '"{input}" cannot be formatted as a {obj_type}.', } def __init__(self, format: str | None = None, **kwargs) -> None: super().__init__(**kwargs) # Allow this to be None. It may be set later in the ``_serialize`` # or ``_deserialize`` methods. This allows a Schema to dynamically set the # format, e.g. from a Meta option self.format = format def _bind_to_schema(self, field_name, schema): super()._bind_to_schema(field_name, schema) self.format = ( self.format or getattr(self.root.opts, self.SCHEMA_OPTS_VAR_NAME) or self.DEFAULT_FORMAT ) def _serialize(self, value, attr, obj, **kwargs) -> str | float | None: if value is None: return None data_format = self.format or self.DEFAULT_FORMAT format_func = self.SERIALIZATION_FUNCS.get(data_format) if format_func: return format_func(value) else: return value.strftime(data_format) def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime: if not value: # Falsy values, e.g. '', None, [] are not valid raise self.make_error("invalid", input=value, obj_type=self.OBJ_TYPE) data_format = self.format or self.DEFAULT_FORMAT func = self.DESERIALIZATION_FUNCS.get(data_format) if func: try: return func(value) except (TypeError, AttributeError, ValueError) as error: raise self.make_error( "invalid", input=value, obj_type=self.OBJ_TYPE ) from error else: try: return self._make_object_from_format(value, data_format) except (TypeError, AttributeError, ValueError) as error: raise self.make_error( "invalid", input=value, obj_type=self.OBJ_TYPE ) from error @staticmethod def _make_object_from_format(value, data_format) -> dt.datetime: return dt.datetime.strptime(value, data_format) class NaiveDateTime(DateTime): """A formatted naive datetime string. :param format: See :class:`DateTime`. :param timezone: Used on deserialization. If `None`, aware datetimes are rejected. If not `None`, aware datetimes are converted to this timezone before their timezone information is removed. :param kwargs: The same keyword arguments that :class:`Field` receives. .. versionadded:: 3.0.0rc9 """ AWARENESS = "naive" def __init__( self, format: str | None = None, *, timezone: dt.timezone | None = None, **kwargs, ) -> None: super().__init__(format=format, **kwargs) self.timezone = timezone def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime: ret = super()._deserialize(value, attr, data, **kwargs) if is_aware(ret): if self.timezone is None: raise self.make_error( "invalid_awareness", awareness=self.AWARENESS, obj_type=self.OBJ_TYPE, ) ret = ret.astimezone(self.timezone).replace(tzinfo=None) return ret class AwareDateTime(DateTime): """A formatted aware datetime string. :param format: See :class:`DateTime`. :param default_timezone: Used on deserialization. If `None`, naive datetimes are rejected. If not `None`, naive datetimes are set this timezone. :param kwargs: The same keyword arguments that :class:`Field` receives. .. versionadded:: 3.0.0rc9 """ AWARENESS = "aware" def __init__( self, format: str | None = None, *, default_timezone: dt.tzinfo | None = None, **kwargs, ) -> None: super().__init__(format=format, **kwargs) self.default_timezone = default_timezone def _deserialize(self, value, attr, data, **kwargs) -> dt.datetime: ret = super()._deserialize(value, attr, data, **kwargs) if not is_aware(ret): if self.default_timezone is None: raise self.make_error( "invalid_awareness", awareness=self.AWARENESS, obj_type=self.OBJ_TYPE, ) ret = ret.replace(tzinfo=self.default_timezone) return ret class Time(DateTime): """A formatted time string. Example: ``'03:12:58.019077'`` :param format: Either ``"iso"`` (for ISO8601) or a date format string. If `None`, defaults to "iso". :param kwargs: The same keyword arguments that :class:`Field` receives. """ SERIALIZATION_FUNCS = {"iso": utils.to_iso_time, "iso8601": utils.to_iso_time} DESERIALIZATION_FUNCS = {"iso": utils.from_iso_time, "iso8601": utils.from_iso_time} DEFAULT_FORMAT = "iso" OBJ_TYPE = "time" SCHEMA_OPTS_VAR_NAME = "timeformat" @staticmethod def _make_object_from_format(value, data_format): return dt.datetime.strptime(value, data_format).time() class Date(DateTime): """ISO8601-formatted date string. :param format: Either ``"iso"`` (for ISO8601) or a date format string. If `None`, defaults to "iso". :param kwargs: The same keyword arguments that :class:`Field` receives. """ #: Default error messages. default_error_messages = { "invalid": "Not a valid date.", "format": '"{input}" cannot be formatted as a date.', } SERIALIZATION_FUNCS = {"iso": utils.to_iso_date, "iso8601": utils.to_iso_date} DESERIALIZATION_FUNCS = {"iso": utils.from_iso_date, "iso8601": utils.from_iso_date} DEFAULT_FORMAT = "iso" OBJ_TYPE = "date" SCHEMA_OPTS_VAR_NAME = "dateformat" @staticmethod def _make_object_from_format(value, data_format): return dt.datetime.strptime(value, data_format).date() class TimeDelta(Field): """A field that (de)serializes a :class:`datetime.timedelta` object to an integer or float and vice versa. The integer or float can represent the number of days, seconds or microseconds. :param precision: Influences how the integer or float is interpreted during (de)serialization. Must be 'days', 'seconds', 'microseconds', 'milliseconds', 'minutes', 'hours' or 'weeks'. :param serialization_type: Whether to (de)serialize to a `int` or `float`. :param kwargs: The same keyword arguments that :class:`Field` receives. Integer Caveats --------------- Any fractional parts (which depends on the precision used) will be truncated when serializing using `int`. Float Caveats ------------- Use of `float` when (de)serializing may result in data precision loss due to the way machines handle floating point values. Regardless of the precision chosen, the fractional part when using `float` will always be truncated to microseconds. For example, `1.12345` interpreted as microseconds will result in `timedelta(microseconds=1)`. .. versionchanged:: 2.0.0 Always serializes to an integer value to avoid rounding errors. Add `precision` parameter. .. versionchanged:: 3.17.0 Allow (de)serialization to `float` through use of a new `serialization_type` parameter. `int` is the default to retain previous behaviour. """ DAYS = "days" SECONDS = "seconds" MICROSECONDS = "microseconds" MILLISECONDS = "milliseconds" MINUTES = "minutes" HOURS = "hours" WEEKS = "weeks" #: Default error messages. default_error_messages = { "invalid": "Not a valid period of time.", "format": "{input!r} cannot be formatted as a timedelta.", } def __init__( self, precision: str = SECONDS, serialization_type: type[int | float] = int, **kwargs, ): precision = precision.lower() units = ( self.DAYS, self.SECONDS, self.MICROSECONDS, self.MILLISECONDS, self.MINUTES, self.HOURS, self.WEEKS, ) if precision not in units: msg = 'The precision must be {} or "{}".'.format( ", ".join([f'"{each}"' for each in units[:-1]]), units[-1] ) raise ValueError(msg) if serialization_type not in (int, float): raise ValueError("The serialization type must be one of int or float") self.precision = precision self.serialization_type = serialization_type super().__init__(**kwargs) def _serialize(self, value, attr, obj, **kwargs): if value is None: return None base_unit = dt.timedelta(**{self.precision: 1}) if self.serialization_type is int: delta = utils.timedelta_to_microseconds(value) unit = utils.timedelta_to_microseconds(base_unit) return delta // unit else: assert self.serialization_type is float return value.total_seconds() / base_unit.total_seconds() def _deserialize(self, value, attr, data, **kwargs): try: value = self.serialization_type(value) except (TypeError, ValueError) as error: raise self.make_error("invalid") from error kwargs = {self.precision: value} try: return dt.timedelta(**kwargs) except OverflowError as error: raise self.make_error("invalid") from error class Mapping(Field): """An abstract class for objects with key-value pairs. :param keys: A field class or instance for dict keys. :param values: A field class or instance for dict values. :param kwargs: The same keyword arguments that :class:`Field` receives. .. note:: When the structure of nested data is not known, you may omit the `keys` and `values` arguments to prevent content validation. .. versionadded:: 3.0.0rc4 """ mapping_type = dict #: Default error messages. default_error_messages = {"invalid": "Not a valid mapping type."} def __init__( self, keys: Field | type | None = None, values: Field | type | None = None, **kwargs, ): super().__init__(**kwargs) if keys is None: self.key_field = None else: try: self.key_field = resolve_field_instance(keys) except FieldInstanceResolutionError as error: raise ValueError( '"keys" must be a subclass or instance of ' "marshmallow.base.FieldABC." ) from error if values is None: self.value_field = None else: try: self.value_field = resolve_field_instance(values) except FieldInstanceResolutionError as error: raise ValueError( '"values" must be a subclass or instance of ' "marshmallow.base.FieldABC." ) from error if isinstance(self.value_field, Nested): self.only = self.value_field.only self.exclude = self.value_field.exclude def _bind_to_schema(self, field_name, schema): super()._bind_to_schema(field_name, schema) if self.value_field: self.value_field = copy.deepcopy(self.value_field) self.value_field._bind_to_schema(field_name, self) if isinstance(self.value_field, Nested): self.value_field.only = self.only self.value_field.exclude = self.exclude if self.key_field: self.key_field = copy.deepcopy(self.key_field) self.key_field._bind_to_schema(field_name, self) def _serialize(self, value, attr, obj, **kwargs): if value is None: return None if not self.value_field and not self.key_field: return self.mapping_type(value) #  Serialize keys if self.key_field is None: keys = {k: k for k in value.keys()} else: keys = { k: self.key_field._serialize(k, None, None, **kwargs) for k in value.keys() } #  Serialize values result = self.mapping_type() if self.value_field is None: for k, v in value.items(): if k in keys: result[keys[k]] = v else: for k, v in value.items(): result[keys[k]] = self.value_field._serialize(v, None, None, **kwargs) return result def _deserialize(self, value, attr, data, **kwargs): if not isinstance(value, _Mapping): raise self.make_error("invalid") if not self.value_field and not self.key_field: return self.mapping_type(value) errors = collections.defaultdict(dict) #  Deserialize keys if self.key_field is None: keys = {k: k for k in value.keys()} else: keys = {} for key in value.keys(): try: keys[key] = self.key_field.deserialize(key, **kwargs) except ValidationError as error: errors[key]["key"] = error.messages #  Deserialize values result = self.mapping_type() if self.value_field is None: for k, v in value.items(): if k in keys: result[keys[k]] = v else: for key, val in value.items(): try: deser_val = self.value_field.deserialize(val, **kwargs) except ValidationError as error: errors[key]["value"] = error.messages if error.valid_data is not None and key in keys: result[keys[key]] = error.valid_data else: if key in keys: result[keys[key]] = deser_val if errors: raise ValidationError(errors, valid_data=result) return result class Dict(Mapping): """A dict field. Supports dicts and dict-like objects. Extends Mapping with dict as the mapping_type. Example: :: numbers = fields.Dict(keys=fields.Str(), values=fields.Float()) :param kwargs: The same keyword arguments that :class:`Mapping` receives. .. versionadded:: 2.1.0 """ mapping_type = dict class Url(String): """An URL field. :param default: Default value for the field if the attribute is not set. :param relative: Whether to allow relative URLs. :param require_tld: Whether to reject non-FQDN hostnames. :param schemes: Valid schemes. By default, ``http``, ``https``, ``ftp``, and ``ftps`` are allowed. :param kwargs: The same keyword arguments that :class:`String` receives. """ #: Default error messages. default_error_messages = {"invalid": "Not a valid URL."} def __init__( self, *, relative: bool = False, schemes: types.StrSequenceOrSet | None = None, require_tld: bool = True, **kwargs, ): super().__init__(**kwargs) self.relative = relative self.require_tld = require_tld # Insert validation into self.validators so that multiple errors can be stored. validator = validate.URL( relative=self.relative, schemes=schemes, require_tld=self.require_tld, error=self.error_messages["invalid"], ) self.validators.insert(0, validator) class Email(String): """An email field. :param args: The same positional arguments that :class:`String` receives. :param kwargs: The same keyword arguments that :class:`String` receives. """ #: Default error messages. default_error_messages = {"invalid": "Not a valid email address."} def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) # Insert validation into self.validators so that multiple errors can be stored. validator = validate.Email(error=self.error_messages["invalid"]) self.validators.insert(0, validator) class IP(Field): """A IP address field. :param bool exploded: If `True`, serialize ipv6 address in long form, ie. with groups consisting entirely of zeros included. .. versionadded:: 3.8.0 """ default_error_messages = {"invalid_ip": "Not a valid IP address."} DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type] def __init__(self, *args, exploded=False, **kwargs): super().__init__(*args, **kwargs) self.exploded = exploded def _serialize(self, value, attr, obj, **kwargs) -> str | None: if value is None: return None if self.exploded: return value.exploded return value.compressed def _deserialize( self, value, attr, data, **kwargs ) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: if value is None: return None try: return (self.DESERIALIZATION_CLASS or ipaddress.ip_address)( utils.ensure_text_type(value) ) except (ValueError, TypeError) as error: raise self.make_error("invalid_ip") from error class IPv4(IP): """A IPv4 address field. .. versionadded:: 3.8.0 """ default_error_messages = {"invalid_ip": "Not a valid IPv4 address."} DESERIALIZATION_CLASS = ipaddress.IPv4Address class IPv6(IP): """A IPv6 address field. .. versionadded:: 3.8.0 """ default_error_messages = {"invalid_ip": "Not a valid IPv6 address."} DESERIALIZATION_CLASS = ipaddress.IPv6Address class IPInterface(Field): """A IPInterface field. IP interface is the non-strict form of the IPNetwork type where arbitrary host addresses are always accepted. IPAddress and mask e.g. '192.168.0.2/24' or '192.168.0.2/255.255.255.0' see https://python.readthedocs.io/en/latest/library/ipaddress.html#interface-objects :param bool exploded: If `True`, serialize ipv6 interface in long form, ie. with groups consisting entirely of zeros included. """ default_error_messages = {"invalid_ip_interface": "Not a valid IP interface."} DESERIALIZATION_CLASS = None # type: typing.Optional[typing.Type] def __init__(self, *args, exploded: bool = False, **kwargs): super().__init__(*args, **kwargs) self.exploded = exploded def _serialize(self, value, attr, obj, **kwargs) -> str | None: if value is None: return None if self.exploded: return value.exploded return value.compressed def _deserialize( self, value, attr, data, **kwargs ) -> None | (ipaddress.IPv4Interface | ipaddress.IPv6Interface): if value is None: return None try: return (self.DESERIALIZATION_CLASS or ipaddress.ip_interface)( utils.ensure_text_type(value) ) except (ValueError, TypeError) as error: raise self.make_error("invalid_ip_interface") from error class IPv4Interface(IPInterface): """A IPv4 Network Interface field.""" default_error_messages = {"invalid_ip_interface": "Not a valid IPv4 interface."} DESERIALIZATION_CLASS = ipaddress.IPv4Interface class IPv6Interface(IPInterface): """A IPv6 Network Interface field.""" default_error_messages = {"invalid_ip_interface": "Not a valid IPv6 interface."} DESERIALIZATION_CLASS = ipaddress.IPv6Interface class Enum(Field): """An Enum field (de)serializing enum members by symbol (name) or by value. :param enum Enum: Enum class :param boolean|Schema|Field by_value: Whether to (de)serialize by value or by name, or Field class or instance to use to (de)serialize by value. Defaults to False. If `by_value` is `False` (default), enum members are (de)serialized by symbol (name). If it is `True`, they are (de)serialized by value using :class:`Field`. If it is a field instance or class, they are (de)serialized by value using this field. .. versionadded:: 3.18.0 """ default_error_messages = { "unknown": "Must be one of: {choices}.", } def __init__( self, enum: type[EnumType], *, by_value: bool | Field | type = False, **kwargs, ): super().__init__(**kwargs) self.enum = enum self.by_value = by_value # Serialization by name if by_value is False: self.field: Field = String() self.choices_text = ", ".join( str(self.field._serialize(m, None, None)) for m in enum.__members__ ) # Serialization by value else: if by_value is True: self.field = Field() else: try: self.field = resolve_field_instance(by_value) except FieldInstanceResolutionError as error: raise ValueError( '"by_value" must be either a bool or a subclass or instance of ' "marshmallow.base.FieldABC." ) from error self.choices_text = ", ".join( str(self.field._serialize(m.value, None, None)) for m in enum ) def _serialize(self, value, attr, obj, **kwargs): if value is None: return None if self.by_value: val = value.value else: val = value.name return self.field._serialize(val, attr, obj, **kwargs) def _deserialize(self, value, attr, data, **kwargs): val = self.field._deserialize(value, attr, data, **kwargs) if self.by_value: try: return self.enum(val) except ValueError as error: raise self.make_error("unknown", choices=self.choices_text) from error try: return getattr(self.enum, val) except AttributeError as error: raise self.make_error("unknown", choices=self.choices_text) from error class Method(Field): """A field that takes the value returned by a `Schema` method. :param str serialize: The name of the Schema method from which to retrieve the value. The method must take an argument ``obj`` (in addition to self) that is the object to be serialized. :param str deserialize: Optional name of the Schema method for deserializing a value The method must take a single argument ``value``, which is the value to deserialize. .. versionchanged:: 2.0.0 Removed optional ``context`` parameter on methods. Use ``self.context`` instead. .. versionchanged:: 2.3.0 Deprecated ``method_name`` parameter in favor of ``serialize`` and allow ``serialize`` to not be passed at all. .. versionchanged:: 3.0.0 Removed ``method_name`` parameter. """ _CHECK_ATTRIBUTE = False def __init__( self, serialize: str | None = None, deserialize: str | None = None, **kwargs, ): # Set dump_only and load_only based on arguments kwargs["dump_only"] = bool(serialize) and not bool(deserialize) kwargs["load_only"] = bool(deserialize) and not bool(serialize) super().__init__(**kwargs) self.serialize_method_name = serialize self.deserialize_method_name = deserialize self._serialize_method = None self._deserialize_method = None def _bind_to_schema(self, field_name, schema): if self.serialize_method_name: self._serialize_method = utils.callable_or_raise( getattr(schema, self.serialize_method_name) ) if self.deserialize_method_name: self._deserialize_method = utils.callable_or_raise( getattr(schema, self.deserialize_method_name) ) super()._bind_to_schema(field_name, schema) def _serialize(self, value, attr, obj, **kwargs): if self._serialize_method is not None: return self._serialize_method(obj) return missing_ def _deserialize(self, value, attr, data, **kwargs): if self._deserialize_method is not None: return self._deserialize_method(value) return value class Function(Field): """A field that takes the value returned by a function. :param serialize: A callable from which to retrieve the value. The function must take a single argument ``obj`` which is the object to be serialized. It can also optionally take a ``context`` argument, which is a dictionary of context variables passed to the serializer. If no callable is provided then the ```load_only``` flag will be set to True. :param deserialize: A callable from which to retrieve the value. The function must take a single argument ``value`` which is the value to be deserialized. It can also optionally take a ``context`` argument, which is a dictionary of context variables passed to the deserializer. If no callable is provided then ```value``` will be passed through unchanged. .. versionchanged:: 2.3.0 Deprecated ``func`` parameter in favor of ``serialize``. .. versionchanged:: 3.0.0a1 Removed ``func`` parameter. """ _CHECK_ATTRIBUTE = False def __init__( self, serialize: None | ( typing.Callable[[typing.Any], typing.Any] | typing.Callable[[typing.Any, dict], typing.Any] ) = None, deserialize: None | ( typing.Callable[[typing.Any], typing.Any] | typing.Callable[[typing.Any, dict], typing.Any] ) = None, **kwargs, ): # Set dump_only and load_only based on arguments kwargs["dump_only"] = bool(serialize) and not bool(deserialize) kwargs["load_only"] = bool(deserialize) and not bool(serialize) super().__init__(**kwargs) self.serialize_func = serialize and utils.callable_or_raise(serialize) self.deserialize_func = deserialize and utils.callable_or_raise(deserialize) def _serialize(self, value, attr, obj, **kwargs): return self._call_or_raise(self.serialize_func, obj, attr) def _deserialize(self, value, attr, data, **kwargs): if self.deserialize_func: return self._call_or_raise(self.deserialize_func, value, attr) return value def _call_or_raise(self, func, value, attr): if len(utils.get_func_args(func)) > 1: if self.parent.context is None: msg = f"No context available for Function field {attr!r}" raise ValidationError(msg) return func(value, self.parent.context) else: return func(value) class Constant(Field): """A field that (de)serializes to a preset constant. If you only want the constant added for serialization or deserialization, you should use ``dump_only=True`` or ``load_only=True`` respectively. :param constant: The constant to return for the field attribute. .. versionadded:: 2.0.0 """ _CHECK_ATTRIBUTE = False def __init__(self, constant: typing.Any, **kwargs): super().__init__(**kwargs) self.constant = constant self.load_default = constant self.dump_default = constant def _serialize(self, value, *args, **kwargs): return self.constant def _deserialize(self, value, *args, **kwargs): return self.constant class Inferred(Field): """A field that infers how to serialize, based on the value type. .. warning:: This class is treated as private API. Users should not need to use this class directly. """ def __init__(self): super().__init__() # We memoize the fields to avoid creating and binding new fields # every time on serialization. self._field_cache = {} def _serialize(self, value, attr, obj, **kwargs): field_cls = self.root.TYPE_MAPPING.get(type(value)) if field_cls is None: field = super() else: field = self._field_cache.get(field_cls) if field is None: field = field_cls() field._bind_to_schema(self.name, self.parent) self._field_cache[field_cls] = field return field._serialize(value, attr, obj, **kwargs) # Aliases URL = Url Str = String Bool = Boolean Int = Integer
mit
4a3d10b43e5c5803d54b042d87dc3d35
33.61009
98
0.591421
4.237359
false
false
false
false
cupy/cupy
cupyx/scipy/interpolate/_polyint.py
1
17500
import cupy from cupyx.scipy._lib._util import _asarray_validated, float_factorial def _isscalar(x): """Check whether x is if a scalar type, or 0-dim""" return cupy.isscalar(x) or hasattr(x, 'shape') and x.shape == () class _Interpolator1D: """Common features in univariate interpolation. Deal with input data type and interpolation axis rolling. The actual interpolator can assume the y-data is of shape (n, r) where `n` is the number of x-points, and `r` the number of variables, and use self.dtype as the y-data type. Attributes ---------- _y_axis : Axis along which the interpolation goes in the original array _y_extra_shape : Additional shape of the input arrays, excluding the interpolation axis dtype : Dtype of the y-data arrays. It can be set via _set_dtype, which forces it to be float or complex Methods ------- __call__ _prepare_x _finish_y _reshape_y _reshape_yi _set_yi _set_dtype _evaluate """ def __init__(self, xi=None, yi=None, axis=None): self._y_axis = axis self._y_extra_shape = None self.dtype = None if yi is not None: self._set_yi(yi, xi=xi, axis=axis) def __call__(self, x): """Evaluate the interpolant Parameters ---------- x : cupy.ndarray The points to evaluate the interpolant Returns ------- y : cupy.ndarray Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x Notes ----- Input values `x` must be convertible to `float` values like `int` or `float`. """ x, x_shape = self._prepare_x(x) y = self._evaluate(x) return self._finish_y(y, x_shape) def _evaluate(self, x): """ Actually evaluate the value of the interpolator """ raise NotImplementedError() def _prepare_x(self, x): """ Reshape input array to 1-D """ x = _asarray_validated(x, check_finite=False, as_inexact=True) x_shape = x.shape return x.ravel(), x_shape def _finish_y(self, y, x_shape): """ Reshape interpolated y back to an N-D array similar to initial y """ y = y.reshape(x_shape + self._y_extra_shape) if self._y_axis != 0 and x_shape != (): nx = len(x_shape) ny = len(self._y_extra_shape) s = (list(range(nx, nx + self._y_axis)) + list(range(nx)) + list(range(nx + self._y_axis, nx + ny))) y = y.transpose(s) return y def _reshape_yi(self, yi, check=False): """ Reshape the updated yi to a 1-D array """ yi = cupy.moveaxis(yi, self._y_axis, 0) if check and yi.shape[1:] != self._y_extra_shape: ok_shape = "%r + (N,) + %r" % (self._y_extra_shape[-self._y_axis:], self._y_extra_shape[:-self._y_axis]) raise ValueError("Data must be of shape %s" % ok_shape) return yi.reshape((yi.shape[0], -1)) def _set_yi(self, yi, xi=None, axis=None): if axis is None: axis = self._y_axis if axis is None: raise ValueError("no interpolation axis specified") shape = yi.shape if shape == (): shape = (1,) if xi is not None and shape[axis] != len(xi): raise ValueError("x and y arrays must be equal in length along " "interpolation axis.") self._y_axis = (axis % yi.ndim) self._y_extra_shape = yi.shape[:self._y_axis]+yi.shape[self._y_axis+1:] self.dtype = None self._set_dtype(yi.dtype) def _set_dtype(self, dtype, union=False): if cupy.issubdtype(dtype, cupy.complexfloating) \ or cupy.issubdtype(self.dtype, cupy.complexfloating): self.dtype = cupy.complex_ else: if not union or self.dtype != cupy.complex_: self.dtype = cupy.float_ class _Interpolator1DWithDerivatives(_Interpolator1D): def derivatives(self, x, der=None): """Evaluate many derivatives of the polynomial at the point x. The function produce an array of all derivative values at the point x. Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the derivatives der : int or None, optional How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points). This number includes the function value as 0th derivative Returns ------- d : cupy.ndarray Array with derivatives; d[j] contains the jth derivative. Shape of d[j] is determined by replacing the interpolation axis in the original array with the shape of x """ x, x_shape = self._prepare_x(x) y = self._evaluate_derivatives(x, der) y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape) if self._y_axis != 0 and x_shape != (): nx = len(x_shape) ny = len(self._y_extra_shape) s = ([0] + list(range(nx+1, nx + self._y_axis+1)) + list(range(1, nx+1)) + list(range(nx+1+self._y_axis, nx+ny+1))) y = y.transpose(s) return y def derivative(self, x, der=1): """Evaluate one derivative of the polynomial at the point x Parameters ---------- x : cupy.ndarray Point or points at which to evaluate the derivatives der : integer, optional Which derivative to extract. This number includes the function value as 0th derivative Returns ------- d : cupy.ndarray Derivative interpolated at the x-points. Shape of d is determined by replacing the interpolation axis in the original array with the shape of x Notes ----- This is computed by evaluating all derivatives up to the desired one (using self.derivatives()) and then discarding the rest. """ x, x_shape = self._prepare_x(x) y = self._evaluate_derivatives(x, der+1) return self._finish_y(y[der], x_shape) class BarycentricInterpolator(_Interpolator1D): """The interpolating polynomial for a set of points. Constructs a polynomial that passes through a given set of points. Allows evaluation of the polynomial, efficient changing of the y values to be interpolated, and updating by adding more x values. For reasons of numerical stability, this function does not compute the coefficients of the polynomial. The value `yi` need to be provided before the function is evaluated, but none of the preprocessing depends on them, so rapid updates are possible. Parameters ---------- xi : cupy.ndarray 1-D array of x-coordinates of the points the polynomial should pass through yi : cupy.ndarray, optional The y-coordinates of the points the polynomial should pass through. If None, the y values will be supplied later via the `set_y` method axis : int, optional Axis in the yi array corresponding to the x-coordinate values See Also -------- scipy.interpolate.BarycentricInterpolator """ def __init__(self, xi, yi=None, axis=0): _Interpolator1D.__init__(self, xi, yi, axis) self.xi = xi.astype(cupy.float_) self.set_yi(yi) self.n = len(self.xi) self._inv_capacity = 4.0 / (cupy.max(self.xi) - cupy.min(self.xi)) permute = cupy.random.permutation(self.n) inv_permute = cupy.zeros(self.n, dtype=cupy.int32) inv_permute[permute] = cupy.arange(self.n) self.wi = cupy.zeros(self.n) for i in range(self.n): dist = self._inv_capacity * (self.xi[i] - self.xi[permute]) dist[inv_permute[i]] = 1.0 self.wi[i] = 1.0 / cupy.prod(dist) def set_yi(self, yi, axis=None): """Update the y values to be interpolated. The barycentric interpolation algorithm requires the calculation of weights, but these depend only on the xi. The yi can be changed at any time. Parameters ---------- yi : cupy.ndarray The y-coordinates of the points the polynomial should pass through. If None, the y values will be supplied later. axis : int, optional Axis in the yi array corresponding to the x-coordinate values """ if yi is None: self.yi = None return self._set_yi(yi, xi=self.xi, axis=axis) self.yi = self._reshape_yi(yi) self.n, self.r = self.yi.shape def add_xi(self, xi, yi=None): """Add more x values to the set to be interpolated. The barycentric interpolation algorithm allows easy updating by adding more points for the polynomial to pass through. Parameters ---------- xi : cupy.ndarray The x-coordinates of the points that the polynomial should pass through yi : cupy.ndarray, optional The y-coordinates of the points the polynomial should pass through. Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is vector-valued If `yi` is not given, the y values will be supplied later. `yi` should be given if and only if the interpolator has y values specified """ if yi is not None: if self.yi is None: raise ValueError("No previous yi value to update!") yi = self._reshape_yi(yi, check=True) self.yi = cupy.vstack((self.yi, yi)) else: if self.yi is not None: raise ValueError("No update to yi provided!") old_n = self.n self.xi = cupy.concatenate((self.xi, xi)) self.n = len(self.xi) self.wi **= -1 old_wi = self.wi self.wi = cupy.zeros(self.n) self.wi[:old_n] = old_wi for j in range(old_n, self.n): self.wi[:j] *= self._inv_capacity * (self.xi[j] - self.xi[:j]) self.wi[j] = cupy.prod( self._inv_capacity * (self.xi[:j] - self.xi[j]) ) self.wi **= -1 def __call__(self, x): """Evaluate the interpolating polynomial at the points x. Parameters ---------- x : cupy.ndarray Points to evaluate the interpolant at Returns ------- y : cupy.ndarray Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x Notes ----- Currently the code computes an outer product between x and the weights, that is, it constructs an intermediate array of size N by len(x), where N is the degree of the polynomial. """ return super().__call__(x) def _evaluate(self, x): if x.size == 0: p = cupy.zeros((0, self.r), dtype=self.dtype) else: c = x[..., cupy.newaxis] - self.xi z = c == 0 c[z] = 1 c = self.wi / c p = cupy.dot(c, self.yi) / cupy.sum(c, axis=-1)[..., cupy.newaxis] r = cupy.nonzero(z) if len(r) == 1: # evaluation at a scalar if len(r[0]) > 0: # equals one of the points p = self.yi[r[0][0]] else: p[r[:-1]] = self.yi[r[-1]] return p def barycentric_interpolate(xi, yi, x, axis=0): """Convenience function for polynomial interpolation. Constructs a polynomial that passes through a given set of points, then evaluates the polynomial. For reasons of numerical stability, this function does not compute the coefficients of the polynomial. Parameters ---------- xi : cupy.ndarray 1-D array of coordinates of the points the polynomial should pass through yi : cupy.ndarray y-coordinates of the points the polynomial should pass through x : scalar or cupy.ndarray Points to evaluate the interpolator at axis : int, optional Axis in the yi array corresponding to the x-coordinate values Returns ------- y : scalar or cupy.ndarray Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape x See Also -------- scipy.interpolate.barycentric_interpolate """ return BarycentricInterpolator(xi, yi, axis=axis)(x) class KroghInterpolator(_Interpolator1DWithDerivatives): """Interpolating polynomial for a set of points. The polynomial passes through all the pairs (xi,yi). One may additionally specify a number of derivatives at each point xi; this is done by repeating the value xi and specifying the derivatives as successive yi values Allows evaluation of the polynomial and all its derivatives. For reasons of numerical stability, this function does not compute the coefficients of the polynomial, although they can be obtained by evaluating all the derivatives. Parameters ---------- xi : cupy.ndarray, length N x-coordinate, must be sorted in increasing order yi : cupy.ndarray y-coordinate, when a xi occurs two or more times in a row, the corresponding yi's represent derivative values axis : int, optional Axis in the yi array corresponding to the x-coordinate values. """ def __init__(self, xi, yi, axis=0): _Interpolator1DWithDerivatives.__init__(self, xi, yi, axis) self.xi = xi.astype(cupy.float_) self.yi = self._reshape_yi(yi) self.n, self.r = self.yi.shape c = cupy.zeros((self.n+1, self.r), dtype=self.dtype) c[0] = self.yi[0] Vk = cupy.zeros((self.n, self.r), dtype=self.dtype) for k in range(1, self.n): s = 0 while s <= k and xi[k-s] == xi[k]: s += 1 s -= 1 Vk[0] = self.yi[k]/float_factorial(s) for i in range(k-s): if xi[i] == xi[k]: raise ValueError("Elements if `xi` can't be equal.") if s == 0: Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k]) else: Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k]) c[k] = Vk[k-s] self.c = c def _evaluate(self, x): pi = 1 p = cupy.zeros((len(x), self.r), dtype=self.dtype) p += self.c[0, cupy.newaxis, :] for k in range(1, self.n): w = x - self.xi[k-1] pi = w*pi p += pi[:, cupy.newaxis] * self.c[k] return p def _evaluate_derivatives(self, x, der=None): n = self.n r = self.r if der is None: der = self.n pi = cupy.zeros((n, len(x))) w = cupy.zeros((n, len(x))) pi[0] = 1 p = cupy.zeros((len(x), self.r), dtype=self.dtype) p += self.c[0, cupy.newaxis, :] for k in range(1, n): w[k-1] = x - self.xi[k-1] pi[k] = w[k-1] * pi[k-1] p += pi[k, :, cupy.newaxis] * self.c[k] cn = cupy.zeros((max(der, n+1), len(x), r), dtype=self.dtype) cn[:n+1, :, :] += self.c[:n+1, cupy.newaxis, :] cn[0] = p for k in range(1, n): for i in range(1, n-k+1): pi[i] = w[k+i-1]*pi[i-1] + pi[i] cn[k] = cn[k] + pi[i, :, cupy.newaxis]*cn[k+i] cn[k] *= float_factorial(k) cn[n, :, :] = 0 return cn[:der] def krogh_interpolate(xi, yi, x, der=0, axis=0): """Convenience function for polynomial interpolation Parameters ---------- xi : cupy.ndarray x-coordinate yi : cupy.ndarray y-coordinates, of shape ``(xi.size, R)``. Interpreted as vectors of length R, or scalars if R=1 x : cupy.ndarray Point or points at which to evaluate the derivatives der : int or list, optional How many derivatives to extract; None for all potentially nonzero derivatives (that is a number equal to the number of points), or a list of derivatives to extract. This number includes the function value as 0th derivative axis : int, optional Axis in the yi array corresponding to the x-coordinate values Returns ------- d : cupy.ndarray If the interpolator's values are R-D then the returned array will be the number of derivatives by N by R. If `x` is a scalar, the middle dimension will be dropped; if the `yi` are scalars then the last dimension will be dropped See Also -------- scipy.interpolate.krogh_interpolate """ P = KroghInterpolator(xi, yi, axis=axis) if der == 0: return P(x) elif _isscalar(der): return P.derivative(x, der=der) else: return P.derivatives(x, der=cupy.amax(der)+1)[der]
mit
5dade2fae5a133c8266d34dfae0a5ea2
32.206831
79
0.563886
3.862282
false
false
false
false
cupy/cupy
cupy/array_api/_dtypes.py
1
3706
import cupy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype("int8") int16 = np.dtype("int16") int32 = np.dtype("int32") int64 = np.dtype("int64") uint8 = np.dtype("uint8") uint16 = np.dtype("uint16") uint32 = np.dtype("uint32") uint64 = np.dtype("uint64") float32 = np.dtype("float32") float64 = np.dtype("float64") # Note: This name is changed bool = np.dtype("bool") _all_dtypes = ( int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool, ) _boolean_dtypes = (bool,) _floating_dtypes = (float32, float64) _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) _dtype_categories = { "all": _all_dtypes, "numeric": _numeric_dtypes, "integer": _integer_dtypes, "integer or boolean": _integer_or_boolean_dtypes, "boolean": _boolean_dtypes, "floating-point": _floating_dtypes, } # Note: the spec defines a restricted type promotion table compared to NumPy. # In particular, cross-kind promotions like integer + float or boolean + # integer are not allowed, even for functions that accept both kinds. # Additionally, NumPy promotes signed integer + uint64 to float64, but this # promotion is not allowed here. To be clear, Python scalar int objects are # allowed to promote to floating-point dtypes, but only in array operators # (see Array._promote_scalar) method in _array_object.py. _promotion_table = { (int8, int8): int8, (int8, int16): int16, (int8, int32): int32, (int8, int64): int64, (int16, int8): int16, (int16, int16): int16, (int16, int32): int32, (int16, int64): int64, (int32, int8): int32, (int32, int16): int32, (int32, int32): int32, (int32, int64): int64, (int64, int8): int64, (int64, int16): int64, (int64, int32): int64, (int64, int64): int64, (uint8, uint8): uint8, (uint8, uint16): uint16, (uint8, uint32): uint32, (uint8, uint64): uint64, (uint16, uint8): uint16, (uint16, uint16): uint16, (uint16, uint32): uint32, (uint16, uint64): uint64, (uint32, uint8): uint32, (uint32, uint16): uint32, (uint32, uint32): uint32, (uint32, uint64): uint64, (uint64, uint8): uint64, (uint64, uint16): uint64, (uint64, uint32): uint64, (uint64, uint64): uint64, (int8, uint8): int16, (int8, uint16): int32, (int8, uint32): int64, (int16, uint8): int16, (int16, uint16): int32, (int16, uint32): int64, (int32, uint8): int32, (int32, uint16): int32, (int32, uint32): int64, (int64, uint8): int64, (int64, uint16): int64, (int64, uint32): int64, (uint8, int8): int16, (uint16, int8): int32, (uint32, int8): int64, (uint8, int16): int16, (uint16, int16): int32, (uint32, int16): int64, (uint8, int32): int32, (uint16, int32): int32, (uint32, int32): int64, (uint8, int64): int64, (uint16, int64): int64, (uint32, int64): int64, (float32, float32): float32, (float32, float64): float64, (float64, float32): float64, (float64, float64): float64, (bool, bool): bool, } def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together")
mit
7b94be3d0360729b7843411608cc1ffb
24.916084
77
0.623314
2.84639
false
false
false
false
cupy/cupy
cupy/random/_distributions.py
1
32812
from cupy.random import _generator from cupy import _util # TODO(beam2d): Implement many distributions def beta(a, b, size=None, dtype=float): """Beta distribution. Returns an array of samples drawn from the beta distribution. Its probability density function is defined as .. math:: f(x) = \\frac{x^{\\alpha-1}(1-x)^{\\beta-1}}{B(\\alpha,\\beta)}. Args: a (float): Parameter of the beta distribution :math:`\\alpha`. b (float): Parameter of the beta distribution :math:`\\beta`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the beta distribution. .. seealso:: :func:`numpy.random.beta` """ rs = _generator.get_random_state() return rs.beta(a, b, size, dtype) def binomial(n, p, size=None, dtype=int): """Binomial distribution. Returns an array of samples drawn from the binomial distribution. Its probability mass function is defined as .. math:: f(x) = \\binom{n}{x}p^x(1-p)^{n-x}. Args: n (int): Trial number of the binomial distribution. p (float): Success probability of the binomial distribution. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the binomial distribution. .. seealso:: :func:`numpy.random.binomial` """ rs = _generator.get_random_state() return rs.binomial(n, p, size, dtype) def chisquare(df, size=None, dtype=float): """Chi-square distribution. Returns an array of samples drawn from the chi-square distribution. Its probability density function is defined as .. math:: f(x) = \\frac{(1/2)^{k/2}}{\\Gamma(k/2)}x^{k/2-1}e^{-x/2}. Args: df (int or array_like of ints): Degree of freedom :math:`k`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the chi-square distribution. .. seealso:: :func:`numpy.random.chisquare` """ rs = _generator.get_random_state() return rs.chisquare(df, size, dtype) def dirichlet(alpha, size=None, dtype=float): """Dirichlet distribution. Returns an array of samples drawn from the dirichlet distribution. Its probability density function is defined as .. math:: f(x) = \\frac{\\Gamma(\\sum_{i=1}^K\\alpha_i)} \ {\\prod_{i=1}^{K}\\Gamma(\\alpha_i)} \ \\prod_{i=1}^Kx_i^{\\alpha_i-1}. Args: alpha (array): Parameters of the dirichlet distribution :math:`\\alpha`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the dirichlet distribution. .. seealso:: :func:`numpy.random.dirichlet` """ rs = _generator.get_random_state() return rs.dirichlet(alpha, size, dtype) def exponential(scale, size=None, dtype=float): """Exponential distribution. Returns an array of samples drawn from the exponential distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{\\beta}\\exp (-\\frac{x}{\\beta}). Args: scale (float or array_like of floats): The scale parameter :math:`\\beta`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the exponential distribution. .. seealso:: :func:`numpy.random.exponential` """ rs = _generator.get_random_state() return rs.exponential(scale, size, dtype) def f(dfnum, dfden, size=None, dtype=float): """F distribution. Returns an array of samples drawn from the f distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{B(\\frac{d_1}{2},\\frac{d_2}{2})} \ \\left(\\frac{d_1}{d_2}\\right)^{\\frac{d_1}{2}} \ x^{\\frac{d_1}{2}-1} \ \\left(1+\\frac{d_1}{d_2}x\\right) \ ^{-\\frac{d_1+d_2}{2}}. Args: dfnum (float or array_like of floats): Parameter of the f distribution :math:`d_1`. dfden (float or array_like of floats): Parameter of the f distribution :math:`d_2`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the f distribution. .. seealso:: :func:`numpy.random.f` """ rs = _generator.get_random_state() return rs.f(dfnum, dfden, size, dtype) def gamma(shape, scale=1.0, size=None, dtype=float): """Gamma distribution. Returns an array of samples drawn from the gamma distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{\\Gamma(k)\\theta^k}x^{k-1}e^{-x/\\theta}. Args: shape (array): Parameter of the gamma distribution :math:`k`. scale (array): Parameter of the gamma distribution :math:`\\theta` size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns:cupy.ndarray: Samples drawn from the gamma distribution. .. seealso:: :func:`numpy.random.gamma` """ rs = _generator.get_random_state() return rs.gamma(shape, scale, size, dtype) def geometric(p, size=None, dtype=int): """Geometric distribution. Returns an array of samples drawn from the geometric distribution. Its probability mass function is defined as .. math:: f(x) = p(1-p)^{k-1}. Args: p (float): Success probability of the geometric distribution. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the geometric distribution. .. seealso:: :func:`numpy.random.geometric` """ rs = _generator.get_random_state() return rs.geometric(p, size, dtype) def gumbel(loc=0.0, scale=1.0, size=None, dtype=float): """Returns an array of samples drawn from a Gumbel distribution. The samples are drawn from a Gumbel distribution with location ``loc`` and scale ``scale``. Its probability density function is defined as .. math:: f(x) = \\frac{1}{\\eta} \ \\exp\\left\\{ - \\frac{x - \\mu}{\\eta} \\right\\} \ \\exp\\left[-\\exp\\left\\{-\\frac{x - \\mu}{\\eta} \ \\right\\}\\right], where :math:`\\mu` is ``loc`` and :math:`\\eta` is ``scale``. Args: loc (float): The location of the mode :math:`\\mu`. scale (float): The scale parameter :math:`\\eta`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the Gumbel distribution. .. seealso:: :func:`numpy.random.gumbel` """ rs = _generator.get_random_state() return rs.gumbel(loc, scale, size, dtype) def hypergeometric(ngood, nbad, nsample, size=None, dtype=int): """hypergeometric distribution. Returns an array of samples drawn from the hypergeometric distribution. Its probability mass function is defined as .. math:: f(x) = \\frac{\\binom{m}{n}\\binom{N-m}{n-x}}{\\binom{N}{n}}. Args: ngood (int or array_like of ints): Parameter of the hypergeometric distribution :math:`n`. nbad (int or array_like of ints): Parameter of the hypergeometric distribution :math:`m`. nsample (int or array_like of ints): Parameter of the hypergeometric distribution :math:`N`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the hypergeometric distribution. .. seealso:: :func:`numpy.random.hypergeometric` """ rs = _generator.get_random_state() return rs.hypergeometric(ngood, nbad, nsample, size, dtype) def logistic(loc=0.0, scale=1.0, size=None, dtype=float): """Logistic distribution. Returns an array of samples drawn from the logistic distribution. Its probability density function is defined as .. math:: f(x) = \\frac{e^{-(x-\\mu)/s}}{s(1+e^{-(x-\\mu)/s})^2}. Args: loc (float): The location of the mode :math:`\\mu`. scale (float): The scale parameter :math:`s`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the logistic distribution. .. seealso:: :func:`numpy.random.logistic` """ rs = _generator.get_random_state() return rs.logistic(loc, scale, size, dtype) def laplace(loc=0.0, scale=1.0, size=None, dtype=float): """Laplace distribution. Returns an array of samples drawn from the laplace distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{2b}\\exp\\left(-\\frac{|x-\\mu|}{b}\\right). Args: loc (float): The location of the mode :math:`\\mu`. scale (float): The scale parameter :math:`b`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the laplace distribution. .. seealso:: :func:`numpy.random.laplace` """ rs = _generator.get_random_state() return rs.laplace(loc, scale, size, dtype) def lognormal(mean=0.0, sigma=1.0, size=None, dtype=float): """Returns an array of samples drawn from a log normal distribution. The samples are natural log of samples drawn from a normal distribution with mean ``mean`` and deviation ``sigma``. Args: mean (float): Mean of the normal distribution. sigma (float): Standard deviation of the normal distribution. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the log normal distribution. .. seealso:: :func:`numpy.random.lognormal` """ rs = _generator.get_random_state() return rs.lognormal(mean, sigma, size=size, dtype=dtype) def logseries(p, size=None, dtype=int): """Log series distribution. Returns an array of samples drawn from the log series distribution. Its probability mass function is defined as .. math:: f(x) = \\frac{-p^x}{x\\ln(1-p)}. Args: p (float): Parameter of the log series distribution :math:`p`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the log series distribution. .. seealso:: :func:`numpy.random.logseries` """ rs = _generator.get_random_state() return rs.logseries(p, size=size, dtype=dtype) def negative_binomial(n, p, size=None, dtype=int): """Negative binomial distribution. Returns an array of samples drawn from the negative binomial distribution. Its probability mass function is defined as .. math:: f(x) = \\binom{x + n - 1}{n - 1}p^n(1-p)^{x}. Args: n (int): Parameter of the negative binomial distribution :math:`n`. p (float): Parameter of the negative binomial distribution :math:`p`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the negative binomial distribution. .. seealso:: :func:`numpy.random.negative_binomial` """ rs = _generator.get_random_state() return rs.negative_binomial(n, p, size=size, dtype=dtype) def multivariate_normal(mean, cov, size=None, check_valid='ignore', tol=1e-08, method='cholesky', dtype=float): """Multivariate normal distribution. Returns an array of samples drawn from the multivariate normal distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{(2\\pi|\\Sigma|)^(n/2)} \ \\exp\\left(-\\frac{1}{2} \ (x-\\mu)^{\\top}\\Sigma^{-1}(x-\\mu)\\right). Args: mean (1-D array_like, of length N): Mean of the multivariate normal distribution :math:`\\mu`. cov (2-D array_like, of shape (N, N)): Covariance matrix :math:`\\Sigma` of the multivariate normal distribution. It must be symmetric and positive-semidefinite for proper sampling. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. check_valid ('warn', 'raise', 'ignore'): Behavior when the covariance matrix is not positive semidefinite. tol (float): Tolerance when checking the singular values in covariance matrix. method : { 'cholesky', 'eigh', 'svd'}, optional The cov input is used to compute a factor matrix A such that ``A @ A.T = cov``. This argument is used to select the method used to compute the factor matrix A. The default method 'cholesky' is the fastest, while 'svd' is the slowest but more robust than the fastest method. The method `eigh` uses eigen decomposition to compute A and is faster than svd but slower than cholesky. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the multivariate normal distribution. .. note:: Default `method` is set to fastest, 'cholesky', unlike numpy which defaults to 'svd'. Cholesky decomposition in CuPy will fail silently if the input covariance matrix is not positive definite and give invalid results, unlike in numpy, where an invalid covariance matrix will raise an exception. Setting `check_valid` to 'raise' will replicate numpy behavior by checking the input, but will also force device synchronization. If validity of input is unknown, setting `method` to 'einh' or 'svd' and `check_valid` to 'warn' will use cholesky decomposition for positive definite matrices, and fallback to the specified `method` for other matrices (i.e., not positive semi-definite), and will warn if decomposition is suspect. .. seealso:: :func:`numpy.random.multivariate_normal` """ _util.experimental('cupy.random.multivariate_normal') rs = _generator.get_random_state() return rs.multivariate_normal( mean, cov, size, check_valid, tol, method, dtype) def normal(loc=0.0, scale=1.0, size=None, dtype=float): """Returns an array of normally distributed samples. Args: loc (float or array_like of floats): Mean of the normal distribution. scale (float or array_like of floats): Standard deviation of the normal distribution. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Normally distributed samples. .. seealso:: :func:`numpy.random.normal` """ rs = _generator.get_random_state() return rs.normal(loc, scale, size, dtype) def pareto(a, size=None, dtype=float): """Pareto II or Lomax distribution. Returns an array of samples drawn from the Pareto II distribution. Its probability density function is defined as .. math:: f(x) = \\alpha(1+x)^{-(\\alpha+1)}. Args: a (float or array_like of floats): Parameter of the Pareto II distribution :math:`\\alpha`. size (int or tuple of ints): The shape of the array. If ``None``, this function generate an array whose shape is `a.shape`. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the Pareto II distribution. .. seealso:: :func:`numpy.random.pareto` """ rs = _generator.get_random_state() return rs.pareto(a, size, dtype) def noncentral_chisquare(df, nonc, size=None, dtype=float): """Noncentral chisquare distribution. Returns an array of samples drawn from the noncentral chisquare distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{2}e^{-(x+\\lambda)/2} \\ \\left(\\frac{x}{\\lambda}\\right)^{k/4 - 1/2} \\ I_{k/2 - 1}(\\sqrt{\\lambda x}), where :math:`I` is the modified Bessel function of the first kind. Args: df (float): Parameter of the noncentral chisquare distribution :math:`k`. nonc (float): Parameter of the noncentral chisquare distribution :math:`\\lambda`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the noncentral chisquare distribution. .. seealso:: :func:`numpy.random.noncentral_chisquare` """ rs = _generator.get_random_state() return rs.noncentral_chisquare(df, nonc, size=size, dtype=dtype) def noncentral_f(dfnum, dfden, nonc, size=None, dtype=float): """Noncentral F distribution. Returns an array of samples drawn from the noncentral F distribution. Reference: https://en.wikipedia.org/wiki/Noncentral_F-distribution Args: dfnum (float): Parameter of the noncentral F distribution. dfden (float): Parameter of the noncentral F distribution. nonc (float): Parameter of the noncentral F distribution. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the noncentral F distribution. .. seealso:: :func:`numpy.random.noncentral_f` """ rs = _generator.get_random_state() return rs.noncentral_f(dfnum, dfden, nonc, size=size, dtype=dtype) def poisson(lam=1.0, size=None, dtype=int): """Poisson distribution. Returns an array of samples drawn from the poisson distribution. Its probability mass function is defined as .. math:: f(x) = \\frac{\\lambda^xe^{-\\lambda}}{k!}. Args: lam (array_like of floats): Parameter of the poisson distribution :math:`\\lambda`. size (int or tuple of ints): The shape of the array. If ``None``, this function generate an array whose shape is `lam.shape`. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the poisson distribution. .. seealso:: :func:`numpy.random.poisson` """ rs = _generator.get_random_state() return rs.poisson(lam, size, dtype) def power(a, size=None, dtype=float): """Power distribution. Returns an array of samples drawn from the power distribution. Its probability density function is defined as .. math:: f(x) = ax^{a-1}. Args: a (float): Parameter of the power distribution :math:`a`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the power distribution. .. seealso:: :func:`numpy.random.power` """ rs = _generator.get_random_state() return rs.power(a, size, dtype) def rayleigh(scale=1.0, size=None, dtype=float): """Rayleigh distribution. Returns an array of samples drawn from the rayleigh distribution. Its probability density function is defined as .. math:: f(x) = \\frac{x}{\\sigma^2}e^{\\frac{-x^2}{2-\\sigma^2}}, x \\ge 0. Args: scale (array): Parameter of the rayleigh distribution :math:`\\sigma`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the rayleigh distribution. .. seealso:: :func:`numpy.random.rayleigh` """ rs = _generator.get_random_state() return rs.rayleigh(scale, size, dtype) def standard_cauchy(size=None, dtype=float): """Standard cauchy distribution. Returns an array of samples drawn from the standard cauchy distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{\\pi(1+x^2)}. Args: size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the standard cauchy distribution. .. seealso:: :func:`numpy.random.standard_cauchy` """ rs = _generator.get_random_state() return rs.standard_cauchy(size, dtype) def standard_exponential(size=None, dtype=float): """Standard exponential distribution. Returns an array of samples drawn from the standard exponential distribution. Its probability density function is defined as .. math:: f(x) = e^{-x}. Args: size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the standard exponential distribution. .. seealso:: :func:`numpy.random.standard_exponential` """ rs = _generator.get_random_state() return rs.standard_exponential(size, dtype) def standard_gamma(shape, size=None, dtype=float): """Standard gamma distribution. Returns an array of samples drawn from the standard gamma distribution. Its probability density function is defined as .. math:: f(x) = \\frac{1}{\\Gamma(k)}x^{k-1}e^{-x}. Args: shape (array): Parameter of the gamma distribution :math:`k`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the standard gamma distribution. .. seealso:: :func:`numpy.random.standard_gamma` """ rs = _generator.get_random_state() return rs.standard_gamma(shape, size, dtype) def standard_normal(size=None, dtype=float): """Returns an array of samples drawn from the standard normal distribution. This is a variant of :func:`cupy.random.randn`. Args: size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Returns: cupy.ndarray: Samples drawn from the standard normal distribution. .. seealso:: :func:`numpy.random.standard_normal` """ rs = _generator.get_random_state() return rs.standard_normal(size, dtype) def standard_t(df, size=None, dtype=float): """Standard Student's t distribution. Returns an array of samples drawn from the standard Student's t distribution. Its probability density function is defined as .. math:: f(x) = \\frac{\\Gamma(\\frac{\\nu+1}{2})} \ {\\sqrt{\\nu\\pi}\\Gamma(\\frac{\\nu}{2})} \ \\left(1 + \\frac{x^2}{\\nu} \\right)^{-(\\frac{\\nu+1}{2})}. Args: df (float or array_like of floats): Degree of freedom :math:`\\nu`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the standard Student's t distribution. .. seealso:: :func:`numpy.random.standard_t` """ rs = _generator.get_random_state() return rs.standard_t(df, size, dtype) def triangular(left, mode, right, size=None, dtype=float): """Triangular distribution. Returns an array of samples drawn from the triangular distribution. Its probability density function is defined as .. math:: f(x) = \\begin{cases} \\frac{2(x-l)}{(r-l)(m-l)} & \\text{for } l \\leq x \\leq m, \\\\ \\frac{2(r-x)}{(r-l)(r-m)} & \\text{for } m \\leq x \\leq r, \\\\ 0 & \\text{otherwise}. \\end{cases} Args: left (float): Lower limit :math:`l`. mode (float): The value where the peak of the distribution occurs. :math:`m`. right (float): Higher Limit :math:`r`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the triangular distribution. .. seealso:: :func:`numpy.random.triangular` """ rs = _generator.get_random_state() return rs.triangular(left, mode, right, size, dtype) def uniform(low=0.0, high=1.0, size=None, dtype=float): """Returns an array of uniformly-distributed samples over an interval. Samples are drawn from a uniform distribution over the half-open interval ``[low, high)``. The samples may contain the ``high`` limit due to floating-point rounding. Args: low (float): Lower end of the interval. high (float): Upper end of the interval. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Returns: cupy.ndarray: Samples drawn from the uniform distribution. .. seealso:: :func:`numpy.random.uniform` """ rs = _generator.get_random_state() return rs.uniform(low, high, size=size, dtype=dtype) def vonmises(mu, kappa, size=None, dtype=float): """von Mises distribution. Returns an array of samples drawn from the von Mises distribution. Its probability density function is defined as .. math:: f(x) = \\frac{e^{\\kappa \\cos(x-\\mu)}}{2\\pi I_0(\\kappa)}. Args: mu (float): Parameter of the von Mises distribution :math:`\\mu`. kappa (float): Parameter of the von Mises distribution :math:`\\kappa`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the von Mises distribution. .. seealso:: :func:`numpy.random.vonmises` """ rs = _generator.get_random_state() return rs.vonmises(mu, kappa, size=size, dtype=dtype) def wald(mean, scale, size=None, dtype=float): """Wald distribution. Returns an array of samples drawn from the Wald distribution. Its probability density function is defined as .. math:: f(x) = \\sqrt{\\frac{\\lambda}{2\\pi x^3}}\\ e^{\\frac{-\\lambda(x-\\mu)^2}{2\\mu^2x}}. Args: mean (float): Parameter of the wald distribution :math:`\\mu`. scale (float): Parameter of the wald distribution :math:`\\lambda`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the wald distribution. .. seealso:: :func:`numpy.random.wald` """ rs = _generator.get_random_state() return rs.wald(mean, scale, size, dtype) def weibull(a, size=None, dtype=float): """weibull distribution. Returns an array of samples drawn from the weibull distribution. Its probability density function is defined as .. math:: f(x) = ax^{(a-1)}e^{-x^a}. Args: a (float): Parameter of the weibull distribution :math:`a`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.float32` and :class:`numpy.float64` types are allowed. Returns: cupy.ndarray: Samples drawn from the weibull distribution. .. seealso:: :func:`numpy.random.weibull` """ rs = _generator.get_random_state() return rs.weibull(a, size=size, dtype=dtype) def zipf(a, size=None, dtype=int): """Zipf distribution. Returns an array of samples drawn from the Zipf distribution. Its probability mass function is defined as .. math:: f(x) = \\frac{x^{-a}}{ \\zeta (a)}, where :math:`\\zeta` is the Riemann Zeta function. Args: a (float): Parameter of the beta distribution :math:`a`. size (int or tuple of ints): The shape of the array. If ``None``, a zero-dimensional array is generated. dtype: Data type specifier. Only :class:`numpy.int32` and :class:`numpy.int64` types are allowed. Returns: cupy.ndarray: Samples drawn from the Zipf distribution. .. seealso:: :func:`numpy.random.zipf` """ rs = _generator.get_random_state() return rs.zipf(a, size=size, dtype=dtype)
mit
f61e584b8a71f45a996be04350da66ba
33.466387
79
0.626356
3.880322
false
false
false
false
cupy/cupy
cupy/_math/trigonometric.py
1
4308
import numpy import cupy from cupy import _core from cupy._math import sumprod from cupy._math import ufunc sin = ufunc.create_math_ufunc( 'sin', 1, 'cupy_sin', '''Elementwise sine function. .. seealso:: :data:`numpy.sin` ''') cos = ufunc.create_math_ufunc( 'cos', 1, 'cupy_cos', '''Elementwise cosine function. .. seealso:: :data:`numpy.cos` ''') tan = ufunc.create_math_ufunc( 'tan', 1, 'cupy_tan', '''Elementwise tangent function. .. seealso:: :data:`numpy.tan` ''') arcsin = ufunc.create_math_ufunc( 'asin', 1, 'cupy_arcsin', '''Elementwise inverse-sine function (a.k.a. arcsine function). .. seealso:: :data:`numpy.arcsin` ''') arccos = ufunc.create_math_ufunc( 'acos', 1, 'cupy_arccos', '''Elementwise inverse-cosine function (a.k.a. arccosine function). .. seealso:: :data:`numpy.arccos` ''') arctan = ufunc.create_math_ufunc( 'atan', 1, 'cupy_arctan', '''Elementwise inverse-tangent function (a.k.a. arctangent function). .. seealso:: :data:`numpy.arctan` ''') hypot = ufunc.create_math_ufunc( 'hypot', 2, 'cupy_hypot', '''Computes the hypoteneous of orthogonal vectors of given length. This is equivalent to ``sqrt(x1 **2 + x2 ** 2)``, while this function is more efficient. .. seealso:: :data:`numpy.hypot` ''') arctan2 = ufunc.create_math_ufunc( 'atan2', 2, 'cupy_arctan2', '''Elementwise inverse-tangent of the ratio of two arrays. .. seealso:: :data:`numpy.arctan2` ''') deg2rad = _core.create_ufunc( 'cupy_deg2rad', ('e->e', 'f->f', 'd->d'), 'out0 = in0 * (out0_type)(M_PI / 180)', doc='''Converts angles from degrees to radians elementwise. .. seealso:: :data:`numpy.deg2rad`, :data:`numpy.radians` ''') rad2deg = _core.create_ufunc( 'cupy_rad2deg', ('e->e', 'f->f', 'd->d'), 'out0 = in0 * (out0_type)(180 / M_PI)', doc='''Converts angles from radians to degrees elementwise. .. seealso:: :data:`numpy.rad2deg`, :data:`numpy.degrees` ''') def unwrap(p, discont=None, axis=-1, *, period=2*numpy.pi): r"""Unwrap by taking the complement of large deltas w.r.t. the period. This unwraps a signal `p` by changing elements which have an absolute difference from their predecessor of more than ``max(discont, period/2)`` to their `period`-complementary values. For the default case where `period` is :math:`2\pi` and is ``discont`` is :math:`\pi`, this unwraps a radian phase `p` such that adjacent differences are never greater than :math:`\pi` by adding :math:`2k\pi` for some integer :math:`k`. Args: p (cupy.ndarray): Input array. discont (float): Maximum discontinuity between values, default is ``period/2``. Values below ``period/2`` are treated as if they were ``period/2``. To have an effect different from the default, ``discont`` should be larger than ``period/2``. axis (int): Axis along which unwrap will operate, default is the last axis. period: float, optional Size of the range over which the input wraps. By default, it is :math:`2\pi`. Returns: cupy.ndarray: The result array. .. seealso:: :func:`numpy.unwrap` """ p = cupy.asarray(p) nd = p.ndim dd = sumprod.diff(p, axis=axis) if discont is None: discont = period/2 slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) slice1 = tuple(slice1) dtype = numpy.result_type(dd.dtype, period) if numpy.issubdtype(dtype, numpy.integer): interval_high, rem = divmod(period, 2) boundary_ambiguous = rem == 0 else: interval_high = period / 2 boundary_ambiguous = True interval_low = -interval_high ddmod = cupy.mod(dd - interval_low, period) + interval_low if boundary_ambiguous: cupy.copyto(ddmod, interval_high, where=( ddmod == interval_low) & (dd > 0)) ph_correct = ddmod - dd cupy.copyto(ph_correct, 0, where=abs(dd) < discont) up = cupy.array(p, copy=True, dtype=dtype) up[slice1] = p[slice1] + cupy.cumsum(ph_correct, axis=axis) return up degrees = rad2deg radians = deg2rad
mit
60116482bf6d2d0f0317923f142ff0c4
25.429448
79
0.611885
3.311299
false
false
false
false
cupy/cupy
cupy/array_api/_set_functions.py
1
2947
from __future__ import annotations from ._array_object import Array from typing import NamedTuple import cupy as np # Note: np.unique() is split into four functions in the array API: # unique_all, unique_counts, unique_inverse, and unique_values (this is done # to remove polymorphic return types). # Note: The various unique() functions are supposed to return multiple NaNs. # This does not match the NumPy behavior, however, this is currently left as a # TODO in this implementation as this behavior may be reverted in np.unique(). # See https://github.com/numpy/numpy/issues/20326. # Note: The functions here return a namedtuple (np.unique() returns a normal # tuple). class UniqueAllResult(NamedTuple): values: Array indices: Array inverse_indices: Array counts: Array class UniqueCountsResult(NamedTuple): values: Array counts: Array class UniqueInverseResult(NamedTuple): values: Array inverse_indices: Array def unique_all(x: Array, /) -> UniqueAllResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, indices, inverse_indices, counts = np.unique( x._array, return_counts=True, return_index=True, return_inverse=True, equal_nan=False, ) # np.unique() flattens inverse indices, but they need to share x's shape # See https://github.com/numpy/numpy/issues/20638 inverse_indices = inverse_indices.reshape(x.shape) return UniqueAllResult( Array._new(values), Array._new(indices), Array._new(inverse_indices), Array._new(counts), ) def unique_counts(x: Array, /) -> UniqueCountsResult: res = np.unique( x._array, return_counts=True, return_index=False, return_inverse=False, equal_nan=False, ) return UniqueCountsResult(*[Array._new(i) for i in res]) def unique_inverse(x: Array, /) -> UniqueInverseResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, inverse_indices = np.unique( x._array, return_counts=False, return_index=False, return_inverse=True, equal_nan=False, ) # np.unique() flattens inverse indices, but they need to share x's shape # See https://github.com/numpy/numpy/issues/20638 inverse_indices = inverse_indices.reshape(x.shape) return UniqueInverseResult(Array._new(values), Array._new(inverse_indices)) def unique_values(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ res = np.unique( x._array, return_counts=False, return_index=False, return_inverse=False, equal_nan=False, ) return Array._new(res)
mit
1ca59c197724511a52179404a9e353e9
26.801887
79
0.663047
3.842243
false
false
false
false
cupy/cupy
cupyx/scipy/sparse/_sputils.py
1
5555
import cupy import operator import numpy from cupy._core._dtype import get_dtype supported_dtypes = [get_dtype(x) for x in ('single', 'double', 'csingle', 'cdouble')] _upcast_memo: dict = {} def isdense(x): return isinstance(x, cupy.ndarray) def isscalarlike(x): """Is x either a scalar, an array scalar, or a 0-dim array?""" return cupy.isscalar(x) or (isdense(x) and x.ndim == 0) def get_index_dtype(arrays=(), maxval=None, check_contents=False): """Based on input (integer) arrays ``a``, determines a suitable index data type that can hold the data in the arrays. Args: arrays (tuple of array_like): Input arrays whose types/contents to check maxval (float, optional): Maximum value needed check_contents (bool, optional): Whether to check the values in the arrays and not just their types. Default: False (check only the types) Returns: dtype: Suitable index data type (int32 or int64) """ int32min = cupy.iinfo(cupy.int32).min int32max = cupy.iinfo(cupy.int32).max dtype = cupy.int32 if maxval is not None: if maxval > int32max: dtype = cupy.int64 if isinstance(arrays, cupy.ndarray): arrays = (arrays,) for arr in arrays: arr = cupy.asarray(arr) if not cupy.can_cast(arr.dtype, cupy.int32): if check_contents: if arr.size == 0: # a bigger type not needed continue elif cupy.issubdtype(arr.dtype, cupy.integer): maxval = arr.max() minval = arr.min() if minval >= int32min and maxval <= int32max: # a bigger type not needed continue dtype = cupy.int64 break return dtype def validateaxis(axis): if axis is not None: axis_type = type(axis) # In NumPy, you can pass in tuples for 'axis', but they are # not very useful for sparse matrices given their limited # dimensions, so let's make it explicit that they are not # allowed to be passed in if axis_type == tuple: raise TypeError(("Tuples are not accepted for the 'axis' " "parameter. Please pass in one of the " "following: {-2, -1, 0, 1, None}.")) # If not a tuple, check that the provided axis is actually # an integer and raise a TypeError similar to NumPy's if not cupy.issubdtype(cupy.dtype(axis_type), cupy.integer): raise TypeError("axis must be an integer, not {name}" .format(name=axis_type.__name__)) if not (-2 <= axis <= 1): raise ValueError("axis out of range") def upcast(*args): """Returns the nearest supported sparse dtype for the combination of one or more types. upcast(t0, t1, ..., tn) -> T where T is a supported dtype Examples: >>> upcast('int32') <type 'numpy.int32'> >>> upcast('int32','float32') <type 'numpy.float64'> >>> upcast('bool',float) <type 'numpy.complex128'> """ t = _upcast_memo.get(args) if t is not None: return t upcast = cupy.find_common_type(args, []) for t in supported_dtypes: if cupy.can_cast(upcast, t): _upcast_memo[args] = t return t raise TypeError('no supported conversion for types: %r' % (args,)) def check_shape(args, current_shape=None): """Check validity of the shape""" if len(args) == 0: raise TypeError("function missing 1 required positional argument: " "'shape'") elif len(args) == 1: try: shape_iter = iter(args[0]) except TypeError: new_shape = (operator.index(args[0]), ) else: new_shape = tuple(operator.index(arg) for arg in shape_iter) else: new_shape = tuple(operator.index(arg) for arg in args) if current_shape is None: if len(new_shape) != 2: raise ValueError('shape must be a 2-tuple of positive integers') elif new_shape[0] < 0 or new_shape[1] < 0: raise ValueError("'shape' elements cannot be negative") else: current_size = numpy.prod(current_shape) negative_indexes = [i for i, x in enumerate(new_shape) if x < 0] if len(negative_indexes) == 0: new_size = numpy.prod(new_shape) if new_size != current_size: raise ValueError('cannot reshape array of size {} into shape' '{}'.format(current_size, new_shape)) elif len(negative_indexes) == 1: skip = negative_indexes[0] specified = numpy.prod(new_shape[0:skip] + new_shape[skip+1:]) unspecified, remainder = divmod(current_size, specified) if remainder != 0: err_shape = tuple('newshape'if x < 0 else x for x in new_shape) raise ValueError('cannot reshape array of size {} into shape' '{}'.format(current_size, err_shape)) new_shape = new_shape[0:skip] + (unspecified,) + new_shape[skip+1:] else: raise ValueError('can only specify one unknown dimension') if len(new_shape) != 2: raise ValueError('matrix shape must be two-dimensional') return new_shape
mit
701f768aba0095e33ec12ef56dda9b94
31.869822
79
0.563276
4.022448
false
false
false
false
landlab/landlab
landlab/components/flow_director/flow_director_steepest.py
3
26741
#! /usr/env/python """ flow_director_steepest.py: provides the component FlowDirectorSteepest. This components finds the steepest single-path steepest descent flow directions. It is equivalent to D4 method in the special case of a raster grid in that it does not consider diagonal links between nodes. For that capability, use FlowDirectorD8. """ import numpy as np from landlab import NodeStatus, VoronoiDelaunayGrid from landlab.components.flow_director import flow_direction_DN from landlab.components.flow_director.flow_director_to_one import _FlowDirectorToOne class FlowDirectorSteepest(_FlowDirectorToOne): """Single-path (steepest direction) flow direction without diagonals. This components finds the steepest single-path steepest descent flow directions. It is equivalent to D4 method in the special case of a raster grid in that it does not consider diagonal links between nodes. For that capability, use FlowDirectorD8. Stores as ModelGrid fields: - Node array of receivers (nodes that receive flow), or ITS OWN ID if there is no receiver: *'flow__receiver_node'* - Node array of steepest downhill slopes: *'topographic__steepest_slope'* - Node array containing ID of link that leads from each node to its receiver, or grid.BAD_INDEX if no link: *'flow__link_to_receiver_node'* - Boolean node array of all local lows: *'flow__sink_flag'* - Link array identifing if flow goes with (1) or against (-1) the link direction: *'flow__link_direction'* The primary method of this class is :func:`run_one_step`. Examples -------- This method works for both raster and irregular grids. First we will look at a raster example, and then an irregular example. >>> import numpy as np >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3), xy_spacing=(1, 1)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.surface_values array([ 0., 1., 2., 1., 2., 3., 2., 3., 4.]) >>> fd.run_one_step() >>> mg.at_node['flow__receiver_node'] array([0, 1, 2, 3, 1, 5, 6, 7, 8]) >>> mg.at_node['topographic__steepest_slope'] array([ 0., 0., 0., 0., 1., 0., 0., 0., 0.]) >>> mg.at_node['flow__link_to_receiver_node'] array([-1, -1, -1, -1, 3, -1, -1, -1, -1]) >>> mg.at_node['flow__sink_flag'].astype(int) array([1, 1, 1, 1, 0, 1, 1, 1, 1]) >>> mg_2 = RasterModelGrid((5, 4), xy_spacing=(1, 1)) >>> topographic__elevation = np.array([0., 0., 0., 0., ... 0., 21., 10., 0., ... 0., 31., 20., 0., ... 0., 32., 30., 0., ... 0., 0., 0., 0.]) >>> _ = mg_2.add_field( ... "topographic__elevation", ... topographic__elevation, ... at="node", ... ) >>> mg_2.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> fd_2 = FlowDirectorSteepest(mg_2) >>> fd_2.run_one_step() >>> mg_2.at_node['flow__receiver_node'] # doctest: +NORMALIZE_WHITESPACE array([ 0, 1, 2, 3, 4, 1, 2, 7, 8, 10, 6, 11, 12, 14, 10, 15, 16, 17, 18, 19]) And the at-link field ``'flow__link_direction'`` indicates if the flow along the link is with or against the direction indicated by ``'link_dirs_at_node'`` (from tail node to head node). >>> mg_2.at_link['flow__link_direction'] array([ 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int8) This indicates that flow on links 4, 5, 12, and 19 goes against the topologic ordering -- that is that flow goes from head node to tail node -- and that flow goes with the topologic ordering on links 15 and 22. All other links have no flow on them. The FlowDirectorSteepest attribute ``flow_link_direction_at_node`` indicates the link flow direction (with or against topology directions) for all links at node. The ordering of links at node mirrors the grid attribute ``links_at_node``. >>> fd_2.flow_link_direction_at_node() array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, -1, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 1, 0, 0, 0], [ 0, -1, 1, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 1, 0, 0, 0], [ 0, 0, 1, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) For example, this indicates that node 10 has flow going along three links that are attached to it. The link to the East has no flow, the link to the North has flow going against the topologic direction, the link to the West has flow going with the topologic direction, and the link to the South has flow going against the topologic direction. In many use cases, one might want to know which links are bringing flow into or out of the node. The flow director attribute ``flow_link_incoming_at_node`` provides this information. Here -1 means that flow is outgoing from the node and 1 means it is incoming. >>> fd_2.flow_link_incoming_at_node() array([[ 0, 0, 0, 0], [ 0, 1, 0, 0], [ 0, 1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 1, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [-1, 0, 0, 0], [ 0, 1, 1, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [-1, 0, 0, 0], [ 0, 0, 1, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) So if one wanted to identify the source nodes at node, you would do the following: >>> np.where(fd_2.flow_link_incoming_at_node() == 1, mg_2.adjacent_nodes_at_node, -1) array([[-1, -1, -1, -1], [-1, 5, -1, -1], [-1, 6, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, 10, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, 14, 9, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, 13, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]) The flow directors also have the ability to return the flow receiver nodes >>> receiver = fd.direct_flow() >>> receiver array([0, 1, 2, 3, 1, 5, 6, 7, 8]) For the second example we will use a Hexagonal Model Grid, a special type of Voroni Grid that has regularly spaced hexagonal cells. >>> from landlab import HexModelGrid >>> mg = HexModelGrid((5, 3)) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + np.round(mg.node_y), ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.surface_values array([ 1. , 2. , 3. , 1.5, 2.5, 3.5, 4.5, 2. , 3. , 4. , 5. , 6. , 3.5, 4.5, 5.5, 6.5, 4. , 5. , 6. ]) >>> fd.run_one_step() >>> mg.at_node['flow__receiver_node'] array([ 0, 1, 2, 3, 0, 1, 6, 7, 3, 4, 5, 11, 12, 8, 9, 15, 16, 17, 18]) >>> mg.at_node['topographic__steepest_slope'] array([ 0. , 0. , 0. , 0. , 1.5, 1.5, 0. , 0. , 1.5, 1.5, 1.5, 0. , 0. , 1.5, 1.5, 0. , 0. , 0. , 0. ]) >>> mg.at_node['flow__link_to_receiver_node'] array([-1, -1, -1, -1, 3, 5, -1, -1, 12, 14, 16, -1, -1, 25, 27, -1, -1, -1, -1]) >>> mg.at_node['flow__sink_flag'].astype(int) array([1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1]) >>> receiver = fd.direct_flow() >>> receiver array([ 0, 1, 2, 3, 0, 1, 6, 7, 3, 4, 5, 11, 12, 8, 9, 15, 16, 17, 18]) References ---------- **Required Software Citation(s) Specific to this Component** None Listed **Additional References** None Listed """ _name = "FlowDirectorSteepest" _unit_agnostic = True _info = { "flow__link_direction": { "dtype": np.int8, "intent": "out", "optional": False, "units": "-", "mapping": "link", "doc": "Direction of flow on link. A value of -1 indicates that water flow goes from head node to tail node, while a value of 1 indicates that water flow goes from tail node to head node.", }, "flow__link_to_receiver_node": { "dtype": int, "intent": "out", "optional": False, "units": "-", "mapping": "node", "doc": "ID of link downstream of each node, which carries the discharge", }, "flow__receiver_node": { "dtype": int, "intent": "out", "optional": False, "units": "-", "mapping": "node", "doc": "Node array of receivers (node that receives flow from current node)", }, "flow__sink_flag": { "dtype": bool, "intent": "out", "optional": False, "units": "-", "mapping": "node", "doc": "Boolean array, True at local lows", }, "topographic__elevation": { "dtype": float, "intent": "in", "optional": True, "units": "m", "mapping": "node", "doc": "Land surface topographic elevation", }, "topographic__steepest_slope": { "dtype": float, "intent": "out", "optional": False, "units": "-", "mapping": "node", "doc": "The steepest *downhill* slope", }, } def __init__(self, grid, surface="topographic__elevation"): """ Parameters ---------- grid : ModelGrid A grid. surface : field name at node or array of length node, optional The surface to direct flow across, default is field at node: topographic__elevation,. """ self._method = "D4" super().__init__(grid, surface) self._is_Voroni = isinstance(self._grid, VoronoiDelaunayGrid) # get 'flow__link_direction' field self._flow_link_direction = grid.at_link["flow__link_direction"] self.updated_boundary_conditions() def updated_boundary_conditions(self): """Method to update FlowDirectorSteepest when boundary conditions change. Call this if boundary conditions on the grid are updated after the component is instantiated. """ self._active_links = self._grid.active_links self._activelink_tail = self._grid.node_at_link_tail[self._grid.active_links] self._activelink_head = self._grid.node_at_link_head[self._grid.active_links] def run_one_step(self): """Find flow directions and save to the model grid. run_one_step() checks for updated boundary conditions, calculates slopes on links, finds baselevel nodes based on the status at node, calculates flow directions, and saves results to the grid. An alternative to direct_flow() is run_one_step() which does the same things but also returns the receiver nodes not return values. """ self.direct_flow() def direct_flow(self): """Find flow directions, save to the model grid, and return receivers. direct_flow() checks for updated boundary conditions, calculates slopes on links, finds baselevel nodes based on the status at node, calculates flow directions, saves results to the grid, and returns a at-node array of receiver nodes. This array is stored in the grid at: grid['node']['flow__receiver_node'] An alternative to direct_flow() is run_one_step() which does the same things but also returns a at-node array of receiver nodes. This array is stored in the grid at: grid['node']['flow__receiver_node'] """ self._check_updated_bc() # update the surface, if it was provided as a model grid field. self._changed_surface() # step 1. Calculate link slopes at active links only. all_grads = -self._grid.calc_grad_at_link(self._surface_values) link_slope = all_grads[self._grid.active_links] # Step 2. Find and save base level nodes. (baselevel_nodes,) = np.where( np.logical_or( self._grid.status_at_node == NodeStatus.FIXED_VALUE, self._grid.status_at_node == NodeStatus.FIXED_GRADIENT, ) ) # Calculate flow directions receiver, steepest_slope, sink, recvr_link = flow_direction_DN.flow_directions( self._surface_values, self._active_links, self._activelink_tail, self._activelink_head, link_slope, grid=self._grid, baselevel_nodes=baselevel_nodes, ) # Save the four ouputs of this component. self._grid["node"]["flow__receiver_node"][:] = receiver self._grid["node"]["topographic__steepest_slope"][:] = steepest_slope self._grid["node"]["flow__link_to_receiver_node"][:] = recvr_link self._grid["node"]["flow__sink_flag"][:] = np.zeros_like(receiver, dtype=bool) self._grid["node"]["flow__sink_flag"][sink] = True # determine link directions self._determine_link_directions() return receiver def _determine_link_directions(self): """Determine link directions and set flow_link_direction field. This routine is slightly different between the route-to-one and route-to-many methods. It works when DepressionFinderAndRouter is run. """ # start by re-setting all links to zero. self._flow_link_direction[:] = 0 # identify where flow is active on links is_active_flow_link = self._links_to_receiver != self._grid.BAD_INDEX # make an array that says which link ID is active active_flow_links = self._links_to_receiver[is_active_flow_link] # for each of those links, the position is the upstream node upstream_node_of_active_flow_link = np.where(is_active_flow_link)[0] # get the head node head_node_at_active_flow_link = self._grid.node_at_link_head[active_flow_links] # if head node is upstream node = -1, else 1 self._flow_link_direction[ active_flow_links[ head_node_at_active_flow_link == upstream_node_of_active_flow_link ] ] = -1 self._flow_link_direction[ active_flow_links[ head_node_at_active_flow_link != upstream_node_of_active_flow_link ] ] = 1 def flow_link_direction_at_node(self): """Return array of flow link direction at node. This property mirrors links_at_node and indicates the relationship between the flow direction (determined based on the elevation of nodes) and the topologic link direction (in which the head and tail nodes are defined based on relative position in x-y space). It has the shape (number of nodes, maximum number of links at node). Recall that the standard landlab link direction goes from the tail node to the head node. A value of zero indicates that the link does not exist or is not active. A value of -1 indicates that water flow based on ``flow__link_to_receiver_node`` goes from head node to tail node, while a value of 1 indicates that water flow goes from tail node to head node. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.run_one_step() >>> fd.flow_link_direction_at_node() array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) This method will be updated when the DepressionFinderAndRouter is run. First, without DepressionFinderAndRouter: >>> from landlab.components import FlowAccumulator >>> mg1 = RasterModelGrid((5, 5)) >>> z1 = mg1.add_field( ... "topographic__elevation", ... mg1.x_of_node+2 * mg1.y_of_node, ... at="node", ... ) >>> z1[12] -= 5 >>> mg1.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> fa1 = FlowAccumulator(mg1, flow_director='Steepest') >>> fa1.run_one_step() >>> fa1.flow_director.links_to_receiver array([-1, -1, -1, -1, -1, -1, 5, 15, 7, -1, -1, 19, -1, 20, -1, -1, 23, 24, 25, -1, -1, -1, -1, -1, -1]) >>> fa1.flow_director.flow_link_direction_at_node() array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 1, 0, 0], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 1, -1, 0, 0], [-1, -1, 1, 1], [ 0, -1, -1, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 0, 0, -1], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) Next with DepressionFinderAndRouter: >>> mg2 = RasterModelGrid((5, 5)) >>> z2 = mg2.add_field( ... "topographic__elevation", ... mg2.x_of_node+2 * mg2.y_of_node, ... at="node", ... ) >>> z2[12] -= 5 >>> mg2.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> fa2 = FlowAccumulator( ... mg2, ... flow_director='Steepest', ... depression_finder='DepressionFinderAndRouter', ... routing='D4' ... ) >>> fa2.run_one_step() >>> fa2.flow_director.links_to_receiver array([-1, -1, -1, -1, -1, -1, 5, 6, 7, -1, -1, 19, 15, 20, -1, -1, 23, 24, 25, -1, -1, -1, -1, -1, -1]) >>> fa2.flow_director.flow_link_direction_at_node() array([[ 0, 0, 0, 0], [ 0, -1, 0, 0], [ 0, -1, 0, 0], [ 0, -1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, -1, 0, -1], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 1, -1, 0, 0], [-1, -1, 1, -1], [ 0, -1, -1, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 0, 0, -1], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) """ flow_link_direction_at_node = self._flow_link_direction[ self._grid.links_at_node ] flow_to_bad = self._grid.links_at_node == self._grid.BAD_INDEX flow_link_direction_at_node[flow_to_bad] = 0 return flow_link_direction_at_node def flow_link_incoming_at_node(self): """Return array that mirrors links at node and indicates incoming flow. This array has the shape (number of nodes, maximum number of links at node). Incoming flow is indicated as 1 and outgoing as -1. 0 indicates that no flow moves along the link or that the link does not exist. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.run_one_step() >>> fd.flow_link_incoming_at_node() array([[ 0, 0, 0, 0], [ 0, 1, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, -1], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0], [ 0, 0, 0, 0]], dtype=int8) """ incoming_at_node = ( self.flow_link_direction_at_node() * self._grid.link_dirs_at_node ) return incoming_at_node @property def flow_link_direction(self): """Return array of flow link direction. This property indicates the relationship between the flow direction (determined based on the elevation of nodes) and the topologic link direction (in which the head and tail nodes are defined based on relative position in x-y space). It has the shape (number_of_links,). Recall that the standard landlab link direction goes from the tail node to the head node. A value of zero indicates that the link does not exist or is not active. A value of -1 indicates that water flow based on ``flow__link_to_receiver_node`` goes from head node to tail node, while a value of 1 indicates that water flow goes from tail node to head node. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.run_one_step() >>> fd.flow_link_direction array([ 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int8) """ return self._flow_link_direction def upstream_node_at_link(self): """At-link array of the upstream node based on flow direction. BAD_INDEX_VALUE is given if no upstream node is defined. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.run_one_step() >>> fd.upstream_node_at_link() array([-1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1]) """ out = -1 * self._grid.ones(at="link", dtype=int) out[self._flow_link_direction == 1] = self._grid.node_at_link_tail[ self._flow_link_direction == 1 ] out[self._flow_link_direction == -1] = self._grid.node_at_link_head[ self._flow_link_direction == -1 ] return out def downstream_node_at_link(self): """At-link array of the downstream node based on flow direction. BAD_INDEX_VALUE is given if no downstream node is defined. Examples -------- >>> from landlab import RasterModelGrid >>> from landlab.components import FlowDirectorSteepest >>> mg = RasterModelGrid((3,3)) >>> mg.set_closed_boundaries_at_grid_edges(True, True, True, False) >>> _ = mg.add_field( ... "topographic__elevation", ... mg.node_x + mg.node_y, ... at="node", ... ) >>> fd = FlowDirectorSteepest(mg, 'topographic__elevation') >>> fd.run_one_step() >>> fd.downstream_node_at_link() array([-1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1]) """ out = -1 * self._grid.ones(at="link", dtype=int) out[self._flow_link_direction == 1] = self._grid.node_at_link_head[ self._flow_link_direction == 1 ] out[self._flow_link_direction == -1] = self._grid.node_at_link_tail[ self._flow_link_direction == -1 ] return out if __name__ == "__main__": # pragma: no cover import doctest doctest.testmod()
mit
67285fa0f20af718b3490a0f7cd6b812
35.136486
201
0.497513
3.338035
false
false
false
false
landlab/landlab
landlab/components/space/space_large_scale_eroder.py
1
20191
# -*- coding: utf-8 -*- """Grid-based simulation of lateral erosion by channels in a drainage network. Benjamin Campforts """ import numpy as np from landlab import Component, RasterModelGrid from landlab.grid.nodestatus import NodeStatus from landlab.utils.return_array import return_array_at_node from ..depression_finder.lake_mapper import _FLOODED from .ext.calc_sequential_ero_depo import _sequential_ero_depo ROOT2 = np.sqrt(2.0) # syntactic sugar for precalculated square root of 2 TIME_STEP_FACTOR = 0.5 # factor used in simple subdivision solver class SpaceLargeScaleEroder(Component): """Stream Power with Alluvium Conservation and Entrainment (SPACE) large scale eroder The SPACE_large_Scale_eroder is based on the SPACE component and is designed to be more robust against large time steps and coded in such a way that mass conservation is explicitly conserved during calculation. See the publication: Shobe, C. M., Tucker, G. E., and Barnhart, K. R.: The SPACE 1.0 model: a Landlab component for 2-D calculation of sediment transport, bedrock erosion, and landscape evolution, Geosci. Model Dev., 10, 4577-4604, `https://doi.org/10.5194/gmd-10-4577-2017 <https://www.geosci-model-dev.net/10/4577/2017/>`_, 2017. Unlike other some other fluvial erosion componets in Landlab, in this component (and :py:class:`~landlab.components.ErosionDeposition`) no erosion occurs in depressions or in areas with adverse slopes. There is no ability to pass a keyword argument ``erode_flooded_nodes``. If a depressions are handled (as indicated by the presence of the field "flood_status_code" at nodes), then deposition occurs throughout the depression and sediment is passed out of the depression. Where pits are encountered, then all sediment is deposited at that node only. Note: In the current version, we do not provide an adaptive time stepper. This will be addded in future versions of this component. For more explanation and examples, check out the correponding notebook of this component Examples --------- >>> import numpy as np >>> from landlab import RasterModelGrid >>> from landlab.components import ( ... PriorityFloodFlowRouter, SpaceLargeScaleEroder ... ) >>> import matplotlib.pyplot as plt # For plotting results; optional >>> from landlab import imshow_grid # For plotting results; optional >>> num_rows = 20 >>> num_columns = 20 >>> node_spacing = 100.0 >>> mg = RasterModelGrid((num_rows, num_columns), xy_spacing=node_spacing) >>> node_next_to_outlet = num_columns + 1 >>> np.random.seed(seed=5000) >>> _ = mg.add_zeros("topographic__elevation", at="node") >>> _ = mg.add_zeros("soil__depth", at="node") >>> mg.at_node["soil__depth"][mg.core_nodes] = 2.0 >>> _ = mg.add_zeros("bedrock__elevation", at="node") >>> mg.at_node["bedrock__elevation"] += ( ... mg.node_y / 10. + mg.node_x / 10. + np.random.rand(len(mg.node_y)) / 10. ... ) >>> mg.at_node["bedrock__elevation"][:] = mg.at_node["topographic__elevation"] >>> mg.at_node["topographic__elevation"][:] += mg.at_node["soil__depth"] >>> mg.set_closed_boundaries_at_grid_edges( ... bottom_is_closed=True, ... left_is_closed=True, ... right_is_closed=True, ... top_is_closed=True, ... ) >>> mg.set_watershed_boundary_condition_outlet_id( ... 0, mg.at_node['topographic__elevation'], -9999.0 ... ) >>> fr = PriorityFloodFlowRouter(mg, flow_metric='D8', suppress_out = True) >>> sp = SpaceLargeScaleEroder( ... mg, ... K_sed=0.01, ... K_br=0.001, ... F_f=0.0, ... phi=0.0, ... H_star=1.0, ... v_s=5.0, ... m_sp=0.5, ... n_sp=1.0, ... sp_crit_sed=0, ... sp_crit_br=0, ... ) >>> timestep = 10.0 >>> elapsed_time = 0.0 >>> count = 0 >>> run_time = 1e4 >>> sed_flux = np.zeros(int(run_time // timestep)) >>> while elapsed_time < run_time: ... fr.run_one_step() ... _ = sp.run_one_step(dt=timestep) ... sed_flux[count] = mg.at_node["sediment__flux"][node_next_to_outlet] ... elapsed_time += timestep ... count += 1 Plot the results. >>> fig = plt.figure() >>> plot = plt.subplot() >>> _ = imshow_grid( ... mg, ... "topographic__elevation", ... plot_name="Sediment flux", ... var_name="Sediment flux", ... var_units=r"m$^3$/yr", ... grid_units=("m", "m"), ... cmap="terrain", ... ) >>> _ = plt.figure() >>> _ = imshow_grid( ... mg, ... "sediment__flux", ... plot_name="Sediment flux", ... var_name="Sediment flux", ... var_units=r"m$^3$/yr", ... grid_units=("m", "m"), ... cmap="terrain", ... ) >>> fig = plt.figure() >>> sedfluxplot = plt.subplot() >>> _ = sedfluxplot.plot(np.arange(len(sed_flux)) * timestep, sed_flux, color="k", linewidth=1.0) >>> _ = sedfluxplot.set_xlabel("Time [yr]") >>> _ = sedfluxplot.set_ylabel(r"Sediment flux [m$^3$/yr]") References ---------- **Required Software Citation(s) Specific to this Component** Shobe, C., Tucker, G., Barnhart, K. (2017). The SPACE 1.0 model: a Landlab component for 2-D calculation of sediment transport, bedrock erosion, and landscape evolution. Geoscientific Model Development 10(12), 4577 - 4604. https://dx.doi.org/10.5194/gmd-10-4577-2017 **Additional References** None Listed """ _name = "SpaceLargeScaleEroder" _unit_agnostic = True _info = { "flow__link_to_receiver_node": { "dtype": int, "intent": "in", "optional": True, "units": "-", "mapping": "node", "doc": "ID of link downstream of each node, which carries the discharge", }, "flow__receiver_node": { "dtype": int, "intent": "in", "optional": False, "units": "-", "mapping": "node", "doc": "Node array of receivers (node that receives flow from current node)", }, "flow__upstream_node_order": { "dtype": int, "intent": "in", "optional": False, "units": "-", "mapping": "node", "doc": "Node array containing downstream-to-upstream ordered list of node IDs", }, "sediment__influx": { "dtype": float, "intent": "out", "optional": False, "units": "m3/s", "mapping": "node", "doc": "Sediment flux (volume per unit time of sediment entering each node)", }, "sediment__outflux": { "dtype": float, "intent": "out", "optional": False, "units": "m3/s", "mapping": "node", "doc": "Sediment flux (volume per unit time of sediment leaving each node)", }, "soil__depth": { "dtype": float, "intent": "inout", "optional": False, "units": "m", "mapping": "node", "doc": "Depth of soil or weathered bedrock", }, "surface_water__discharge": { "dtype": float, "intent": "in", "optional": False, "units": "m**3/s", "mapping": "node", "doc": "Volumetric discharge of surface water", }, "topographic__elevation": { "dtype": float, "intent": "inout", "optional": False, "units": "m", "mapping": "node", "doc": "Land surface topographic elevation", }, "topographic__steepest_slope": { "dtype": float, "intent": "in", "optional": True, "units": "-", "mapping": "node", "doc": "The steepest *downhill* slope", }, } _cite_as = """@Article{gmd-10-4577-2017, AUTHOR = {Shobe, C. M. and Tucker, G. E. and Barnhart, K. R.}, TITLE = {The SPACE~1.0 model: a~Landlab component for 2-D calculation of sediment transport, bedrock erosion, and landscape evolution}, JOURNAL = {Geoscientific Model Development}, VOLUME = {10}, YEAR = {2017}, NUMBER = {12}, PAGES = {4577--4604}, URL = {https://www.geosci-model-dev.net/10/4577/2017/}, DOI = {10.5194/gmd-10-4577-2017} }""" def __init__( self, grid, K_sed=0.02, K_br=0.02, F_f=0.0, phi=0.3, H_star=0.1, v_s=1.0, v_s_lake=None, m_sp=0.5, n_sp=1.0, sp_crit_sed=0.0, sp_crit_br=0.0, discharge_field="surface_water__discharge", erode_flooded_nodes=False, thickness_lim=100, ): """Initialize the SpaceLargeScaleEroder model. Parameters ---------- grid : ModelGrid Landlab ModelGrid object K_sed : float, array of float, or str, optional Erodibility for sediment (units vary) as either a number or a field name. K_br : float, array of float, or str, optional Erodibility for bedrock (units vary) as either a number or a field name. F_f : float, optional Fraction of permanently suspendable fines in bedrock [-]. phi : float, optional Sediment porosity [-]. H_star : float, optional Sediment thickness required for full entrainment [L]. v_s : float, optional Effective settling velocity for chosen grain size metric [L/T]. v_s_lake : float, optional Effective settling velocity in lakes for chosen grain size metric [L/T]. m_sp : float, optional Drainage area exponent (units vary). n_sp : float, optional Slope exponent (units vary). sp_crit_sed : float, array of float, or str, optional Critical stream power to erode sediment [E/(TL^2)]. sp_crit_br : float, array of float, or str, optional Critical stream power to erode rock [E/(TL^2)] discharge_field : float, array of float, or str, optional Discharge [L^2/T]. The default is to use the grid field 'surface_water__discharge', which is simply drainage area multiplied by the default rainfall rate (1 m/yr). To use custom spatially/temporally varying rainfall, use 'water__unit_flux_in' to specify water input to the FlowAccumulator. erode_flooded_nodes : bool, optional Whether erosion occurs in flooded nodes identified by a depression/lake mapper (e.g., DepressionFinderAndRouter). When set to false, the field *flood_status_code* must be present on the grid (this is created by the DepressionFinderAndRouter). Default True. """ if grid.at_node["flow__receiver_node"].size != grid.size("node"): raise NotImplementedError( "A route-to-multiple flow director has been " "run on this grid. The landlab development team has not " "verified that SpaceLargeScaleEroder is compatible with " "route-to-multiple methods. Please open a GitHub Issue " "to start this process." ) super(SpaceLargeScaleEroder, self).__init__(grid) self._soil__depth = grid.at_node["soil__depth"] self._topographic__elevation = grid.at_node["topographic__elevation"] if "bedrock__elevation" in grid.at_node: self._bedrock__elevation = grid.at_node["bedrock__elevation"] else: self._bedrock__elevation = grid.add_zeros( "bedrock__elevation", at="node", dtype=float ) self._bedrock__elevation[:] = ( self._topographic__elevation - self._soil__depth ) # Check consistency of bedrock, soil and topogarphic elevation fields err_msg = ( "The sum of bedrock elevation and topographic elevation should be equal" ) np.testing.assert_almost_equal( grid.at_node["bedrock__elevation"] + grid.at_node["soil__depth"], grid.at_node["topographic__elevation"], decimal=5, err_msg=err_msg, ) # specific inits self._thickness_lim = thickness_lim self._H_star = H_star self._sed_erosion_term = np.zeros(grid.number_of_nodes) self._br_erosion_term = np.zeros(grid.number_of_nodes) self._Es = np.zeros(grid.number_of_nodes) self._Er = np.zeros(grid.number_of_nodes) # K's and critical values can be floats, grid fields, or arrays # use setters defined below self._K_sed = K_sed self._K_br = K_br self._sp_crit_sed = return_array_at_node(grid, sp_crit_sed) self._sp_crit_br = return_array_at_node(grid, sp_crit_br) self._erode_flooded_nodes = erode_flooded_nodes self._flow_receivers = grid.at_node["flow__receiver_node"] self._stack = grid.at_node["flow__upstream_node_order"] self._slope = grid.at_node["topographic__steepest_slope"] self.initialize_output_fields() self._qs = grid.at_node["sediment__outflux"] self._q = return_array_at_node(grid, discharge_field) # for backward compatibility (remove in 3.0.0+) grid.at_node["sediment__flux"] = grid.at_node["sediment__outflux"] self._Q_to_the_m = np.zeros(grid.number_of_nodes) self._S_to_the_n = np.zeros(grid.number_of_nodes) # store other constants self._m_sp = np.float64(m_sp) self._n_sp = np.float64(n_sp) self._phi = np.float64(phi) self._v_s = np.float64(v_s) if isinstance(grid, RasterModelGrid): self._link_lengths = grid.length_of_d8 else: self._link_lengths = grid.length_of_link if v_s_lake is None: self._v_s_lake = np.float64(v_s) else: self._v_s_lake = np.float64(v_s_lake) self._F_f = np.float64(F_f) if phi >= 1.0: raise ValueError("Porosity must be < 1.0") if F_f > 1.0: raise ValueError("Fraction of fines must be <= 1.0") if phi < 0.0: raise ValueError("Porosity must be > 0.0") if F_f < 0.0: raise ValueError("Fraction of fines must be > 0.0") @property def K_br(self): """Erodibility of bedrock(units depend on m_sp).""" return self._K_br @K_br.setter def K_br(self, new_val): self._K_br = return_array_at_node(self._grid, new_val) @property def K_sed(self): """Erodibility of sediment(units depend on m_sp).""" return self._K_sed @K_sed.setter def K_sed(self, new_val): self._K_sed = return_array_at_node(self._grid, new_val) @property def Es(self): """Sediment erosion term.""" return self._Es @property def Er(self): """Bedrock erosion term.""" return self._Er @property def sediment_influx(self): """Volumetric sediment influx to each node.""" return self.grid.at_node["sediment__influx"] def _calc_erosion_rates(self): """Calculate erosion rates.""" br = self.grid.at_node["bedrock__elevation"] H = self.grid.at_node["soil__depth"] # if sp_crits are zero, then this colapses to correct all the time. if np.isclose(self._n_sp, 1.0): S_to_the_n = self._slope else: S_to_the_n = np.power(self._slope, self._n_sp) omega_sed = self._K_sed * self._Q_to_the_m * S_to_the_n omega_br = self._K_br * self._Q_to_the_m * S_to_the_n omega_sed_over_sp_crit = np.divide( omega_sed, self._sp_crit_sed, out=np.zeros_like(omega_sed), where=self._sp_crit_sed != 0, ) omega_br_over_sp_crit = np.divide( omega_br, self._sp_crit_br, out=np.zeros_like(omega_br), where=self._sp_crit_br != 0, ) self._sed_erosion_term = omega_sed - self._sp_crit_sed * ( 1.0 - np.exp(-omega_sed_over_sp_crit) ) / ( 1 - self._phi ) # convert from a volume to a mass flux. self._br_erosion_term = omega_br - self._sp_crit_br * ( 1.0 - np.exp(-omega_br_over_sp_crit) ) # Do not allow for the formation of potholes (addition v2) r = self._grid.at_node["flow__receiver_node"] br_e_max = br - br[r] br_e_max[br_e_max < 0] = 0 self._br_erosion_term = np.minimum(self._br_erosion_term, br_e_max) self._Es = self._sed_erosion_term * (1.0 - np.exp(-H / self._H_star)) self._Er = self._br_erosion_term * np.exp(-H / self._H_star) # if the soil layer becomes exceptionally thick (e.g. because of # landslide derived sediment deposition(,) the algorithm will become # unstable because np.exp(x) with x > 709 yeilds inf values. # Therefore soil depth is temporqlly topped of at 200m and the remaining # values are added back after the space component has run self._Es[H > self._thickness_lim] = self._sed_erosion_term[ H > self._thickness_lim ] self._Er[H > self._thickness_lim] = 0 def run_one_step_basic(self, dt=10): node_status = self.grid.status_at_node z = self.grid.at_node["topographic__elevation"] br = self.grid.at_node["bedrock__elevation"] H = self.grid.at_node["soil__depth"] link_to_rcvr = self.grid.at_node["flow__link_to_receiver_node"] area = self.grid.cell_area_at_node r = self.grid.at_node["flow__receiver_node"] stack_flip_ud = np.flipud(self.grid.at_node["flow__upstream_node_order"]) # Select core nodes where qs >0 stack_flip_ud_sel = stack_flip_ud[ (node_status[stack_flip_ud] == NodeStatus.CORE) & (self._q[stack_flip_ud] > 0.0) ] slope = (z - z[r]) / self._link_lengths[link_to_rcvr] # Choose a method for calculating erosion: self._Q_to_the_m[:] = np.power(self._q, self._m_sp) self._calc_erosion_rates() if "flood_status_code" in self.grid.at_node: flood_status = self.grid.at_node["flood_status_code"] flooded_nodes = np.nonzero(flood_status == _FLOODED)[0] else: flooded_nodes = np.nonzero([slope < 0])[1] self._Es[flooded_nodes] = 0.0 self._Er[flooded_nodes] = 0.0 self._sed_erosion_term[flooded_nodes] = 0.0 self._br_erosion_term[flooded_nodes] = 0.0 self.sediment_influx[:] = 0 K_sed_vector = np.broadcast_to(self._K_sed, self._q.shape) vol_SSY_riv = _sequential_ero_depo( stack_flip_ud_sel, r, area, self._q, self._qs, self.sediment_influx, self._Es, self._Er, self._Q_to_the_m, slope, H, br, self._sed_erosion_term, self._br_erosion_term, K_sed_vector, self._v_s, self._phi, self._F_f, self._H_star, dt, self._thickness_lim, ) V_leaving_riv = np.sum(self.sediment_influx) * dt # Update topography cores = self._grid.core_nodes z[cores] = br[cores] + H[cores] return vol_SSY_riv, V_leaving_riv def run_one_step(self, dt): vol_SSY_riv, V_leaving_riv = self.run_one_step_basic(dt) return vol_SSY_riv, V_leaving_riv
mit
36490f31b3af88e209387634fb42d01a
34.927046
153
0.554802
3.38548
false
false
false
false
california-civic-data-coalition/django-calaccess-raw-data
calaccess_raw/management/commands/cleancalaccessrawfile.py
1
9732
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Clean a source CAL-ACCESS TSV file and reformat it as a CSV. """ import time # Files import os import csv import csvkit from django.core.files import File # Django from django.conf import settings from django.utils.timezone import now # Commands from django.core.management.base import CommandError from calaccess_raw.management.commands import CalAccessCommand from calaccess_raw.models.tracking import RawDataVersion, RawDataFile class Command(CalAccessCommand): """ Clean a source CAL-ACCESS TSV file and reformat it as a CSV. """ help = 'Clean a source CAL-ACCESS TSV file and reformat it as a CSV' def add_arguments(self, parser): """ Adds custom arguments specific to this command. """ super(Command, self).add_arguments(parser) parser.add_argument( 'file_name', help="Name of the TSV file to be cleaned and discarded for a CSV" ) parser.add_argument( "--keep-file", action="store_true", dest="keep_file", default=False, help="Keep original TSV file" ) def handle(self, *args, **options): """ Make it happen. """ super(Command, self).handle(*args, **options) # Set all the config options self.set_options(options) # Get the tracking object from the database self.raw_file = self.get_file_obj() # If the file has data ... if self.row_count: # Walk through the raw TSV file and create a clean CSV file if self.verbosity > 1: self.log(" Cleaning %s" % self.file_name) self.clean() # If requested, archive the files if getattr(settings, 'CALACCESS_STORE_ARCHIVE', False): self.archive() # Unless keeping files, remove the raw TSV file if not options['keep_file']: os.remove(self.tsv_path) # Store the finish time in the database self.raw_file.clean_finish_datetime = now() # Save the tracking record in the database one last time self.raw_file.save() def set_options(self, options): """ Set options for use in other methods. """ # Set options self.file_name = options['file_name'] # Set log variables self.log_dir = os.path.join(self.data_dir, "log/") self.log_name = self.file_name.lower().replace("tsv", "errors.csv") self.error_log_path = os.path.join(self.log_dir, self.log_name) self.log_rows = [] # Make sure the log directory exists os.path.exists(self.log_dir) or os.makedirs(self.log_dir) # Input and output paths self.tsv_path = os.path.join(self.tsv_dir, self.file_name) self.csv_name = self.file_name.lower().replace("tsv", "csv") self.csv_path = os.path.join(self.csv_dir, self.csv_name) # Pull and clean the headers self.headers = self.get_headers() self.headers_count = len(self.headers) # Get the row count with open(self.tsv_path, "r") as tsv_file: self.row_count = max(sum(1 for line in tsv_file), 0) def get_headers(self): """ Returns the headers from the TSV file. """ with open(self.tsv_path, "r") as tsv_file: tsv_reader = csvkit.reader(tsv_file, delimiter=str("\t")) try: return next(tsv_reader) except StopIteration: return [] def get_file_obj(self): """ Get the file object from our tracking database table. """ # Get most recently extracted RawDataVersion try: version = RawDataVersion.objects.latest_extract() except RawDataVersion.DoesNotExist: raise CommandError('No record of extracting zip (run `python manage.py extractcalaccessrawfiles`)') # Raise exception if extract step did not finish if not version.extract_completed: raise CommandError('Previous extraction did not finish (run `python manage.py extractcalaccessrawfiles`)') # Get the raw file record raw_file = RawDataFile.objects.get( file_name=self.file_name.replace('.TSV', ''), version=version ) # store the start time for the clean raw_file.clean_start_datetime = now() # reset the finish time for the clean raw_file.clean_finish_datetime = None # Set the count fields raw_file.download_columns_count = self.headers_count raw_file.download_records_count = self.row_count - 1 # Save here in case command doesn't finish raw_file.save() # Pass it back return raw_file def _convert_tsv(self): """ Given it a raw list of rows from a TSV, yields cleaned rows for a CSV. """ with open(self.tsv_path, 'rb') as tsv_file: # Pop the headers out of the TSV file next(tsv_file) # Loop through all the rows for tsv_line in tsv_file: # Decode the line for testing tsv_line = tsv_line.decode("ascii", "replace") # If the line is empty skip it if not tsv_line.strip(): continue # Nuke any null bytes if tsv_line.count('\x00'): tsv_line = tsv_line.replace('\x00', ' ') # Nuke the ASCII "substitute character." chr(26) in Python if tsv_line.count('\x1a'): tsv_line = tsv_line.replace('\x1a', '') # Remove any extra newline chars tsv_line = tsv_line.replace("\r\n", "").replace("\r", "").replace("\n", "") # Split on tabs so we can later spit it back out as a CSV row csv_line = tsv_line.split("\t") csv_field_count = len(csv_line) # If it matches the header count, yield it if csv_field_count == self.headers_count: yield csv_line else: # Otherwise log it self.log_rows.append([self.headers_count, csv_field_count, ','.join(csv_line)]) def clean(self): """ Cleans the provided source TSV file and writes it out in CSV format. """ # Create the output object with open(self.csv_path, 'w') as csv_file: # Create the CSV writer csv_writer = csvkit.writer(csv_file) # Write the headers csv_writer.writerow(self.headers) # Write out the rows [csv_writer.writerow(row) for row in self._convert_tsv()] # Log errors if there are any if self.log_rows: # Log to the terminal if self.verbosity > 2: msg = ' {} errors logged (not including empty lines)' self.failure(msg.format(len(self.log_rows))) # Log to the file with open(self.error_log_path, 'w') as log_file: log_writer = csvkit.writer(log_file, quoting=csv.QUOTE_ALL) log_writer.writerow(['headers', 'fields', 'value']) log_writer.writerows(self.log_rows) # Add counts to raw_file_record self.raw_file.clean_columns_count = self.headers_count self.raw_file.error_count = len(self.log_rows) self.raw_file.clean_records_count = self.raw_file.download_records_count - self.raw_file.error_count # Add file size to the raw_file_record self.raw_file.download_file_size = os.path.getsize(self.tsv_path) or 0 self.raw_file.clean_file_size = os.path.getsize(self.csv_path) or 0 # Save it in case it crashes in the next step self.raw_file.save() def archive(self, suffix=None): """ Archive the file. """ if self.verbosity > 2: self.log(" Archiving {}".format(os.path.basename(self.csv_path))) identifier = "ccdc-raw-data-{dt:%Y-%m-%d_%H-%M-%S}".format(dt=self.raw_file.version.release_datetime) if suffix: identifier += suffix # Open up the .CSV file so we can wrap it in the Django File obj with open(self.csv_path, 'rb') as csv_file: # Save the .CSV on the raw data file try: self.raw_file.clean_file_archive.save( identifier, File(csv_file) ) except FileExistsError: self.raw_file.clean_file_archive.delete() self.raw_file.clean_file_archive.save( identifier, File(csv_file) ) time.sleep(.25) # if there are any errors, archive the log too if self.log_rows: error_log_name = os.path.basename(self.error_log_path) if self.verbosity > 2: self.log(" Archiving {}".format(error_log_name)) # Save it with open(self.error_log_path, 'rb') as error_file: try: self.raw_file.error_log_archive.save( identifier, File(error_file) ) except FileExistsError: self.raw_file.error_log_archive.delete() self.raw_file.error_log_archive.save( identifier, File(error_file) ) time.sleep(0.5)
mit
44938599c24aced433d733a83dfb3371
34.007194
118
0.554151
4.04657
false
false
false
false
california-civic-data-coalition/django-calaccess-raw-data
calaccess_raw/migrations/0004_auto_20160804_1758.py
1
1227
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-04 17:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('calaccess_raw', '0003_auto_20160804_1443'), ] operations = [ migrations.AddField( model_name='rawdataversion', name='clean_zip_size', field=models.BigIntegerField(help_text='The size of the zip containing all cleaned raw data files and error logs.', null=True, verbose_name='clean zip size'), ), migrations.AddField( model_name='rawdataversion', name='download_zip_size', field=models.BigIntegerField(help_text='The actual size of the downloaded CAL-ACCESS zip after the downloaded completed.', null=True, verbose_name='downloaded zip size'), ), migrations.AlterField( model_name='rawdataversion', name='expected_size', field=models.BigIntegerField(help_text='The expected size of the downloaded CAL-ACCESS zip, as specified in the content-length field in HTTP response header.', verbose_name='expected downloaded zip size'), ), ]
mit
a4988614b104d5b46a8ee581e228bcd3
39.9
217
0.651182
4.397849
false
false
false
false
pdfminer/pdfminer.six
pdfminer/pdfparser.py
1
5896
import logging from io import BytesIO from typing import BinaryIO, TYPE_CHECKING, Optional, Union from . import settings from .pdftypes import PDFException from .pdftypes import PDFObjRef from .pdftypes import PDFStream from .pdftypes import dict_value from .pdftypes import int_value from .psparser import KWD from .psparser import PSEOF from .psparser import PSKeyword from .psparser import PSStackParser from .psparser import PSSyntaxError if TYPE_CHECKING: from .pdfdocument import PDFDocument log = logging.getLogger(__name__) class PDFSyntaxError(PDFException): pass # PDFParser stack holds all the base types plus PDFStream, PDFObjRef, and None class PDFParser(PSStackParser[Union[PSKeyword, PDFStream, PDFObjRef, None]]): """ PDFParser fetch PDF objects from a file stream. It can handle indirect references by referring to a PDF document set by set_document method. It also reads XRefs at the end of every PDF file. Typical usage: parser = PDFParser(fp) parser.read_xref() parser.read_xref(fallback=True) # optional parser.set_document(doc) parser.seek(offset) parser.nextobject() """ def __init__(self, fp: BinaryIO) -> None: PSStackParser.__init__(self, fp) self.doc: Optional["PDFDocument"] = None self.fallback = False def set_document(self, doc: "PDFDocument") -> None: """Associates the parser with a PDFDocument object.""" self.doc = doc KEYWORD_R = KWD(b"R") KEYWORD_NULL = KWD(b"null") KEYWORD_ENDOBJ = KWD(b"endobj") KEYWORD_STREAM = KWD(b"stream") KEYWORD_XREF = KWD(b"xref") KEYWORD_STARTXREF = KWD(b"startxref") def do_keyword(self, pos: int, token: PSKeyword) -> None: """Handles PDF-related keywords.""" if token in (self.KEYWORD_XREF, self.KEYWORD_STARTXREF): self.add_results(*self.pop(1)) elif token is self.KEYWORD_ENDOBJ: self.add_results(*self.pop(4)) elif token is self.KEYWORD_NULL: # null object self.push((pos, None)) elif token is self.KEYWORD_R: # reference to indirect object if len(self.curstack) >= 2: try: ((_, objid), (_, genno)) = self.pop(2) (objid, genno) = (int(objid), int(genno)) # type: ignore[arg-type] assert self.doc is not None obj = PDFObjRef(self.doc, objid, genno) self.push((pos, obj)) except PSSyntaxError: pass elif token is self.KEYWORD_STREAM: # stream object ((_, dic),) = self.pop(1) dic = dict_value(dic) objlen = 0 if not self.fallback: try: objlen = int_value(dic["Length"]) except KeyError: if settings.STRICT: raise PDFSyntaxError("/Length is undefined: %r" % dic) self.seek(pos) try: (_, line) = self.nextline() # 'stream' except PSEOF: if settings.STRICT: raise PDFSyntaxError("Unexpected EOF") return pos += len(line) self.fp.seek(pos) data = bytearray(self.fp.read(objlen)) self.seek(pos + objlen) while 1: try: (linepos, line) = self.nextline() except PSEOF: if settings.STRICT: raise PDFSyntaxError("Unexpected EOF") break if b"endstream" in line: i = line.index(b"endstream") objlen += i if self.fallback: data += line[:i] break objlen += len(line) if self.fallback: data += line self.seek(pos + objlen) # XXX limit objlen not to exceed object boundary log.debug( "Stream: pos=%d, objlen=%d, dic=%r, data=%r...", pos, objlen, dic, data[:10], ) assert self.doc is not None stream = PDFStream(dic, bytes(data), self.doc.decipher) self.push((pos, stream)) else: # others self.push((pos, token)) class PDFStreamParser(PDFParser): """ PDFStreamParser is used to parse PDF content streams that is contained in each page and has instructions for rendering the page. A reference to a PDF document is needed because a PDF content stream can also have indirect references to other objects in the same document. """ def __init__(self, data: bytes) -> None: PDFParser.__init__(self, BytesIO(data)) def flush(self) -> None: self.add_results(*self.popall()) KEYWORD_OBJ = KWD(b"obj") def do_keyword(self, pos: int, token: PSKeyword) -> None: if token is self.KEYWORD_R: # reference to indirect object try: ((_, objid), (_, genno)) = self.pop(2) (objid, genno) = (int(objid), int(genno)) # type: ignore[arg-type] obj = PDFObjRef(self.doc, objid, genno) self.push((pos, obj)) except PSSyntaxError: pass return elif token in (self.KEYWORD_OBJ, self.KEYWORD_ENDOBJ): if settings.STRICT: # See PDF Spec 3.4.6: Only the object values are stored in the # stream; the obj and endobj keywords are not used. raise PDFSyntaxError("Keyword endobj found in stream") return # others self.push((pos, token))
mit
0ebe22a91e015a2d8b3f89055961f496
32.5
87
0.544946
4.088766
false
false
false
false
pdfminer/pdfminer.six
pdfminer/ascii85.py
1
2097
""" Python implementation of ASCII85/ASCIIHex decoder (Adobe version). This code is in the public domain. """ import re import struct # ascii85decode(data) def ascii85decode(data: bytes) -> bytes: """ In ASCII85 encoding, every four bytes are encoded with five ASCII letters, using 85 different types of characters (as 256**4 < 85**5). When the length of the original bytes is not a multiple of 4, a special rule is used for round up. The Adobe's ASCII85 implementation is slightly different from its original in handling the last characters. """ n = b = 0 out = b"" for i in iter(data): c = bytes((i,)) if b"!" <= c and c <= b"u": n += 1 b = b * 85 + (ord(c) - 33) if n == 5: out += struct.pack(">L", b) n = b = 0 elif c == b"z": assert n == 0, str(n) out += b"\0\0\0\0" elif c == b"~": if n: for _ in range(5 - n): b = b * 85 + 84 out += struct.pack(">L", b)[: n - 1] break return out # asciihexdecode(data) hex_re = re.compile(rb"([a-f\d]{2})", re.IGNORECASE) trail_re = re.compile(rb"^(?:[a-f\d]{2}|\s)*([a-f\d])[\s>]*$", re.IGNORECASE) def asciihexdecode(data: bytes) -> bytes: """ ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the ASCIIHexDecode filter produces one byte of binary data. All white-space characters are ignored. A right angle bracket character (>) indicates EOD. Any other characters will cause an error. If the filter encounters the EOD marker after reading an odd number of hexadecimal digits, it will behave as if a 0 followed the last digit. """ def decode(x: bytes) -> bytes: i = int(x, 16) return bytes((i,)) out = b"" for x in hex_re.findall(data): out += decode(x) m = trail_re.search(data) if m: out += decode(m.group(1) + b"0") return out
mit
7fc7675e70d7c4017b534e46e630f165
28.125
77
0.562709
3.530303
false
false
false
false
stopstalk/stopstalk-deployment
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/html5lib/filters/inject_meta_charset.py
169
2945
from __future__ import absolute_import, division, unicode_literals from . import base class Filter(base.Filter): """Injects ``<meta charset=ENCODING>`` tag into head of document""" def __init__(self, source, encoding): """Creates a Filter :arg source: the source token stream :arg encoding: the encoding to set """ base.Filter.__init__(self, source) self.encoding = encoding def __iter__(self): state = "pre_head" meta_found = (self.encoding is None) pending = [] for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag": if token["name"].lower() == "head": state = "in_head" elif type == "EmptyTag": if token["name"].lower() == "meta": # replace charset with actual encoding has_http_equiv_content_type = False for (namespace, name), value in token["data"].items(): if namespace is not None: continue elif name.lower() == 'charset': token["data"][(namespace, name)] = self.encoding meta_found = True break elif name == 'http-equiv' and value.lower() == 'content-type': has_http_equiv_content_type = True else: if has_http_equiv_content_type and (None, "content") in token["data"]: token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding meta_found = True elif token["name"].lower() == "head" and not meta_found: # insert meta into empty head yield {"type": "StartTag", "name": "head", "data": token["data"]} yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} yield {"type": "EndTag", "name": "head"} meta_found = True continue elif type == "EndTag": if token["name"].lower() == "head" and pending: # insert meta into head (if necessary) and flush pending queue yield pending.pop(0) if not meta_found: yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} while pending: yield pending.pop(0) meta_found = True state = "post_head" if state == "in_head": pending.append(token) else: yield token
mit
ad35f35f5bbe271fd8ab9327782c9970
39.342466
102
0.441766
5.017036
false
false
false
false
chainer/chainer
tests/chainermn_tests/links_tests/test_n_step_rnn.py
4
4452
import chainer import chainer.backends from chainer.backends.cuda import cupy import chainer.functions as F import chainer.links as L import chainer.testing import chainer.testing.attr import chainermn import numpy as np import pytest class Model(chainer.Chain): def __init__(self, n_vocab, n_hid, communicator, rank_next, rank_prev): n_layers = 1 n_rnn_hid = 10 super(Model, self).__init__() with self.init_scope(): self.l1 = L.EmbedID(n_vocab, n_rnn_hid, ignore_label=-1) self.rnn = chainermn.links.create_multi_node_n_step_rnn( L.NStepLSTM( n_layers=n_layers, in_size=n_rnn_hid, out_size=n_rnn_hid, dropout=0.1), communicator, rank_in=rank_prev, rank_out=rank_next, ) self.l2 = L.Linear(n_rnn_hid, n_hid) self.l3 = L.Linear(n_hid, 1) def __call__(self, xs, ts): h1 = [self.l1(x) for x in xs] # MultiNodeNStepRNN returns outputs of actual_rnn + delegate_variable. cell1, cell2, os, delegate_variable = self.rnn(h1) os = F.concat(os, axis=0) h2 = self.l2(os) h3 = self.l3(h2) ys = F.sum(h3, axis=0) err = F.mean_squared_error(ys, ts) err, = chainermn.functions.pseudo_connect(delegate_variable, err) return err def setup_communicator(gpu): if gpu: communicator = chainermn.create_communicator('flat') chainer.backends.cuda.get_device_from_id( communicator.intra_rank).use() else: communicator = chainermn.create_communicator('naive') if communicator.size < 2: pytest.skip('This test is for multinode only') rank_next = communicator.rank + 1 rank_prev = communicator.rank - 1 if rank_prev < 0: rank_prev = None if rank_next >= communicator.size: rank_next = None return communicator, rank_prev, rank_next def check_homogeneous_rnn(gpu, dtype): communicator, rank_prev, rank_next = setup_communicator(gpu=gpu) n, n_vocab, l = 100, 8, 10 # Number of model parameters are same among processes. n_hid = 2 with chainer.using_config('dtype', dtype): X = [np.random.randint( 0, n_vocab, size=np.random.randint(l // 2, l + 1), dtype=np.int32) for _ in range(n)] Y = (np.random.rand(n) * 2).astype(dtype) model = Model( n_vocab, n_hid, communicator, rank_next, rank_prev) if gpu: model.to_device(cupy.cuda.Device()) X = [chainer.backends.cuda.to_gpu(x) for x in X] Y = chainer.backends.cuda.to_gpu(Y) for i in range(n): err = model(X[i:i + 1], Y[i:i + 1]) err.backward() # Check if backprop finishes without deadlock. assert True @pytest.mark.parametrize('dtype', [np.float16, np.float32]) def test_homogeneous_rnn_cpu(dtype): check_homogeneous_rnn(False, dtype) @chainer.testing.attr.gpu @pytest.mark.parametrize('dtype', [np.float16, np.float32]) def test_homogeneous_rnn_gpu(dtype): check_homogeneous_rnn(True, dtype) def check_heterogeneous_rnn(gpu, dtype): communicator, rank_prev, rank_next = setup_communicator(gpu) with chainer.using_config('dtype', dtype): n, n_vocab, l = 100, 8, 10 # Number of model parameters are different among processes. n_hid = (communicator.rank + 1) * 10 X = [np.random.randint( 0, n_vocab, size=np.random.randint(l // 2, l + 1), dtype=np.int32) for _ in range(n)] Y = (np.random.rand(n) * 2).astype(dtype) model = Model( n_vocab, n_hid, communicator, rank_next, rank_prev) if gpu: model.to_device(cupy.cuda.Device()) X = [chainer.backends.cuda.to_gpu(x) for x in X] Y = chainer.backends.cuda.to_gpu(Y) for i in range(n): err = model(X[i:i + 1], Y[i:i + 1]) err.backward() # Check if backprop finishes without deadlock. assert True @pytest.mark.parametrize('dtype', [np.float16, np.float32]) def test_heterogeneous_rnn_cpu(dtype): check_heterogeneous_rnn(False, dtype) @chainer.testing.attr.gpu @pytest.mark.parametrize('dtype', [np.float16, np.float32]) def test_heterogeneous_rnn_gpu(dtype): check_heterogeneous_rnn(True, dtype)
mit
71c50c7005dcd0f63ce30e25b9bb075e
30.132867
78
0.59726
3.283186
false
true
false
false
chainer/chainer
chainermn/communicators/__init__.py
4
5933
import warnings from chainer.utils import argument from chainermn.communicators.communicator_base import CommunicatorBase # NOQA def create_communicator( communicator_name='pure_nccl', mpi_comm=None, **kwargs): """Create a ChainerMN communicator. Different communicators provide different approaches of communication, so they have different performance charasteristics. The default communicator ``pure_nccl`` is expected to generally perform well on a variety of environments, so one need not to change communicators in most cases. However, you may need to choose other communicators depending on your computing platform and the availability of NCCL library. The following communicators are available. +---------------+---+---+--------+--------------------------------------+ |Name |CPU|GPU|NCCL |Recommended Use Cases | +===============+===+===+========+======================================+ |pure_nccl | |OK |Required|``pure_nccl`` is recommended when | | | | |(>= v2) |NCCL2 is available in the environment.| +---------------+---+---+--------+--------------------------------------+ |flat | |OK | |N/A | +---------------+---+---+--------+--------------------------------------+ |naive |OK |OK | |Testing on CPU mode | +---------------+---+---+--------+--------------------------------------+ pure_nccl communicator supports multiple data types, FP32 and FP16, in gradient exchange. The communication data type is determined based on `chainer.global_config.dtype` and `allreduce_grad_dtype`. When `allreduce_grad_dtype` is the default value `None`, FP32 is used when `chainer.global_config.dtype` is `numpy.float32` and FP16 otherwise. `allreduce_grad_dtype` parameter, which is either `numpy.float16` or `numpy.float32`, overwrites the `chainer.global_config.dtype`. The table blow summarizes the data type selection in gradient exchange. +---------------------+--------------------------------------------+ | | allreduce_grad_dtype | +---------------------+---------+------------------+---------------+ | global_config.dtype | None | numpy.float16 | numpy.float32 | +=====================+=========+==================+===============+ | chainer.mixed16 | FP16 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ | numpy.float16 | FP16 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ | numpy.float32 | FP32 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ Other communicators, namely ``flat`` and ``naive``, support only float32 communication, no matter what the model is. This is due to MPI's limited support of float16. Args: communicator_name: The name of communicator (``naive``, ``flat``, or ``pure_nccl``) mpi_comm: MPI4py communicator allreduce_grad_dtype: Data type of gradient used in All-Reduce. If ``None``, the dtype of a model is used. Returns: ChainerMN communicator that implements methods defined in :class:`chainermn.CommunicatorBase` """ if mpi_comm is None: try: import mpi4py.MPI except ImportError as e: raise ImportError(str(e) + ': ' 'ChainerMN requires mpi4py for ' 'distributed training. ' 'Please read the Chainer official document ' 'and setup MPI and mpi4py.') mpi_comm = mpi4py.MPI.COMM_WORLD allreduce_grad_dtype, batched_copy = argument.parse_kwargs( kwargs, ('allreduce_grad_dtype', None), ('batched_copy', True)) argument.assert_kwargs_empty(kwargs) if 'batched_copy' in kwargs: warnings.warn("The option 'batched_copy' is enabled by default " "it is deprecated, and will be removed in next version", DeprecationWarning) if communicator_name != 'pure_nccl' and allreduce_grad_dtype is not None: raise ValueError( 'allreduce_grad_dtype is only available ' 'at \'pure_nccl\' communicator.') comm = None if communicator_name == 'naive': from chainermn.communicators.naive_communicator \ import NaiveCommunicator comm = NaiveCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'flat': from chainermn.communicators.flat_communicator \ import FlatCommunicator comm = FlatCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'non_cuda_aware': from chainermn.communicators.non_cuda_aware_communicator \ import NonCudaAwareCommunicator comm = NonCudaAwareCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'pure_nccl': from chainermn.communicators.pure_nccl_communicator \ import PureNcclCommunicator comm = PureNcclCommunicator(mpi_comm=mpi_comm) comm.set_config('allreduce_grad_dtype', allreduce_grad_dtype) elif communicator_name == 'dummy': from chainermn.communicators.dummy_communicator \ import DummyCommunicator comm = DummyCommunicator(mpi_comm=mpi_comm) else: raise ValueError( 'Unrecognized communicator: "{}"'.format(communicator_name)) # As all currently supported communicators are all ancestor of # MpiCommunicator, it is fine calling here for all descendants comm.set_config('batched_copy', batched_copy) return comm
mit
b1e133af57ecadf90dddd443ddfe3fc8
43.94697
78
0.537839
4.464259
false
false
false
false
chainer/chainer
examples/word2vec/search.py
8
1487
#!/usr/bin/env python import argparse import os import numpy import six n_result = 5 # number of search result to show parser = argparse.ArgumentParser() parser.add_argument('--result', default='result', help='Directory of a training result') args = parser.parse_args() with open(os.path.join(args.result, 'word2vec.model'), 'r') as f: ss = f.readline().split() n_vocab, n_units = int(ss[0]), int(ss[1]) word2index = {} index2word = {} w = numpy.empty((n_vocab, n_units), dtype=numpy.float32) for i, line in enumerate(f): ss = line.split() assert len(ss) == n_units + 1 word = ss[0] word2index[word] = i index2word[i] = word w[i] = numpy.array([float(s) for s in ss[1:]], dtype=numpy.float32) s = numpy.sqrt((w * w).sum(1)) w /= s.reshape((s.shape[0], 1)) # normalize try: while True: q = six.moves.input('>> ') if q not in word2index: print('"{0}" is not found'.format(q)) continue v = w[word2index[q]] similarity = w.dot(v) print('query: {}'.format(q)) count = 0 for i in (-similarity).argsort(): if numpy.isnan(similarity[i]): continue if index2word[i] == q: continue print('{0}: {1}'.format(index2word[i], similarity[i])) count += 1 if count == n_result: break except EOFError: pass
mit
f6bf7792df873735159a7b0f588ab8ca
25.553571
75
0.538668
3.402746
false
false
false
false
stopstalk/stopstalk-deployment
aws_lambda/spoj_aws_lambda_function/lambda_code/pip/_vendor/cachecontrol/caches/file_cache.py
33
4177
import hashlib import os from textwrap import dedent from ..cache import BaseCache from ..controller import CacheController try: FileNotFoundError except NameError: # py2.X FileNotFoundError = (IOError, OSError) def _secure_open_write(filename, fmode): # We only want to write to this file, so open it in write only mode flags = os.O_WRONLY # os.O_CREAT | os.O_EXCL will fail if the file already exists, so we only # will open *new* files. # We specify this because we want to ensure that the mode we pass is the # mode of the file. flags |= os.O_CREAT | os.O_EXCL # Do not follow symlinks to prevent someone from making a symlink that # we follow and insecurely open a cache file. if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW # On Windows we'll mark this file as binary if hasattr(os, "O_BINARY"): flags |= os.O_BINARY # Before we open our file, we want to delete any existing file that is # there try: os.remove(filename) except (IOError, OSError): # The file must not exist already, so we can just skip ahead to opening pass # Open our file, the use of os.O_CREAT | os.O_EXCL will ensure that if a # race condition happens between the os.remove and this line, that an # error will be raised. Because we utilize a lockfile this should only # happen if someone is attempting to attack us. fd = os.open(filename, flags, fmode) try: return os.fdopen(fd, "wb") except: # An error occurred wrapping our FD in a file object os.close(fd) raise class FileCache(BaseCache): def __init__( self, directory, forever=False, filemode=0o0600, dirmode=0o0700, use_dir_lock=None, lock_class=None, ): if use_dir_lock is not None and lock_class is not None: raise ValueError("Cannot use use_dir_lock and lock_class together") try: from pip._vendor.lockfile import LockFile from pip._vendor.lockfile.mkdirlockfile import MkdirLockFile except ImportError: notice = dedent( """ NOTE: In order to use the FileCache you must have lockfile installed. You can install it via pip: pip install lockfile """ ) raise ImportError(notice) else: if use_dir_lock: lock_class = MkdirLockFile elif lock_class is None: lock_class = LockFile self.directory = directory self.forever = forever self.filemode = filemode self.dirmode = dirmode self.lock_class = lock_class @staticmethod def encode(x): return hashlib.sha224(x.encode()).hexdigest() def _fn(self, name): # NOTE: This method should not change as some may depend on it. # See: https://github.com/ionrock/cachecontrol/issues/63 hashed = self.encode(name) parts = list(hashed[:5]) + [hashed] return os.path.join(self.directory, *parts) def get(self, key): name = self._fn(key) try: with open(name, "rb") as fh: return fh.read() except FileNotFoundError: return None def set(self, key, value): name = self._fn(key) # Make sure the directory exists try: os.makedirs(os.path.dirname(name), self.dirmode) except (IOError, OSError): pass with self.lock_class(name) as lock: # Write our actual file with _secure_open_write(lock.path, self.filemode) as fh: fh.write(value) def delete(self, key): name = self._fn(key) if not self.forever: try: os.remove(name) except FileNotFoundError: pass def url_to_file_path(url, filecache): """Return the file cache path based on the URL. This does not ensure the file exists! """ key = CacheController.cache_url(url) return filecache._fn(key)
mit
a7ccb53bccac9bcc426bd7412b7c8c8f
27.609589
79
0.593967
4.075122
false
false
false
false
chainer/chainer
chainer/training/extension.py
8
6662
from chainer.utils import argument PRIORITY_WRITER = 300 PRIORITY_EDITOR = 200 PRIORITY_READER = 100 class Extension(object): """Base class of trainer extensions. Extension of :class:`Trainer` is a callable object that takes the trainer object as the argument. It also provides some default configurations as its attributes, e.g. the default trigger and the default priority. This class provides a set of typical default values for these attributes. There are three ways to define users' own extensions: inheriting this class, decorating closures by :func:`make_extension`, or using any callable including lambda functions as extensions. Decorator can slightly reduce the overhead and is much easier to use, while this class provides more flexibility (for example, it can have methods to configure the behavior). Using a lambda function allows one-line coding for simple purposes, but users have to specify the configurations as arguments to :meth:`Trainer.extend`. For a callable not inheriting this class, the default configurations of this class are used unless the user explicitly specifies them in :meth:`Trainer.extend` method. Attributes: trigger: Default value of trigger for this extension. It is set to ``(1, 'iteration')`` by default. priority: Default priority of the extension. It is set to ``PRIORITY_READER`` by default. ~Extension.name: Name of the extension. It is set to ``None`` by default. This value will be overwritten when registering an extension to a trainer. See :meth:`chainer.training.Trainer.extend` for details. """ trigger = 1, 'iteration' priority = PRIORITY_READER name = None @property def default_name(self): """Default name of the extension. It is the name of the class by default. Implementation can override this property, or provide a class attribute to hide it. """ return type(self).__name__ def __call__(self, trainer): """Invokes the extension. Implementations should override this operator. This method is called at iterations which the corresponding trigger accepts. Args: trainer (Trainer): Trainer object that calls this operator. """ raise NotImplementedError( 'Extension implementation must override __call__.') def __getattr__(self, name): if name == 'invoke_before_training': raise AttributeError( 'invoke_before_training has been removed since Chainer ' 'v2.0.0. Use Extension.initialize instead.') raise AttributeError('{} object has no attribute {}'.format( type(self).__name__, name)) def finalize(self): """Finalizes the extension. This method is called at the end of the training loop. """ pass def initialize(self, trainer): """Initializes up the trainer state. This method is called before entering the training loop. An extension that modifies the state of :class:`~chainer.training.Trainer` can override this method to initialize it. When the trainer has been restored from a snapshot, this method has to recover an appropriate part of the state of the trainer. For example, :class:`~chainer.training.extensions.ExponentialShift` extension changes the optimizer's hyperparameter at each invocation. Note that the hyperparameter is not saved to the snapshot; it is the responsibility of the extension to recover the hyperparameter. The :class:`~chainer.training.extensions.ExponentialShift` extension recovers it in its ``initialize`` method if it has been loaded from a snapshot, or just setting the initial value otherwise. Args: trainer (Trainer): Trainer object that runs the training loop. """ pass def on_error(self, trainer, exc, tb): """Handles the error raised during training before finalization. This method is called when an exception is thrown during the training loop, before finalize. An extension that needs different error handling from finalize, can override this method to handle errors. Args: trainer (Trainer): Trainer object that runs the training loop. exc (Exception): arbitrary exception thrown during update loop. tb (traceback): traceback object of the exception """ pass def serialize(self, serializer): """Serializes the extension state. It is called when a trainer that owns this extension is serialized. It serializes nothing by default. """ pass def make_extension(trigger=None, default_name=None, priority=None, finalizer=None, initializer=None, on_error=None, **kwargs): """Decorator to make given functions into trainer extensions. This decorator just adds some attributes to a given function. The value of the attributes are given by the arguments of this decorator. See :class:`Extension` for details of trainer extensions. Most of the default values of arguments also follow those for this class. Args: trigger: Default trigger of the extension. default_name: Default name of the extension. The name of a given function is used by default. priority (int): Default priority of the extension. finalizer: Finalizer function of this extension. It is called at the end of the training loop. initializer: Initializer function of this extension. It is called at the beginning of the training loop. on_error: Error handler callback function of this extension. It is called after an error is raised during the trainer loop. """ if kwargs: msg = ('invoke_before_training has been removed since Chainer v2.0.0. ' 'Use initializer= instead.') argument.check_unexpected_kwargs(kwargs, invoke_before_training=msg) argument.assert_kwargs_empty(kwargs) if trigger is None: trigger = Extension.trigger if priority is None: priority = Extension.priority def decorator(ext): ext.trigger = trigger ext.default_name = default_name or ext.__name__ ext.priority = priority ext.finalize = finalizer ext.on_error = on_error ext.initialize = initializer return ext return decorator
mit
b2510ab6fef319dd12fa6f51211a177f
36.852273
79
0.669168
4.923873
false
false
false
false
chainer/chainer
chainer/training/triggers/minmax_value_trigger.py
10
3888
from chainer import reporter from chainer.training import util class BestValueTrigger(object): """Trigger invoked when specific value becomes best. Args: key (str): Key of value. compare (callable): Compare function which takes current best value and new value and returns whether new value is better than current best. trigger: Trigger that decides the comparison interval between current best value and new value. This must be a tuple in the form of ``<int>, 'epoch'`` or ``<int>, 'iteration'`` which is passed to :class:`~chainer.training.triggers.IntervalTrigger`. """ def __init__(self, key, compare, trigger=(1, 'epoch')): self._key = key self._best_value = None self._interval_trigger = util.get_trigger(trigger) self._init_summary() self._compare = compare def __call__(self, trainer): """Decides whether the extension should be called on this iteration. Args: trainer (~chainer.training.Trainer): Trainer object that this trigger is associated with. The ``observation`` of this trainer is used to determine if the trigger should fire. Returns: bool: ``True`` if the corresponding extension should be invoked in this iteration. """ observation = trainer.observation summary = self._summary key = self._key if key in observation: summary.add({key: observation[key]}) if not self._interval_trigger(trainer): return False stats = summary.compute_mean() value = float(stats[key]) # copy to CPU self._init_summary() if self._best_value is None or self._compare(self._best_value, value): self._best_value = value return True return False def _init_summary(self): self._summary = reporter.DictSummary() def serialize(self, serializer): self._interval_trigger.serialize(serializer['interval_trigger']) self._summary.serialize(serializer['summary']) self._best_value = serializer('best_value', self._best_value) class MaxValueTrigger(BestValueTrigger): """Trigger invoked when specific value becomes maximum. For example you can use this trigger to take snapshot on the epoch the validation accuracy is maximum. Args: key (str): Key of value. The trigger fires when the value associated with this key becomes maximum. trigger: Trigger that decides the comparison interval between current best value and new value. This must be a tuple in the form of ``<int>, 'epoch'`` or ``<int>, 'iteration'`` which is passed to :class:`~chainer.training.triggers.IntervalTrigger`. """ def __init__(self, key, trigger=(1, 'epoch')): super(MaxValueTrigger, self).__init__( key, lambda max_value, new_value: new_value > max_value, trigger) class MinValueTrigger(BestValueTrigger): """Trigger invoked when specific value becomes minimum. For example you can use this trigger to take snapshot on the epoch the validation loss is minimum. Args: key (str): Key of value. The trigger fires when the value associated with this key becomes minimum. trigger: Trigger that decides the comparison interval between current best value and new value. This must be a tuple in the form of ``<int>, 'epoch'`` or ``<int>, 'iteration'`` which is passed to :class:`~chainer.training.triggers.IntervalTrigger`. """ def __init__(self, key, trigger=(1, 'epoch')): super(MinValueTrigger, self).__init__( key, lambda min_value, new_value: new_value < min_value, trigger)
mit
a67bfe6fc87606a5785381345a290ec5
34.345455
79
0.629115
4.684337
false
false
false
false
chainer/chainer
chainer/functions/activation/softmax.py
8
3591
import chainer from chainer import backend from chainer.backends import cuda from chainer import function_node import chainer.functions from chainer.utils import type_check if cuda.cudnn_enabled: cudnn = cuda.cudnn _algorithm = cuda.libcudnn.CUDNN_SOFTMAX_ACCURATE class Softmax(function_node.FunctionNode): """Softmax activation function.""" def __init__(self, axis=1): self.axis = axis def check_type_forward(self, in_types): type_check._argname(in_types, ('x',)) x_type, = in_types type_check.expect( x_type.dtype.kind == 'f', -x_type.ndim <= self.axis < x_type.ndim, ) def forward(self, x): xp = backend.get_array_module(*x) if xp is cuda.cupy and chainer.should_use_cudnn('>=auto'): y = cudnn.softmax_forward(x[0], self.axis, _algorithm) else: y = x[0] - x[0].max(axis=self.axis, keepdims=True) xp.exp(y, out=y) y /= y.sum(axis=self.axis, keepdims=True) self.retain_outputs((0,)) return y, def backward(self, indexes, grad_outputs): y = self.get_retained_outputs()[0] gy, = grad_outputs return _SoftmaxGrad(self.axis).apply((y, gy)) class _SoftmaxGrad(function_node.FunctionNode): def __init__(self, axis): self.axis = axis def forward(self, inputs): self.retain_inputs((0, 1)) y, gy = inputs xp = backend.get_array_module(*y) if xp is cuda.cupy and chainer.should_use_cudnn('>=auto'): gx = cudnn.softmax_backward(y, gy, self.axis, _algorithm) else: gx = y * gy sumdx = gx.sum(axis=self.axis, keepdims=True) gx -= y * sumdx return gx, def backward(self, indexes, grad_outputs): y, gy = self.get_retained_inputs() ggx, = grad_outputs gs = chainer.functions.sum(ggx * y, axis=self.axis, keepdims=True) ga = ggx - chainer.functions.broadcast_to(gs, gy.shape) ret = [] if 0 in indexes: s = chainer.functions.broadcast_to(chainer.functions.sum( y * gy, axis=self.axis, keepdims=True), gy.shape) gy2 = ga * gy - ggx * s ret.append(gy2) if 1 in indexes: ggy = ga * y ret.append(ggy) return tuple(ret) def softmax(x, axis=1): """Softmax function. This function computes its softmax along an axis. Let :math:`c = (c_1, c_2, \\dots, c_D)` be the slice of ``x`` along with the axis. For each slice :math:`c`, it computes the function :math:`f(c)` defined as :math:`f(c)={\\exp(c) \\over \\sum_{d} \\exp(c_d)}`. Args: x (:class:`~chainer.Variable` or :ref:`ndarray`): Input variable. A :math:`n`-dimensional (:math:`n \\geq 2`) float array. axis (int): The axis along which the softmax is to be computed. Returns: ~chainer.Variable: Output variable. A :math:`n`-dimensional (:math:`n \\geq 2`) float array, which is the same shape with x. .. admonition:: Example >>> x = np.array([[0, 1, 2], [0, 2, 4]], np.float32) >>> x array([[0., 1., 2.], [0., 2., 4.]], dtype=float32) >>> y = F.softmax(x, axis=1) >>> y.array array([[0.09003057, 0.24472848, 0.66524094], [0.01587624, 0.11731043, 0.86681336]], dtype=float32) >>> F.sum(y, axis=1).array array([1., 1.], dtype=float32) """ return Softmax(axis=axis).apply((x,))[0]
mit
308ae5a350f8d4953a8b76432cb63728
30.226087
77
0.557783
3.349813
false
false
false
false
chainer/chainer
onnx_chainer/functions/array.py
3
23717
import warnings import chainer import numpy as np import onnx from onnx.mapping import NP_TYPE_TO_TENSOR_TYPE from onnx_chainer.functions.opset_version import support from onnx_chainer import onnx_helper TENSOR_TYPE_TO_NAME = { 0: 'UNDEFINED', 1: 'FLOAT', 2: 'UINT8', 3: 'INT8', 4: 'UINT16', 5: 'INT16', 6: 'INT32', 7: 'INT64', 8: 'STRING', 9: 'BOOL', 10: 'FLOAT16', 11: 'DOUBLE', 12: 'UINT32', 13: 'UINT64', 14: 'COMPLEX64', 15: 'COMPLEX128', } @support((1, 6)) def convert_Cast(func, opset_version, input_names, output_names, context): typ = func.type if isinstance(func.type, np.dtype) else np.dtype(func.type) if opset_version == 1: return onnx_helper.make_node( 'Cast', input_names, output_names, to=TENSOR_TYPE_TO_NAME[NP_TYPE_TO_TENSOR_TYPE[typ]] ), elif opset_version == 6: return onnx_helper.make_node( 'Cast', input_names, output_names, to=NP_TYPE_TO_TENSOR_TYPE[typ] ), @support((1, 4)) def convert_Concat(func, opset_version, input_names, output_names, context): if opset_version == 1: return onnx_helper.make_node( 'Concat', input_names, output_names, axis=func.axis ), elif opset_version == 4: return onnx_helper.make_node( 'Concat', input_names, output_names, axis=func.axis ), def convert_Copy(func, opset_version, input_names, output_names, context): return onnx_helper.make_node( 'Identity', input_names, output_names ), def convert_Depth2Space( func, opset_version, input_names, output_names, context): return onnx_helper.make_node( 'DepthToSpace', input_names, output_names, blocksize=func.r ), def get_slice_node( gb, opset_version, context, input_names, axes, starts, ends, steps): if opset_version < 11 and any([i != 1 for i in steps]): raise ValueError( 'GetItem with n-step slicing is supported from opset11, ' 'opset{} is not supported'.format(opset_version)) if opset_version < 10: return gb.op( 'Slice', input_names, axes=axes, starts=starts, ends=ends) else: inputs = [('starts', starts), ('ends', ends), ('axes', axes)] if opset_version > 10: inputs.append(('steps', steps)) for name, values in inputs: param_name = context.add_const( np.asarray(list(values), dtype=np.int64), name) input_names.append(param_name) return gb.op('Slice', input_names) def _to_ndarray(x, dtype=np.int64): if isinstance(x, list): return np.array(x, dtype=dtype) else: return chainer.cuda.to_cpu(x).astype(dtype) @support((1, 10, 11)) def convert_GetItem(func, opset_version, input_names, output_names, context): x = func.inputs[0] axes, starts, ends, steps = [], [], [], [] squeeze_idxs, unsqueeze_idxs = [], [] skipped = 0 # when set ellipsis, need to skip index rolling prev_gathered_axis = -1 gather_axis = -1 gather_idx = None # when GatherND, set first array for broadcasting gather_nd_idx = None is_used_slice_whole = False # GatherND does not support axis, need to care for i, idx in enumerate(func.slices): # axis means the index of input x, adjust None and Ellipsis counts axis = i - len(unsqueeze_idxs) + skipped if isinstance(idx, slice): if idx.start is None and idx.stop is None and idx.step is None: is_used_slice_whole = True continue axes.append(axis) step = 1 if idx.step is None else idx.step steps.append(step) if step < 0: starts.append( np.iinfo(np.int64).max if idx.start is None else idx.start) ends.append( np.iinfo(np.int64).min if idx.stop is None else idx.stop) else: starts.append(0 if idx.start is None else idx.start) ends.append( np.iinfo(np.int64).max if idx.stop is None else idx.stop) elif isinstance(idx, int): axes.append(axis) steps.append(1) if idx == -1: starts.append(idx) ends.append(np.iinfo(np.int64).max) else: starts.append(idx) ends.append(idx+1) squeeze_idxs.append(axis) elif isinstance(idx, np.ndarray) and idx.ndim == 0: scalar_idx = idx.item() axes.append(axis) starts.append(scalar_idx) ends.append(scalar_idx+1) steps.append(1) squeeze_idxs.append(axis) elif idx is None: unsqueeze_idxs.append(i - len(squeeze_idxs) + skipped) elif idx is Ellipsis: # calculate rest slice number except None, GetItem does not allow # multiple Ellipsis, so ignore latter Ellipsis count rest_slice_len = len( [idx_ for idx_ in func.slices[i+1:] if idx_ is not None]) assert skipped == 0 skipped = len(x.shape) - axis - rest_slice_len - 1 elif isinstance(idx, (list,) + chainer.get_array_types()): if prev_gathered_axis >= 0: if (i - 1) != prev_gathered_axis: raise ValueError( 'ONNX-Chainer does not support non-consecutive' 'multiple advanced indexing') if is_used_slice_whole: raise ValueError( 'ONNX-Chainer does not support whole indexing(`[:]`)' 'in front of multiple advanced indexing') if unsqueeze_idxs: raise ValueError( 'ONNX-Chainer does not support new axis in front of ' 'multiple advanced indexing') # multiple advanced index, convert to GatherND idx_array = _to_ndarray(idx) base_idx = gather_idx if gather_nd_idx is None else\ gather_nd_idx gather_nd_idx = np.vstack((base_idx, idx_array)) prev_gathered_axis = i else: # convert to Gather, if next index is also list, change to # GatherND gather_axis = axis - len(squeeze_idxs) + len(unsqueeze_idxs) gather_idx = _to_ndarray(idx) prev_gathered_axis = i else: raise ValueError( 'GetItem with type {} cannot handle in ONNX Slice, so that ' 'ONNX-Chainer does not accept the type'.format(type(idx))) gb = onnx_helper.GraphBuilder() slice_output = input_names if axes: output = get_slice_node( gb, opset_version, context, slice_output, axes, starts, ends, steps) slice_output = [output] if squeeze_idxs: output = gb.op('Squeeze', slice_output, axes=squeeze_idxs) slice_output = [output] if unsqueeze_idxs: output = gb.op('Unsqueeze', slice_output, axes=unsqueeze_idxs) slice_output = [output] if gather_nd_idx is not None: if opset_version < 11: raise ValueError( 'ONNX-Chainer supports multiple advanced indexing from opset11' ', opset{} is not supported'.format(opset_version)) gather_nd_idx_name = context.add_const(gather_nd_idx.T, 'indices') slice_output.append(gather_nd_idx_name) gb.op('GatherND', slice_output) elif gather_idx is not None: gather_idx_name = context.add_const(gather_idx, 'indices') slice_output.append(gather_idx_name) gb.op('Gather', slice_output, axis=gather_axis) return gb.nodes(output_names=output_names) @support((9, 11)) def convert_SelectItem(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() if opset_version >= 11: t = gb.op('Unsqueeze', [input_names[1]], axes=[1]) out = gb.op('GatherElements', [input_names[0], t], axis=1) gb.op('Squeeze', [out], axes=[1]) else: data, target_idxs = input_names target_idxs = gb.op('Cast', [target_idxs], to=NP_TYPE_TO_TENSOR_TYPE[np.dtype('int64')]) n_rows = gb.op('Shape', [target_idxs]) # This is an equivalent of using Range. one_1 = onnx.helper.make_tensor( 'one_1', onnx.TensorProto.FLOAT, [1], [1]) ones = gb.op('ConstantOfShape', [n_rows], value=one_1) row_idxs = gb.op('Squeeze', [gb.op('NonZero', [ones])]) data_shape = gb.op('Shape', [data]) one_2 = context.add_const(np.array([1]), 'one_2') n_cols = gb.op('Gather', [data_shape, one_2], axis=0) data = gb.op('Squeeze', [gb.op('Flatten', [data], axis=2)]) target_idxs = gb.op( 'Add', [target_idxs, gb.op('Mul', [row_idxs, n_cols])]) gb.op('Gather', [data, target_idxs], axis=0) return gb.nodes(output_names) @support((1, 2, 11)) def convert_Pad(func, opset_version, input_names, output_names, context): if func.mode not in ['constant', 'reflect', 'edge']: raise ValueError( '{} mode is not supported in ONNX\'s Pad operation'.format( func.mode)) pad_begin = [] pad_end = [] pad_bw = func.pad_bw if pad_bw.ndim == 1: pad_bw = np.tile(pad_bw, (len(func.inputs[0].shape), 1)) for pp in pad_bw.tolist(): pad_begin.append(pp[0]) pad_end.append(pp[1]) pad = pad_begin + pad_end constant_value = func.keywords.get('constant_values', None) if constant_value is not None: # 'constant_values' only accepts int or array-like on Chainer if not isinstance(constant_value, int) and len(constant_value) > 1: raise ValueError( 'ONNX doesn\'t support multiple constant values for Pad ' 'operation') elif not isinstance(constant_value, int): constant_value = float(constant_value[0]) else: constant_value = float(constant_value) if opset_version == 1: kwargs = { 'mode': func.mode, 'paddings': pad, } if constant_value is not None: kwargs['value'] = constant_value elif opset_version == 2: kwargs = { 'mode': func.mode, 'pads': pad, } if constant_value is not None: kwargs['value'] = constant_value elif opset_version == 11: pads_name = context.add_const(np.array(pad, dtype=np.int64), 'pads') input_names.append(pads_name) if constant_value is not None: constant_value_name = context.add_const( np.array(constant_value, dtype=np.float32), 'constant_value') input_names.append(constant_value_name) kwargs = {'mode': func.mode} return onnx_helper.make_node('Pad', input_names, output_names, **kwargs), @support((9, 11)) def convert_Permutate(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() indices_name = context.get_name(func.indices) if func.inv: empty = context.add_const( np.zeros(dtype=np.int64, shape=func.indices.shape), 'empty') r = context.add_const(np.arange(len(func.indices), dtype=np.int64), 'range') op = 'ScatterElements' if opset_version == 11 else 'Scatter' indices_name = gb.op(op, [empty, indices_name, r]) input_names.append(indices_name) gb.op_output_named('Gather', input_names, output_names, axis=func.axis) return gb.nodes() @support((1, 5)) def convert_Reshape(func, opset_version, input_names, output_names, context): if opset_version == 1: return onnx_helper.make_node( 'Reshape', input_names, output_names, shape=func.shape ), elif opset_version == 5: if hasattr(func, 'shape'): # if the function has shape parameter, means not dynamic assert len(input_names) == 1 shape_name = context.add_const( np.asarray(list(func.shape), dtype=np.int64), 'shape') input_names.append(shape_name) else: if len(input_names) != 2: raise ValueError('shape must be set as parameter or 2nd input') return onnx_helper.make_node( 'Reshape', input_names, output_names, ), def convert_Space2Depth( func, opset_version, input_names, output_names, context): return onnx_helper.make_node( 'SpaceToDepth', input_names, output_names, blocksize=func.r ), @support((1, 2)) def convert_SplitAxis(func, opset_version, input_names, output_names, context): if func.indices is not None: indices_or_sections = func.indices else: indices_or_sections = func.sections total = func.inputs[0].shape[func.axis] if hasattr(indices_or_sections, '__iter__'): split = [] prev_i = 0 for i in indices_or_sections: split.append(i - prev_i) prev_i = i split.append(total - prev_i) else: length = total // indices_or_sections split = [length for _ in range(indices_or_sections)] assert len(output_names) == len(split) if opset_version == 1: return onnx_helper.make_node( 'Split', input_names, output_names, axis=func.axis, split=split ), elif opset_version == 2: return onnx_helper.make_node( 'Split', input_names, output_names, axis=func.axis, split=split ), def convert_Squeeze(func, opset_version, input_names, output_names, context): if func.axis is None: axis = [] for i, s in enumerate(func.inputs[0].shape): if s == 1: axis.append(i) else: axis = func.axis return onnx_helper.make_node( 'Squeeze', input_names, output_names, axes=axis ), def convert_Swapaxes(func, opset_version, input_names, output_names, context): perm = list(range(len(func.inputs[0].shape))) perm[func.axis1], perm[func.axis2] = perm[func.axis2], perm[func.axis1] return onnx_helper.make_node( 'Transpose', input_names, output_names, perm=perm ), @support((1, 6)) def convert_Tile(func, opset_version, input_names, output_names, context): # Add tiles and axis to graph if isinstance(func.reps, int): func.reps = [func.reps] tiles_name = context.add_const( np.asarray(func.reps, dtype=np.int64), 'tiles') input_names.append(tiles_name) # In operater version = 1, axis also should be given if opset_version == 1: axis_name = context.add_const( np.array([i for i, _ in enumerate(func.reps)], dtype=np.float32), 'axis') input_names.append(axis_name) return onnx_helper.make_node('Tile', input_names, output_names), def convert_Transpose(func, opset_version, input_names, output_names, context): if func.axes is None: node = onnx_helper.make_node('Transpose', input_names, output_names) else: node = onnx_helper.make_node( 'Transpose', input_names, output_names, perm=func.axes ) return node, def convert_ExpandDims( func, opset_version, input_names, output_names, context): axis = func.axis if axis < 0: axis = len(func.inputs[0].shape) + 1 + axis return onnx_helper.make_node( 'Unsqueeze', input_names, output_names, axes=[axis]), @support((9,)) def convert_Where(func, opset_version, input_names, output_names, context): input_names.insert(0, context.get_name(func.condition)) return onnx_helper.make_node('Where', input_names, output_names), @support((7, 9, 10, 11)) def convert_Repeat(func, opset_version, input_names, output_names, context): repeats = func.repeats if len(repeats) > 1: raise NotImplementedError( 'ONNX-Chainer currently does not support elementwise repeat') gb = onnx_helper.GraphBuilder() inputs = list(input_names) axis = func.axis if axis is None: shape_name = context.add_const(np.array([-1], dtype=np.int64), 'shape') input_names.append(shape_name) inputs = [gb.op('Reshape', input_names)] scales = [float(repeats[0])] else: scales = [1.0] * func.inputs[0].data.ndim scales[axis] = float(repeats[0]) if opset_version == 7: gb.op_output_named('Upsample', inputs, output_names, scales=scales) return gb.nodes() scales_name = context.add_const( np.array(scales, dtype=np.float32), 'scales') if opset_version in [9, 10]: inputs.append(scales_name) op = 'Upsample' if opset_version == 9 else 'Resize' gb.op_output_named(op, inputs, output_names) return gb.nodes() if opset_version == 11: roi = context.add_const(np.array([]), 'roi') inputs.extend([roi, scales_name]) gb.op_output_named('Resize', inputs, output_names) return gb.nodes() @support((7, 9, 10, 11)) def convert_ResizeImages( func, opset_version, input_names, output_names, context): warnings.warn( '`resize_images` is mapped to `Upsampling` ONNX op with bilinear ' 'interpolation. ' 'Behavior of bilinear interpolation differs from each implementation. ' 'See the issue https://github.com/chainer/onnx-chainer/issues/147 ' 'for details.', UserWarning) outsize = (func.out_H, func.out_W) h, w = func.inputs[0].shape[2:] # Compute scaling factor. # NOTE(syoyo): Despite of its name, `Upsample` onnx op will downsample # images when scale value is less than 1.0 scales = [1.0, 1.0, float(outsize[0]) / float(h), float(outsize[1]) / float(w)] if (scales[2] < 1.0e-8) and (scales[3] < 1.0e-8): raise ValueError( 'scaling factor is too small or zero. scales for h = {}, scales ' 'for w = {}'.format(scales[2], scales[3])) # resize_images in Chainer only supports bilinear interpolation # Actually this will be mapped to 'bilinear' in onnxruntime mode = 'linear' if opset_version == 7: return onnx_helper.make_node('Upsample', input_names, output_names, scales=scales, mode=mode), scales_name = context.add_const( np.array(scales, dtype=np.float32), 'scales') if opset_version in [9, 10]: input_names.append(scales_name) op = 'Upsample' if opset_version == 9 else 'Resize' return onnx_helper.make_node(op, input_names, output_names, mode=mode), if opset_version == 11: roi_name = context.add_const(np.array([]), 'roi') input_names.extend([roi_name, scales_name]) return onnx_helper.make_node( 'Resize', input_names, output_names, mode=mode), def convert_Stack(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() axis = func.axis if axis < 0: axis = len(func.inputs[0].shape) + 1 + axis # To use concat op, reshape every inputs add new axes inputs = [gb.op('Unsqueeze', [name], axes=[axis]) for name in input_names] gb.op_output_named('Concat', inputs, output_names, axis=axis) return gb.nodes() def convert_Hstack(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() input0_ndim = len(func.inputs[0].shape) inputs = input_names axis = 1 if input0_ndim == 0: inputs = [gb.op('Unsqueeze', [name], axes=[0]) for name in input_names] axis = 0 elif input0_ndim == 1: axis = 0 gb.op_output_named('Concat', inputs, output_names, axis=axis) return gb.nodes() def convert_Vstack(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() input0_ndim = len(func.inputs[0].shape) inputs = input_names if input0_ndim == 0: inputs = [gb.op('Unsqueeze', [name], axes=[0, 1]) for name in input_names] elif input0_ndim == 1: inputs = [gb.op('Unsqueeze', [name], axes=[0]) for name in input_names] gb.op_output_named('Concat', inputs, output_names, axis=0) return gb.nodes() def convert_Dstack(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() input0_ndim = len(func.inputs[0].shape) inputs = input_names if input0_ndim == 0: inputs = [gb.op('Unsqueeze', [name], axes=[0, 1, 2]) for name in input_names] elif input0_ndim == 1: inputs = [gb.op('Unsqueeze', [name], axes=[0, 2]) for name in input_names] elif input0_ndim == 2: inputs = [gb.op('Unsqueeze', [name], axes=[2]) for name in input_names] gb.op_output_named('Concat', inputs, output_names, axis=2) return gb.nodes() def convert_Separate(func, opset_version, input_names, output_names, context): gb = onnx_helper.GraphBuilder() split_outs = gb.op( 'Split', input_names, num_outputs=len(output_names), axis=func.axis) if len(output_names) == 1: split_outs = [split_outs] for i, node_name in enumerate(split_outs): gb.op_output_named( 'Squeeze', [node_name], [output_names[i]], axes=[func.axis]) return gb.nodes() def convert_Shape(func, opset_version, input_names, output_names, context): return onnx_helper.make_node('Shape', input_names, output_names), def convert_Moveaxis(func, opset_version, input_names, output_names, context): ndim = len(func.inputs[0].shape) source = [a % ndim for a in func.source] destination = [a % ndim for a in func.destination] order = [n for n in range(ndim) if n not in source] for dest, src in sorted(zip(destination, source)): order.insert(dest, src) node = onnx_helper.make_node('Transpose', input_names, output_names, perm=order) return node, def convert_Rollaxis(func, opset_version, input_names, output_names, context): ndim = len(func.inputs[0].shape) order = list(range(ndim)) order.remove(func.axis) order.insert(func.start, func.axis) node = onnx_helper.make_node('Transpose', input_names, output_names, perm=order) return node, def convert_TransposeSequence( func, opset_version, input_names, output_names, context): if any(x.shape != func.inputs[0].shape for x in func.inputs): raise ValueError( 'ONNX-Chainer can convert TransposeSequence only when all ' 'inputs have same shape') gb = onnx_helper.GraphBuilder() n = func.inputs[0].shape[0] concat_out = gb.op( 'Concat', [gb.op('Unsqueeze', [name], axes=[0]) for name in input_names], axis=0) perm = list(range(len(func.inputs[0].shape) + 1)) perm[0], perm[1] = perm[1], perm[0] transpose_out = gb.op('Transpose', [concat_out], perm=perm) split_outs = gb.op('Split', [transpose_out], axis=0, num_outputs=n) if n == 1: split_outs = [split_outs] for i, name in enumerate(split_outs): gb.op_output_named('Squeeze', [name], [output_names[i]], axes=[0]) return gb.nodes()
mit
bf2d7a9ca898e8fa44dff2ad1b58c664
34.136296
79
0.586626
3.513109
false
false
false
false
chainer/chainer
chainermn/functions/collective_communication.py
5
12921
import chainer from chainer import backend import numpy class AllGather(chainer.Function): """Collective all-gather communication.""" def __init__(self, comm): chainer.utils.experimental('chainermn.functions.AllGather') self.comm = comm def forward(self, inputs): x, = inputs x_dtype = x.dtype # convert to float32 for communication if numpy.float16 == x_dtype: x = x.astype(numpy.float32) ret = self.comm.allgather(x) # convert back if numpy.float16 == x_dtype: ret = tuple([item.astype(x_dtype) for item in ret]) return ret def backward(self, inputs, grad_outputs): xp = backend.get_array_module(*inputs) grad_dtype = grad_outputs[0].dtype # convert to float32 for communication if numpy.float16 == grad_dtype: grad_outputs = tuple([item.astype(numpy.float32) for item in grad_outputs]) gxs = self.comm.alltoall(grad_outputs) gx = xp.stack(gxs).sum(axis=0) # convert back if numpy.float16 == grad_dtype: gx = gx.astype(grad_dtype) return gx, class AllToAll(chainer.Function): """Collective all-to-all communication.""" def __init__(self, comm): chainer.utils.experimental('chainermn.functions.AllToAll') self.comm = comm def forward(self, inputs): if len(inputs) != self.comm.size: raise ValueError( 'The length of inputs must be same as communicator size.') xs_dtype = inputs[0].dtype # convert to float32 for communication if numpy.float16 == xs_dtype: xs = tuple([x.astype(numpy.float32) for x in inputs]) else: xs = tuple([x for x in inputs]) ret = self.comm.alltoall(xs) # convert back if numpy.float16 == xs_dtype: ret = tuple([item.astype(xs_dtype) for item in ret]) return ret def backward(self, inputs, grad_outputs): assert self.comm.size == len(grad_outputs) xs_dtype = inputs[0].dtype # convert to float32 for communication if numpy.float16 == xs_dtype: gys = tuple([gy.astype(numpy.float32) for gy in grad_outputs]) else: gys = tuple([gy for gy in grad_outputs]) ret = self.comm.alltoall(gys) # convert back if numpy.float16 == xs_dtype: ret = tuple([item.astype(xs_dtype) for item in ret]) return ret class Bcast(chainer.Function): """Collective broadcast communication.""" def __init__(self, comm, root): chainer.utils.experimental('chainermn.functions.Bcast') self.comm = comm self.root = root def __call__(self, *inputs): xp = backend.get_array_module(*inputs) if inputs == (): # Without dummy variable, this function does not "require_grad", # thus back propagation will not be invoked. dummy_var = chainer.Variable( xp.array([], dtype=chainer.config.dtype)) dummy_var.name = 'dummy_var' return super(Bcast, self).__call__(dummy_var) else: return super(Bcast, self).__call__(*inputs) def forward(self, inputs): x_dtype = inputs[0].dtype if self.comm.rank == self.root: x, = inputs # convert to float32 for communication if numpy.float16 == x_dtype: x = x.astype(numpy.float32) else: x = None x = self.comm.bcast(x, self.root), # convert back if numpy.float16 == x_dtype: x = tuple([item.astype(x_dtype) for item in x]) return x def backward(self, inputs, grad_outputs): gx, = grad_outputs gx_dtype = gx.dtype # convert to float32 for communication if numpy.float16 == gx_dtype: gx = gx.astype(numpy.float32) gxs = self.comm.gather(gx, self.root) if self.comm.rank == self.root: xp = backend.get_array_module(*gxs) gxs = xp.stack(gxs) _sum = gxs.sum(axis=0), # convert back if numpy.float16 == gx_dtype: _sum = tuple([item.astype(gx_dtype) for item in _sum]) return _sum else: return None, class Gather(chainer.Function): """Collective gather communication.""" def __init__(self, comm, root): chainer.utils.experimental('chainermn.functions.Gather') self.comm = comm self.root = root def forward(self, inputs): xp = backend.get_array_module(*inputs) x, = inputs # convert to float32 for communication x_dtype = x.dtype if numpy.float16 == x_dtype: x = x.astype(numpy.float32) ys = self.comm.gather(x, self.root) if self.comm.rank == self.root: # convert back if numpy.float16 == x_dtype: ys = tuple([item.astype(x_dtype) for item in ys]) return ys else: # Return an empty variable, which serves as "delegate_variable." return xp.array([], dtype=x_dtype), def backward(self, inputs, grad_outputs): # convert to float32 for communication input_dtype = inputs[0].dtype if self.comm.rank == self.root and numpy.float16 == input_dtype: grad_outputs = tuple([item.astype(numpy.float32) for item in grad_outputs]) ret = self.comm.scatter(grad_outputs, self.root), # convert back if numpy.float16 == input_dtype: ret = tuple([item.astype(input_dtype) for item in ret]) return ret class Scatter(chainer.Function): """Collective scatter communication.""" def __init__(self, comm, root): chainer.utils.experimental('chainermn.functions.Scatter') self.comm = comm self.root = root def __call__(self, *inputs): xp = backend.get_array_module(*inputs) if inputs == (): # Without dummy variable, this function does not "require_grad", # thus back propagation will not be invoked. dummy_var = chainer.Variable( xp.array([], dtype=chainer.config.dtype)) dummy_var.name = 'dummy_var' return super(Scatter, self).__call__(dummy_var) else: return super(Scatter, self).__call__(*inputs) def forward(self, inputs): input_dtype = inputs[0].dtype if self.comm.rank == self.root: # convert to float32 for communication if numpy.float16 == input_dtype: inputs = tuple([item.astype(numpy.float32) for item in inputs]) y = self.comm.scatter(inputs, self.root) else: y = self.comm.scatter(None, self.root) # convert back if numpy.float16 == input_dtype: y = y.astype(input_dtype) return y, def backward(self, inputs, grad_outputs): xp = backend.get_array_module(*inputs) gy, = grad_outputs gy_dtype = gy.dtype # convert to float32 for communication if numpy.float16 == gy_dtype: gy = gy.astype(numpy.float32) gxs = self.comm.gather(gy, self.root) if self.comm.rank == self.root: # convert back if numpy.float16 == gy_dtype: gxs = tuple([item.astype(gy_dtype) for item in gxs]) return gxs else: # Slave processes need to maintain input/output shapes. if inputs == (): dummy_var = tuple([xp.array([], dtype=xp.float32)]) else: dummy_var = tuple([xp.zeros_like(x) for x in inputs]) return dummy_var def allgather(comm, x): """Differentiable all-gather communication between workers. This function invokes gather communications among processes specified by the communicator. Backward will be invoked as well as the ordinary chainer functions, where gradients are reduced to each process. The received array will be on the current CUDA device on the invoking process if ``x`` is on GPU. Please be aware that the current CUDA device is intended one. (``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``) Args: comm: ChainerMN communicator. x (chainer.Variables): Variables to send. Returns: ys (list of chainer.Variables): Received variables. """ chainer.utils.experimental('chainermn.functions.all_gather') return AllGather(comm)(x) def alltoall(comm, xs): """Differentiable all-to-all communication between workers. This function invokes all-to-all communications among processes specified by the communicator. Backward will be invoked as well as the ordinary chainer functions, just passing input gradients back. Unlike point-to-point communication such as ``chainermn.functions.send`` and ``chainermn.functions.recv``, users need not to care about delegate variables, since ``backward()`` will not be invoked until all gradients from output direction arrive. Please refer to ``chainermn.functions.pseudo_connect`` about the detail of delegate variables. The received array will be on the current CUDA device on the invoking process if ``xs`` is on GPU. Please be aware that the current CUDA device is intended one. (``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``) Args: comm: ChainerMN communicator. xs (list of chainer.Variables): Variables to send. Returns: ys (list of chainer.Variables): Received variables. """ chainer.utils.experimental('chainermn.functions.all_to_all') if len(xs) != comm.size: raise ValueError('The length of xs must be same as communicator size.') return AllToAll(comm)(*xs) def bcast(comm, x, root=0): """Differentiable broadcast communication between workers. This function invokes broadcast communications among processes specified by the communicator. Backward will be invoked as well as the ordinary chainer functions, where gradients are gathered to the root process and summed up. The received array will be on the current CUDA device if ``x`` on the invoking process is on GPU. Please be aware that the current CUDA device is intended one. (``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``) Args: comm: ChainerMN communicator. x (chainer.Variable): Variable to be sent. Returns: y (chainer.Variable): Broadcasted variable. """ chainer.utils.experimental('chainermn.functions.bcast') if comm.rank == root: return Bcast(comm, root)(x) else: return Bcast(comm, root)() def gather(comm, x, root=0): """Differentiable gather communication between workers. This function invokes gather communications among processes specified by the communicator. Backward will be invoked as well as the ordinary chainer functions, where gradients are scattered from the root process to each slave. The received array will be on the current CUDA device if ``x`` on the root process is on GPU. Please be aware that the current CUDA device is intended one. (``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``) Args: comm: ChainerMN communicator. x (chainer.Variable): Variable to be sent. Returns: ys (chainer.Variable): Gathered variables. ``None`` for slaves. """ chainer.utils.experimental('chainermn.functions.gather') return Gather(comm, root)(x) def scatter(comm, xs, root=0): """Differentiable scatter communication between workers. This function invokes scatter communications among processes specified by the communicator. Backward will be invoked as well as the ordinary chainer functions, where gradients are gathered to the root process. The received array will be on the current CUDA device if ``xs`` on the root process is on GPU. Please be aware that the current CUDA device is intended one. (``https://docs-cupy.chainer.org/en/stable/tutorial/basic.html#current-device``) Args: comm: ChainerMN communicator. xs (list of chainer.Variable): Variables to be scattered for master process. ``None`` for slave process. Returns: y (chainer.Variable): Scattered variable. """ chainer.utils.experimental('chainermn.functions.scatter') if comm.rank == root: return Scatter(comm, root)(*xs) else: return Scatter(comm, root)()
mit
392ed65632710da4a15f8ffdf0a6c39e
31.3025
84
0.6152
4.101905
false
false
false
false
chainer/chainer
chainer/training/triggers/once_trigger.py
5
1517
import warnings class OnceTrigger(object): """Trigger based on the starting point of the iteration. This trigger accepts only once at starting point of the iteration. There are two ways to specify the starting point: only starting point in whole iteration or called again when training resumed. Args: call_on_resume (bool): Whether the extension is called again or not when restored from a snapshot. It is set to ``False`` by default. Attributes: finished (bool): Flag that indicates whether or not this trigger will fire in the future. This flag is used to determine if the extension should be initialized after resume. """ def __init__(self, call_on_resume=False): self._flag_first = True self._flag_resumed = call_on_resume @property def finished(self): return not (self._flag_first or self._flag_resumed) def __call__(self, trainer): fire = not self.finished self._flag_resumed = False self._flag_first = False return fire def serialize(self, serializer): try: self._flag_first = serializer('_flag_first', self._flag_first) except KeyError: warnings.warn( 'The flag is not saved.' 'OnceTrigger guess it is not first when resumed. ' 'If this trigger is resumed before first called, ' 'it may not work correctly.') self._flag_first = False
mit
c0d99a911ff2188fc445a1c3be56155c
31.978261
77
0.624918
4.610942
false
false
false
false
chainer/chainer
chainer/iterators/multiprocess_iterator.py
6
22878
from __future__ import division import datetime import multiprocessing from multiprocessing import sharedctypes # type: ignore import signal import sys import threading import warnings import numpy import six from chainer.dataset import iterator from chainer.iterators import _statemachine from chainer.iterators.order_samplers import ShuffleOrderSampler _response_time = 0.1 def _raise_timeout_warning(): warnings.warn( 'Stalled dataset is detected. ' 'See the documentation of MultiprocessIterator for common causes and ' 'workarounds:\n' 'https://docs.chainer.org/en/stable/reference/generated/' 'chainer.iterators.MultiprocessIterator.html', MultiprocessIterator.TimeoutWarning) class MultiprocessIterator(iterator.Iterator): """Dataset iterator that loads examples in parallel. This is an implementation of :class:`~chainer.dataset.Iterator` that loads examples with worker processes. It uses the standard :mod:`multiprocessing` module to parallelize the loading. The dataset is sent to the worker processes in the standard way using pickle. Note that this iterator effectively prefetches the examples for the next batch asynchronously after the current batch is returned. This iterator saves ``-1`` instead of ``None`` in snapshots since some serializers do not support ``None``. .. note:: When you are using OpenCV somewhere in your code and the ``MultiprocessIterator`` is used in the training code, the training loop may get stuck at some point. In such situation, there are several workarounds to prevent the process got stuck. 1. Set the environment variable as follows: ``OMP_NUM_THREADS=1`` 2. Add ``cv2.setNumThreads(0)`` right after ``import cv2`` in your training script. 3. Use :class:`~chainer.iterators.MultithreadIterator` instead of ``MultiprocessIterator``. Args: dataset (~chainer.dataset.Dataset): Dataset to iterate. batch_size (int): Number of examples within each batch. repeat (bool): If ``True``, it infinitely loops over the dataset. Otherwise, it stops iteration at the end of the first epoch. shuffle (bool): If ``True``, the order of examples is shuffled at the beginning of each epoch. Otherwise, examples are extracted in the order of indexes. If ``None`` and no ``order_sampler`` is given, the behavior is the same as the case with ``shuffle=True``. n_processes (int): Number of worker processes. The number of CPUs is used by default. n_prefetch (int): Number of prefetch batches. shared_mem (int): The size of using shared memory per data. If ``None``, size is adjusted automatically. dataset_timeout (float): :class:`MultiprocessIterator.TimeoutWarning` will be issued after this time in seconds elapsed in each dataset realization. ``None`` to disable the warning. You can turn this warning into an error by using :func:`warnings.simplefilter`:: warnings.simplefilter( 'error', chainer.iterators.MultiprocessIterator.TimeoutWarning) order_sampler (callable): A callable that generates the order of the indices to sample in the next epoch when a epoch finishes. This function should take two arguments: the current order and the current position of the iterator. This should return the next order. The size of the order should remain constant. This option cannot be used when ``shuffle`` is not ``None``. maxtasksperchild (int): Number of tasks a worker of prefetch process can complete before it will exit and be replaced with a fresh worker process, to enable unused resources to be freed. If ``None``, worker processes will live as long as the pool. """ class TimeoutWarning(RuntimeWarning): pass _interruption_testing = False # for testing _finalized = False _prefetch_loop = None _comm = None def __init__(self, dataset, batch_size, repeat=True, shuffle=None, n_processes=None, n_prefetch=1, shared_mem=None, order_sampler=None, dataset_timeout=30.0, maxtasksperchild=None): self.dataset = dataset self.batch_size = batch_size self.repeat = repeat self.shuffle = shuffle self.n_processes = n_processes or multiprocessing.cpu_count() self.n_prefetch = max(n_prefetch, 1) self.shared_mem = shared_mem self.dataset_timeout = dataset_timeout self._maxtasksperchild = maxtasksperchild if self.shuffle is not None: if order_sampler is not None: raise ValueError('`shuffle` is not `None` and a custom ' '`order_sampler` is set. Please set ' '`shuffle` to `None` to use the custom ' 'order sampler.') else: if self.shuffle: order_sampler = ShuffleOrderSampler() else: if order_sampler is None: order_sampler = ShuffleOrderSampler() self.order_sampler = order_sampler self._initialize_loop() def _initialize_loop(self): self._comm = _Communicator(self.n_prefetch, self.dataset_timeout) self.reset() self._prefetch_loop = _PrefetchLoop( self.dataset, self.batch_size, self.repeat, self.n_processes, self.n_prefetch, self.shared_mem, self._comm, self.order_sampler, self._interruption_testing, self._maxtasksperchild) # defer launching prefetch thread until creating the worker pool, # not to leave a background thread in forked processes. def __next__(self): measure_mode = False if self._prefetch_loop.thread is None: if self._prefetch_loop.measure_required(): measure_mode = True batch, state = self._prefetch_loop.measure( self.dataset_timeout) self._prefetch_loop.launch_thread() if not measure_mode: batch, state = self._comm.get() self._previous_epoch_detail = self.epoch_detail self._state = state if batch is None: raise StopIteration else: return batch next = __next__ def finalize(self): if self._finalized: return if self._comm is not None: self._comm.terminate() if self._prefetch_loop is not None: self._prefetch_loop.terminate() self._comm = None self._prefetch_loop = None self._finalized = True def __copy__(self): # This function is implemented for backward compatibility. # Please use `reset` normally. other = MultiprocessIterator( self.dataset, self.batch_size, self.repeat, shuffle=None, n_processes=self.n_processes, n_prefetch=self.n_prefetch, shared_mem=self.shared_mem, order_sampler=self.order_sampler) other._reset_state(self.current_position, self.epoch, self.is_new_epoch, self._state.order) other._previous_epoch_detail = self._previous_epoch_detail return other @property def current_position(self): return self._state.current_position @property def epoch(self): return self._state.epoch @property def is_new_epoch(self): return self._state.is_new_epoch @property def epoch_detail(self): return self.epoch + self.current_position / self._epoch_size @property def previous_epoch_detail(self): if self._previous_epoch_detail < 0: return None return self._previous_epoch_detail def serialize(self, serializer): current_position = serializer('current_position', self.current_position) epoch = serializer('epoch', self.epoch) is_new_epoch = serializer('is_new_epoch', self.is_new_epoch) order = self._state.order.copy() try: serializer('order', order) except KeyError: serializer('_order', order) self._reset_state(current_position, epoch, is_new_epoch, order) try: self._previous_epoch_detail = serializer( 'previous_epoch_detail', self._previous_epoch_detail) except KeyError: # guess previous_epoch_detail for older version self._previous_epoch_detail = self.epoch + \ (self.current_position - self.batch_size) / self._epoch_size if self.epoch_detail > 0: self._previous_epoch_detail = max( self._previous_epoch_detail, 0.) else: self._previous_epoch_detail = -1. def reset(self): if self.order_sampler is None: order = None else: order = self.order_sampler(numpy.arange(len(self.dataset)), 0) self._reset_state(0, 0, False, order) self._previous_epoch_detail = -1. def _reset_state(self, current_position, epoch, is_new_epoch, order): if self._finalized: raise NotImplementedError( 'Reset of finalized MultiProcessIterator is currently not ' 'supported.') self._state = _statemachine.IteratorState( current_position, epoch, is_new_epoch, order) self._comm.reset(self._state) @property def _epoch_size(self): order = self._state.order if order is None: epoch_size = len(self.dataset) else: epoch_size = len(order) return epoch_size def __getstate__(self): # We trick the serializer to fill a dict for us # this allows us to use the same code for both # chainer and pickle serializers state = {} self.serialize(lambda k, v: state.__setitem__(k, v)) self._reset_state(self.current_position, self.epoch, self.is_new_epoch, state['order']) # Unpickling resets the instance without calling __init__ # Chainer serializers dumps the state in an existing # object hence we need to save the initial parameters too init = self.__dict__.copy() del init['_comm'] del init['_state'] del init['_prefetch_loop'] # TODO(ecastill): When pickling this object there is the risk to copy # the entire dataset. If the dataset is entirely in memory # it can be duplicated when spawning new processes. state['init'] = init return state def __setstate__(self, state): self.__dict__.update(state['init']) self._initialize_loop() # Iterator state is restored after initialization self._reset_state(state['current_position'], state['epoch'], state['is_new_epoch'], state['order']) self._previous_epoch_detail = state['previous_epoch_detail'] class _Communicator(object): STATUS_CONTINUE = 0 STATUS_RESET = 1 STATUS_TERMINATE = 2 def __init__(self, n_prefetch, dataset_timeout): self.n_prefetch = n_prefetch self.dataset_timeout = dataset_timeout self._lock = threading.Lock() self._not_empty_cond = threading.Condition(self._lock) self._not_full_cond = threading.Condition(self._lock) self._batch_queue = [] self._status = _Communicator.STATUS_CONTINUE self._reset_count = 0 @property def is_terminated(self): with self._lock: return self._status == _Communicator.STATUS_TERMINATE # called from iterator def get(self): with self._lock: start = datetime.datetime.now() while not self._batch_queue: self._not_empty_cond.wait(_response_time) dt = datetime.datetime.now() - start if (self.dataset_timeout is not None and dt > datetime.timedelta( seconds=self.dataset_timeout)): _raise_timeout_warning() batch, prefetch_state = self._batch_queue.pop(0) self._not_full_cond.notify() return batch, prefetch_state # called from iterator def reset(self, prefetch_state): with self._lock: self._status = _Communicator.STATUS_RESET self._prefetch_state = prefetch_state self._batch_queue = [] self._not_full_cond.notify() self._reset_count += 1 # called from iterator def terminate(self): with self._lock: self._status = _Communicator.STATUS_TERMINATE self._batch_queue = [] self._not_full_cond.notify() self._reset_count += 1 # called from thread def check(self): with self._lock: status = self._status self._status = _Communicator.STATUS_CONTINUE prefetch_state = None if status == _Communicator.STATUS_RESET: prefetch_state = self._prefetch_state return status, prefetch_state, self._reset_count # called from thread def put(self, batch, prefetch_state, reset_count): with self._lock: if len(self._batch_queue) == self.n_prefetch: self._not_full_cond.wait() if reset_count == self._reset_count: self._batch_queue.append((batch, prefetch_state)) self._not_empty_cond.notify() class _PrefetchLoop(object): _thread = None _pool = None _terminating = False def __init__(self, dataset, batch_size, repeat, n_processes, n_prefetch, mem_size, comm, order_sampler, _interruption_testing, maxtasksperchild): self.dataset = dataset self.batch_size = batch_size self.repeat = repeat self.n_processes = n_processes self.mem_size = mem_size self._comm = comm self.order_sampler = order_sampler self.maxtasksperchild = maxtasksperchild self._allocate_shared_memory() self._interruption_testing = _interruption_testing def terminate(self): self._terminating = True # Terminate the thread first because it depends on the pool. if self._thread is not None: while self._thread.is_alive(): self._thread.join(_response_time) if self._pool is not None: self._pool.terminate() self._thread = None self._pool = None @property def thread(self): return self._thread def measure_required(self): return self.mem_size is None def measure(self, dataset_timeout): # dataset_timeout: timeout in seconds or None status, prefetch_state, _ = self._comm.check() if status == _Communicator.STATUS_RESET: self.prefetch_state = prefetch_state self.prefetch_state, indices = _statemachine.iterator_statemachine( self.prefetch_state, self.batch_size, self.repeat, self.order_sampler, len(self.dataset)) if indices is None: # stop iteration batch = None else: batch_ret = [None] def fetch_batch(): batch_ret[0] = [self.dataset[idx] for idx in indices] if dataset_timeout is None: # Timeout is not set: fetch synchronously fetch_batch() else: # Timeout is set: fetch asynchronously and watch for timeout thr = threading.Thread(target=fetch_batch) thr.daemon = True thr.start() thr.join(dataset_timeout) if thr.is_alive(): _raise_timeout_warning() thr.join() batch = batch_ret[0] self.mem_size = max(map(_measure, batch)) self._allocate_shared_memory() return batch, self.prefetch_state def _allocate_shared_memory(self): if self.measure_required(): self.mem_bulk = None else: self.mem_bulk = \ sharedctypes.RawArray('b', self.batch_size * self.mem_size) def launch_thread(self): self._pool = multiprocessing.Pool( processes=self.n_processes, initializer=_fetch_setup, initargs=(self.dataset, self.mem_size, self.mem_bulk), maxtasksperchild=self.maxtasksperchild) if self._interruption_testing: pids = self._pool.map(_report_pid, range(self.n_processes)) print(' '.join(map(str, pids))) sys.stdout.flush() thread = threading.Thread(target=self._run, name='prefetch_loop') thread.setDaemon(True) thread.start() self._thread = thread return thread def _run(self): # The entry routine of the prefetch thread. alive = True try: while alive: if self._terminating: break alive = self._task() finally: self._pool.close() self._pool.join() def _task(self): # Do a single task in the prefetch thread. # Returns a bool indicating whether the loop should continue running. status, prefetch_state, reset_count = self._comm.check() if status == _Communicator.STATUS_RESET: self.prefetch_state = prefetch_state elif status == _Communicator.STATUS_TERMINATE: return False # stop loop self.prefetch_state, indices = _statemachine.iterator_statemachine( self.prefetch_state, self.batch_size, self.repeat, self.order_sampler, len(self.dataset)) if indices is None: # stop iteration batch = None else: future = self._pool.map_async(_fetch_run, enumerate(indices)) while True: try: data_all = future.get(_response_time) except multiprocessing.TimeoutError: if self._comm.is_terminated: return False else: break batch = [_unpack(data, self.mem_bulk) for data in data_all] self._comm.put(batch, self.prefetch_state, reset_count) return True # Using `parameterized` function (e.g. bound method) with Pool is tricky due to # restrictions imposed by Pickle. Picklable types differ across versions. # Just using top-level function with globals seems to be safest. # it doesn't mean thread safety broken or global variables visible; # notice that each process uses different address space. # To make static linter happy, we first initialize global variables. _fetch_dataset = None _fetch_mem_size = None _fetch_mem_bulk = None def _fetch_setup(dataset, mem_size, mem_bulk): global _fetch_dataset, _fetch_mem_size, _fetch_mem_bulk signal.signal(signal.SIGINT, signal.SIG_IGN) _fetch_dataset = dataset _fetch_mem_size = mem_size _fetch_mem_bulk = mem_bulk def _fetch_run(inputs): i, index = inputs data = _fetch_dataset[index] if _fetch_mem_bulk is not None: offset = i * _fetch_mem_size limit = offset + _fetch_mem_size data = _pack(data, _fetch_mem_bulk, offset, limit) return data def _report_pid(_): # for testing return multiprocessing.current_process().pid class _PackedNdarray(object): def __init__(self, array, mem, offset): self.shape = array.shape self.dtype = array.dtype self.nbytes = array.nbytes self.size = array.size self.offset = offset total = self.offset + self.nbytes if total > len(mem): raise ValueError( 'Shared memory size is too small. expect:{}, actual:{}'.format( total, len(mem))) target = numpy.frombuffer(mem, self.dtype, self.size, self.offset) target[...] = array.ravel() def unpack(self, mem): ret = numpy.frombuffer(mem, self.dtype, self.size, self.offset) ret = ret.reshape(self.shape).copy() return ret def _measure(data): expect = 0 t = type(data) if t is tuple or t is list or t is dict: for v in data: if isinstance(v, numpy.ndarray): expect += v.nbytes return expect def _pack(data, mem, offset, limit): if len(mem) == 0: return data t = type(data) over = False if t is tuple or t is list: ret = [] for v in data: if isinstance(v, numpy.ndarray): if v.nbytes + offset > limit: over = True else: v = _PackedNdarray(v, mem, offset) offset += v.nbytes ret.append(v) data = t(ret) elif t is dict: ret = {} for k, v in six.iteritems(data): if isinstance(v, numpy.ndarray): if v.nbytes + offset > limit: over = True else: v = _PackedNdarray(v, mem, offset) offset += v.nbytes ret[k] = v data = ret elif t is numpy.ndarray: if data.nbytes + offset > limit: over = True else: data = _PackedNdarray(data, mem, offset) offset += data.nbytes if over: expect = _measure(data) warnings.warn( 'Shared memory size is too small.\n' + 'Please set shared_mem option for MultiprocessIterator.\n' + 'Expect shared memory size: {} bytes.\n'.format(expect) + 'Actual shared memory size: {} bytes.'.format(limit - offset), UserWarning) return data def _unpack(data, mem): if len(mem) == 0: return data t = type(data) if t is tuple or t is list: ret = [] for v in data: if isinstance(v, _PackedNdarray): v = v.unpack(mem) ret.append(v) data = t(ret) elif t is dict: ret = {} for k, v in six.iteritems(data): if isinstance(v, _PackedNdarray): v = v.unpack(mem) ret[k] = v data = ret elif t is _PackedNdarray: data = data.unpack(mem) return data
mit
8fedb525802568e8b47ae84a61d7100b
34.035222
79
0.584623
4.346125
false
false
false
false
stopstalk/stopstalk-deployment
aws_lambda/spoj_aws_lambda_function/lambda_code/lxml/html/builder.py
150
4310
# -------------------------------------------------------------------- # The ElementTree toolkit is # Copyright (c) 1999-2004 by Fredrik Lundh # -------------------------------------------------------------------- """ A set of HTML generator tags for building HTML documents. Usage:: >>> from lxml.html.builder import * >>> html = HTML( ... HEAD( TITLE("Hello World") ), ... BODY( CLASS("main"), ... H1("Hello World !") ... ) ... ) >>> import lxml.etree >>> print lxml.etree.tostring(html, pretty_print=True) <html> <head> <title>Hello World</title> </head> <body class="main"> <h1>Hello World !</h1> </body> </html> """ from lxml.builder import ElementMaker from lxml.html import html_parser E = ElementMaker(makeelement=html_parser.makeelement) # elements A = E.a # anchor ABBR = E.abbr # abbreviated form (e.g., WWW, HTTP, etc.) ACRONYM = E.acronym # ADDRESS = E.address # information on author APPLET = E.applet # Java applet (DEPRECATED) AREA = E.area # client-side image map area B = E.b # bold text style BASE = E.base # document base URI BASEFONT = E.basefont # base font size (DEPRECATED) BDO = E.bdo # I18N BiDi over-ride BIG = E.big # large text style BLOCKQUOTE = E.blockquote # long quotation BODY = E.body # document body BR = E.br # forced line break BUTTON = E.button # push button CAPTION = E.caption # table caption CENTER = E.center # shorthand for DIV align=center (DEPRECATED) CITE = E.cite # citation CODE = E.code # computer code fragment COL = E.col # table column COLGROUP = E.colgroup # table column group DD = E.dd # definition description DEL = getattr(E, 'del') # deleted text DFN = E.dfn # instance definition DIR = E.dir # directory list (DEPRECATED) DIV = E.div # generic language/style container DL = E.dl # definition list DT = E.dt # definition term EM = E.em # emphasis FIELDSET = E.fieldset # form control group FONT = E.font # local change to font (DEPRECATED) FORM = E.form # interactive form FRAME = E.frame # subwindow FRAMESET = E.frameset # window subdivision H1 = E.h1 # heading H2 = E.h2 # heading H3 = E.h3 # heading H4 = E.h4 # heading H5 = E.h5 # heading H6 = E.h6 # heading HEAD = E.head # document head HR = E.hr # horizontal rule HTML = E.html # document root element I = E.i # italic text style IFRAME = E.iframe # inline subwindow IMG = E.img # Embedded image INPUT = E.input # form control INS = E.ins # inserted text ISINDEX = E.isindex # single line prompt (DEPRECATED) KBD = E.kbd # text to be entered by the user LABEL = E.label # form field label text LEGEND = E.legend # fieldset legend LI = E.li # list item LINK = E.link # a media-independent link MAP = E.map # client-side image map MENU = E.menu # menu list (DEPRECATED) META = E.meta # generic metainformation NOFRAMES = E.noframes # alternate content container for non frame-based rendering NOSCRIPT = E.noscript # alternate content container for non script-based rendering OBJECT = E.object # generic embedded object OL = E.ol # ordered list OPTGROUP = E.optgroup # option group OPTION = E.option # selectable choice P = E.p # paragraph PARAM = E.param # named property value PRE = E.pre # preformatted text Q = E.q # short inline quotation S = E.s # strike-through text style (DEPRECATED) SAMP = E.samp # sample program output, scripts, etc. SCRIPT = E.script # script statements SELECT = E.select # option selector SMALL = E.small # small text style SPAN = E.span # generic language/style container STRIKE = E.strike # strike-through text (DEPRECATED) STRONG = E.strong # strong emphasis STYLE = E.style # style info SUB = E.sub # subscript SUP = E.sup # superscript TABLE = E.table # TBODY = E.tbody # table body TD = E.td # table data cell TEXTAREA = E.textarea # multi-line text field TFOOT = E.tfoot # table footer TH = E.th # table header cell THEAD = E.thead # table header TITLE = E.title # document title TR = E.tr # table row TT = E.tt # teletype or monospaced text style U = E.u # underlined text style (DEPRECATED) UL = E.ul # unordered list VAR = E.var # instance of a variable or program argument # attributes (only reserved words are included here) ATTR = dict def CLASS(v): return {'class': v} def FOR(v): return {'for': v}
mit
3d3e9363d235c26d828f908cf6792fc7
31.406015
82
0.662645
3.359314
false
false
false
false
chainer/chainer
chainer/functions/math/logsumexp.py
6
3116
import six import chainer from chainer import backend from chainer import function_node from chainer import utils from chainer.utils import type_check import chainerx class LogSumExp(function_node.FunctionNode): def __init__(self, axis=None): if axis is None: self.axis = None elif isinstance(axis, six.integer_types): self.axis = (axis,) elif isinstance(axis, tuple) and all( isinstance(a, six.integer_types) for a in axis): if len(set(axis)) != len(axis): raise ValueError('duplicate value in axis: ({})'.format( ', '.join(map(str, axis)))) self.axis = axis else: raise TypeError('None, int or tuple of int are required') def check_type_forward(self, in_types): type_check._argname(in_types, ('x',)) type_check.expect(in_types[0].dtype.kind == 'f') if self.axis is not None: for axis in self.axis: if axis >= 0: type_check.expect( axis < in_types[0].ndim, ) else: type_check.expect( -axis - 1 < in_types[0].ndim, ) def forward_chainerx(self, inputs): return chainerx.logsumexp(inputs[0], self.axis), def forward(self, inputs): self.retain_inputs((0,)) self.retain_outputs((0,)) xp = backend.get_array_module(*inputs) x, = inputs m = x.max(axis=self.axis, keepdims=True) y = utils.force_array(x - m) xp.exp(y, out=y) y_sum = y.sum(axis=self.axis) y = xp.asarray(xp.log(y_sum) + m.reshape(y_sum.shape)) return y, def backward(self, indexes, grads): x, = self.get_retained_inputs() y, = self.get_retained_outputs() gy, = grads if self.axis is not None: actual_axis = [] for axis in self.axis: if axis < 0: axis = len(x.shape) + axis actual_axis.append(axis) for axis in sorted(actual_axis): gy = chainer.functions.expand_dims(gy, axis=axis) y = chainer.functions.expand_dims(y, axis=axis) gy = chainer.functions.broadcast_to(gy, x.shape) y = chainer.functions.broadcast_to(y, x.shape) gx = gy * chainer.functions.exp(x - y) return gx, def logsumexp(x, axis=None): """Log-sum-exp of array elements over a given axis. This function calculates logarithm of sum of exponential of array elements. .. math:: y_i = \\log\\left(\\sum_j \\exp(x_{ij})\\right) Args: x (:class:`~chainer.Variable` or :ref:`ndarray`): Elements to log-sum-exp. axis (None, int, or tuple of int): Axis which a sum is performed. The default (axis = None) is perform a sum over all the dimensions of the input array. Returns: ~chainer.Variable: Output variable. """ return LogSumExp(axis).apply((x,))[0]
mit
3134242878e0fb775499e185fa4d7c31
30.795918
79
0.544288
3.80464
false
false
false
false
chainer/chainer
chainer/dataset/download.py
12
5087
import hashlib import os import shutil import sys import filelock from six.moves.urllib import request from chainer import utils _dataset_root = os.environ.get( 'CHAINER_DATASET_ROOT', os.path.join(os.path.expanduser('~'), '.chainer', 'dataset')) def get_dataset_root(): """Gets the path to the root directory to download and cache datasets. Returns: str: The path to the dataset root directory. """ return _dataset_root def set_dataset_root(path): """Sets the root directory to download and cache datasets. There are two ways to set the dataset root directory. One is by setting the environment variable ``CHAINER_DATASET_ROOT``. The other is by using this function. If both are specified, one specified via this function is used. The default dataset root is ``$HOME/.chainer/dataset``. Args: path (str): Path to the new dataset root directory. """ global _dataset_root _dataset_root = path def get_dataset_directory(dataset_name, create_directory=True): """Gets the path to the directory of given dataset. The generated path is just a concatenation of the global root directory (see :func:`set_dataset_root` for how to change it) and the dataset name. The dataset name can contain slashes, which are treated as path separators. Args: dataset_name (str): Name of the dataset. create_directory (bool): If True (default), this function also creates the directory at the first time. If the directory already exists, then this option is ignored. Returns: str: Path to the dataset directory. """ path = os.path.join(_dataset_root, dataset_name) if create_directory: try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise return path def cached_download(url): """Downloads a file and caches it. It downloads a file from the URL if there is no corresponding cache. After the download, this function stores a cache to the directory under the dataset root (see :func:`set_dataset_root`). If there is already a cache for the given URL, it just returns the path to the cache without downloading the same file. .. note:: This function raises :class:`OSError` when it fails to create the cache directory. In older version, it raised :class:`RuntimeError`. Args: url (str): URL to download from. Returns: str: Path to the downloaded file. """ cache_root = os.path.join(_dataset_root, '_dl_cache') try: os.makedirs(cache_root) except OSError: if not os.path.isdir(cache_root): raise lock_path = os.path.join(cache_root, '_dl_lock') urlhash = hashlib.md5(url.encode('utf-8')).hexdigest() cache_path = os.path.join(cache_root, urlhash) with filelock.FileLock(lock_path): if os.path.exists(cache_path): return cache_path with utils.tempdir(dir=cache_root) as temp_root: temp_path = os.path.join(temp_root, 'dl') sys.stderr.write('Downloading from {}...\n'.format(url)) sys.stderr.flush() request.urlretrieve(url, temp_path) with filelock.FileLock(lock_path): shutil.move(temp_path, cache_path) return cache_path def cache_or_load_file(path, creator, loader): """Caches a file if it does not exist, or loads it otherwise. This is a utility function used in dataset loading routines. The ``creator`` creates the file to given path, and returns the content. If the file already exists, the ``loader`` is called instead, and it loads the file and returns the content. Note that the path passed to the creator is temporary one, and not same as the path given to this function. This function safely renames the file created by the creator to a given path, even if this function is called simultaneously by multiple threads or processes. Args: path (str): Path to save the cached file. creator: Function to create the file and returns the content. It takes a path to temporary place as the argument. Before calling the creator, there is no file at the temporary path. loader: Function to load the cached file and returns the content. Returns: It returns the returned values by the creator or the loader. """ if os.path.exists(path): return loader(path) try: os.makedirs(_dataset_root) except OSError: if not os.path.isdir(_dataset_root): raise RuntimeError('cannot create dataset directory') lock_path = os.path.join(_dataset_root, '_create_lock') with utils.tempdir() as temp_dir: file_name = os.path.basename(path) temp_path = os.path.join(temp_dir, file_name) content = creator(temp_path) with filelock.FileLock(lock_path): if not os.path.exists(path): shutil.move(temp_path, path) return content
mit
bde72939d56aa58fcbb412408ce10e99
30.993711
79
0.660704
4.145884
false
false
false
false
stopstalk/stopstalk-deployment
aws_lambda/spoj_aws_lambda_function/lambda_code/requests/packages/urllib3/util/timeout.py
707
9596
from __future__ import absolute_import # The default socket timeout, used by httplib to indicate that no timeout was # specified by the user from socket import _GLOBAL_DEFAULT_TIMEOUT import time from ..exceptions import TimeoutStateError # A sentinel value to indicate that no timeout was specified by the user in # urllib3 _Default = object() def current_time(): """ Retrieve the current time. This function is mocked out in unit testing. """ return time.time() class Timeout(object): """ Timeout configuration. Timeouts can be defined as a default for a pool:: timeout = Timeout(connect=2.0, read=7.0) http = PoolManager(timeout=timeout) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool):: response = http.request('GET', 'http://example.com/', timeout=Timeout(10)) Timeouts can be disabled by setting all the parameters to ``None``:: no_timeout = Timeout(connect=None, read=None) response = http.request('GET', 'http://example.com/, timeout=no_timeout) :param total: This combines the connect and read timeouts into one; the read timeout will be set to the time leftover from the connect attempt. In the event that both a connect timeout and a total are specified, or a read timeout and a total are specified, the shorter timeout will be applied. Defaults to None. :type total: integer, float, or None :param connect: The maximum amount of time to wait for a connection attempt to a server to succeed. Omitting the parameter will default the connect timeout to the system default, probably `the global default timeout in socket.py <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_. None will set an infinite timeout for connection attempts. :type connect: integer, float, or None :param read: The maximum amount of time to wait between consecutive read operations for a response from the server. Omitting the parameter will default the read timeout to the system default, probably `the global default timeout in socket.py <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_. None will set an infinite timeout. :type read: integer, float, or None .. note:: Many factors can affect the total amount of time for urllib3 to return an HTTP response. For example, Python's DNS resolver does not obey the timeout specified on the socket. Other factors that can affect total request time include high CPU load, high swap, the program running at a low priority level, or other behaviors. In addition, the read and total timeouts only measure the time between read operations on the socket connecting the client and the server, not the total amount of time for the request to return a complete response. For most requests, the timeout is raised because the server has not sent the first byte in the specified time. This is not always the case; if a server streams one byte every fifteen seconds, a timeout of 20 seconds will not trigger, even though the request will take several minutes to complete. If your goal is to cut off any request after a set amount of wall clock time, consider having a second "watcher" thread to cut off a slow request. """ #: A sentinel object representing the default timeout value DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT def __init__(self, total=None, connect=_Default, read=_Default): self._connect = self._validate_timeout(connect, 'connect') self._read = self._validate_timeout(read, 'read') self.total = self._validate_timeout(total, 'total') self._start_connect = None def __str__(self): return '%s(connect=%r, read=%r, total=%r)' % ( type(self).__name__, self._connect, self._read, self.total) @classmethod def _validate_timeout(cls, value, name): """ Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If the type is not an integer or a float, or if it is a numeric value less than zero. """ if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value try: float(value) except (TypeError, ValueError): raise ValueError("Timeout value %s was %s, but it must be an " "int or float." % (name, value)) try: if value < 0: raise ValueError("Attempted to set %s timeout to %s, but the " "timeout cannot be set to a value less " "than 0." % (name, value)) except TypeError: # Python 3 raise ValueError("Timeout value %s was %s, but it must be an " "int or float." % (name, value)) return value @classmethod def from_float(cls, timeout): """ Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value. :type timeout: integer, float, sentinel default object, or None :return: Timeout object :rtype: :class:`Timeout` """ return Timeout(read=timeout, connect=timeout) def clone(self): """ Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total) def start_connect(self): """ Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.TimeoutStateError: if you attempt to start a timer that has been started already. """ if self._start_connect is not None: raise TimeoutStateError("Timeout timer has already been started.") self._start_connect = current_time() return self._start_connect def get_connect_duration(self): """ Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. """ if self._start_connect is None: raise TimeoutStateError("Can't get connect duration for timer " "that has not started.") return current_time() - self._start_connect @property def connect_timeout(self): """ Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total) @property def read_timeout(self): """ Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if (self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read
mit
8f99e9edecb44f06b966d3212970c5c7
38.652893
82
0.63516
4.606817
false
false
false
false
botify-labs/simpleflow
simpleflow/process/supervisor.py
1
9275
import functools import multiprocessing import os import signal import time import types import psutil from simpleflow import logger from .named_mixin import NamedMixin, with_state def reset_signal_handlers(func): """ Decorator that resets signal handlers from the decorated function. Useful for workers where we actively want handlers defined on the supervisor to be removed, because they wouldn't work on the worker process. """ @functools.wraps(func) def wrapped(*args, **kwargs): signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGCHLD, signal.SIG_DFL) return func(*args, **kwargs) wrapped.__wrapped__ = func return wrapped def _void_handle_sigchld(signum, frame): """ Default action for a SIGCHLD signal handling is to ignore it which in practice has no effect on the running program. Having a handler that does nothing is a bit different, in the sense it will interrupt the execution of any "time.sleep()" routing. From "time" module docs: The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. """ pass class Supervisor(NamedMixin): """ The `Supervisor` class is responsible for managing one or many worker processes in parallel. Those processes can be "deciders" or "activity workers" in the SWF terminology. It's heavily inspired by the process Supervisor from honcho (which is a clone of the "foreman" process manager, in python): https://github.com/nickstenning/honcho It also has its roots in the former simpleflow process manager and some of Botify private code which wasn't really well tested, and was re-written in a TDD-y style. """ def __init__(self, payload, arguments=None, nb_children=None, background=False): """ Initializes a Manager() instance, with a payload (a callable that will be executed on worker processes), some arguments (a list or tuple of arguments to pass to the callable on workers), and nb_children (the expected number of workers, which defaults to the number of CPU cores if not passed). :param payload: :type payload: callable :param arguments: :type arguments: tuple | list :param nb_children: :type nb_children: int :param background: wether the supervisor process should launch in background :type background: bool """ # NB: below, compare explicitly to "None" there because nb_children could be 0 if nb_children is None: self._nb_children = multiprocessing.cpu_count() else: self._nb_children = nb_children self._payload = payload self._payload_friendly_name = self.payload_friendly_name() self._named_mixin_properties = ["_payload_friendly_name", "_nb_children"] self._args = arguments if arguments is not None else () self._background = background self._processes = {} self._terminating = False super(Supervisor, self).__init__() @with_state("running") def start(self): """ Used to start the Supervisor process once it's configured. Has to be called explicitly on a Supervisor instance so it starts (no auto-start from __init__()). """ logger.info("starting {}".format(self._payload)) if self._background: p = multiprocessing.Process(target=self.target) p.start() else: self.target() def _cleanup_worker_processes(self): # cleanup children to_remove = [] for pid, child in self._processes.items(): try: name, status = child.name(), child.status() except psutil.NoSuchProcess: # May be untimely deceased name, status = "unknown", "unknown" logger.debug( " child: name=%s pid=%d status=%s" % (name, child.pid, status) ) if status in (psutil.STATUS_ZOMBIE, "unknown"): logger.debug(" process {} is zombie, will cleanup".format(child.pid)) # join process to clean it up child.wait() # set the process to be removed from self._processes to_remove.append(pid) # cleanup our internal state (self._processes) for pid in to_remove: del self._processes[pid] def _start_worker_processes(self): """ Start missing worker processes depending on self._nb_children and the current processes stored in self._processes. """ if self._terminating: return for _ in range(len(self._processes), self._nb_children): child = multiprocessing.Process( target=reset_signal_handlers(self._payload), args=self._args ) child.start() # One might wonder if `child.pid` is guaranteed to be set at this # point. I tried it experimentally, and read quickly the source # at https://github.com/python/cpython/blob/2.7/Lib/multiprocessing/process.py # which shows that `pid` ultimately translates to `os.getpid()` after the # fork. So no big risk, but I add an assertion just in case anyway. pid = child.pid assert pid, "Cannot add process with pid={}: {}".format(pid, child) self._processes[pid] = psutil.Process(pid) def target(self): """ Supervisor's main "target", as defined in the `multiprocessing` API. It's the code that the manager will execute once started. """ # handle signals self.bind_signal_handlers() # protection against double use of ".start()" if len(self._processes) != 0: raise Exception( "Child processes map is not empty, already called .start() ?" ) # wait for all processes to finish while True: # if terminating, join all processes and exit the loop so we finish # the supervisor process if self._terminating: for proc in self._processes.values(): logger.info( "process: waiting for proces={} to finish.".format(proc) ) proc.wait() break # start worker processes self._cleanup_worker_processes() self._start_worker_processes() # re-evaluate state at least every 5 seconds ; if a SIGCHLD happens during # the "time.sleep()" below, it will be interrupted, making the code above # run nearly immediately ; but if a SIGCHLD happens during the two calls # above, the "time.sleep()" here won't be stopped, so better have it # relatively short, but not too short since the above methods involve # scanning a bunch of entries in /proc so that could become slow if we do # it every 0.1s. time.sleep(5) def bind_signal_handlers(self): """ Binds signals for graceful shutdown: - SIGTERM and SIGINT lead to a graceful shutdown - SIGCHLD is intentionally left to a void handler, see comment - other signals are not modified for now """ # NB: Function is nested to have a reference to *self*. def _handle_graceful_shutdown(signum, frame): signals_map = {2: "SIGINT", 15: "SIGTERM"} signal_name = signals_map.get(signum, signum) logger.info( "process: caught signal signal={} pid={}".format( signal_name, os.getpid() ) ) self.terminate() # bind SIGTERM and SIGINT signal.signal(signal.SIGTERM, _handle_graceful_shutdown) signal.signal(signal.SIGINT, _handle_graceful_shutdown) # bind SIGCHLD signal.signal(signal.SIGCHLD, _void_handle_sigchld) @with_state("stopping") def terminate(self): """ Terminate all worker processes managed by this Supervisor. """ self._terminating = True logger.info( "process: will stop workers, this might take up several minutes. " "Please, be patient." ) self._killall() def _killall(self): """ Sends a stop (SIGTERM) signal to all worker processes. """ for process in self._processes.values(): logger.info("process: sending SIGTERM to pid={}".format(process.pid)) process.terminate() def payload_friendly_name(self): payload = self._payload if isinstance(payload, types.MethodType): instance = payload.__self__ return "{}.{}".format(instance.__class__.__name__, payload.__name__) elif isinstance(payload, types.FunctionType): return payload.__name__ raise TypeError("invalid payload type {}".format(type(payload)))
mit
d48fd5b884c9e8b6ae7076c72d3c888f
37.168724
90
0.605822
4.502427
false
false
false
false
frappe/frappe
frappe/sessions.py
2
13214
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE """ Boot session from cache or build Session bootstraps info needed by common client side activities including permission, homepage, default variables, system defaults etc """ import json from urllib.parse import unquote import redis import frappe import frappe.defaults import frappe.model.meta import frappe.translate import frappe.utils from frappe import _ from frappe.cache_manager import clear_user_cache from frappe.query_builder import DocType, Order from frappe.query_builder.functions import Now from frappe.query_builder.utils import PseudoColumn from frappe.utils import cint, cstr, get_assets_json @frappe.whitelist() def clear(): frappe.local.session_obj.update(force=True) frappe.local.db.commit() clear_user_cache(frappe.session.user) frappe.response["message"] = _("Cache Cleared") def clear_sessions(user=None, keep_current=False, device=None, force=False): """Clear other sessions of the current user. Called at login / logout :param user: user name (default: current user) :param keep_current: keep current session (default: false) :param device: delete sessions of this device (default: desktop, mobile) :param force: triggered by the user (default false) """ reason = "Logged In From Another Session" if force: reason = "Force Logged out by the user" for sid in get_sessions_to_clear(user, keep_current, device): delete_session(sid, reason=reason) def get_sessions_to_clear(user=None, keep_current=False, device=None): """Returns sessions of the current user. Called at login / logout :param user: user name (default: current user) :param keep_current: keep current session (default: false) :param device: delete sessions of this device (default: desktop, mobile) """ if not user: user = frappe.session.user if not device: device = ("desktop", "mobile") if not isinstance(device, (tuple, list)): device = (device,) offset = 0 if user == frappe.session.user: simultaneous_sessions = frappe.db.get_value("User", user, "simultaneous_sessions") or 1 offset = simultaneous_sessions - 1 session = DocType("Sessions") session_id = frappe.qb.from_(session).where( (session.user == user) & (session.device.isin(device)) ) if keep_current: session_id = session_id.where(session.sid != frappe.session.sid) query = ( session_id.select(session.sid) .offset(offset) .limit(100) .orderby(session.lastupdate, order=Order.desc) ) return query.run(pluck=True) def delete_session(sid=None, user=None, reason="Session Expired"): from frappe.core.doctype.activity_log.feed import logout_feed if frappe.flags.read_only: # This isn't manually initated logout, most likely user's cookies were expired in such case # we should just ignore it till database is back up again. return frappe.cache().hdel("session", sid) frappe.cache().hdel("last_db_session_update", sid) if sid and not user: table = DocType("Sessions") user_details = ( frappe.qb.from_(table).where(table.sid == sid).select(table.user).run(as_dict=True) ) if user_details: user = user_details[0].get("user") logout_feed(user, reason) frappe.db.delete("Sessions", {"sid": sid}) frappe.db.commit() def clear_all_sessions(reason=None): """This effectively logs out all users""" frappe.only_for("Administrator") if not reason: reason = "Deleted All Active Session" for sid in frappe.qb.from_("Sessions").select("sid").run(pluck=True): delete_session(sid, reason=reason) def get_expired_sessions(): """Returns list of expired sessions""" sessions = DocType("Sessions") expired = [] for device in ("desktop", "mobile"): expired.extend( frappe.db.get_values( sessions, filters=( PseudoColumn(f"({Now()} - {sessions.lastupdate.get_sql()})") > get_expiry_period_for_query(device) ) & (sessions.device == device), fieldname="sid", order_by=None, pluck=True, ) ) return expired def clear_expired_sessions(): """This function is meant to be called from scheduler""" for sid in get_expired_sessions(): delete_session(sid, reason="Session Expired") def get(): """get session boot info""" from frappe.boot import get_bootinfo, get_unseen_notes from frappe.utils.change_log import get_change_log bootinfo = None if not getattr(frappe.conf, "disable_session_cache", None): # check if cache exists bootinfo = frappe.cache().hget("bootinfo", frappe.session.user) if bootinfo: bootinfo["from_cache"] = 1 bootinfo["user"]["recent"] = json.dumps(frappe.cache().hget("user_recent", frappe.session.user)) if not bootinfo: # if not create it bootinfo = get_bootinfo() frappe.cache().hset("bootinfo", frappe.session.user, bootinfo) try: frappe.cache().ping() except redis.exceptions.ConnectionError: message = _("Redis cache server not running. Please contact Administrator / Tech support") if "messages" in bootinfo: bootinfo["messages"].append(message) else: bootinfo["messages"] = [message] # check only when clear cache is done, and don't cache this if frappe.local.request: bootinfo["change_log"] = get_change_log() bootinfo["metadata_version"] = frappe.cache().get_value("metadata_version") if not bootinfo["metadata_version"]: bootinfo["metadata_version"] = frappe.reset_metadata_version() bootinfo.notes = get_unseen_notes() bootinfo.assets_json = get_assets_json() bootinfo.read_only = bool(frappe.flags.read_only) for hook in frappe.get_hooks("extend_bootinfo"): frappe.get_attr(hook)(bootinfo=bootinfo) bootinfo["lang"] = frappe.translate.get_user_lang() bootinfo["disable_async"] = frappe.conf.disable_async bootinfo["setup_complete"] = cint(frappe.get_system_settings("setup_complete")) bootinfo["desk_theme"] = frappe.db.get_value("User", frappe.session.user, "desk_theme") or "Light" return bootinfo @frappe.whitelist() def get_boot_assets_json(): return get_assets_json() def get_csrf_token(): if not frappe.local.session.data.csrf_token: generate_csrf_token() return frappe.local.session.data.csrf_token def generate_csrf_token(): frappe.local.session.data.csrf_token = frappe.generate_hash() if not frappe.flags.in_test: frappe.local.session_obj.update(force=True) class Session: __slots__ = ("user", "device", "user_type", "full_name", "data", "time_diff", "sid") def __init__(self, user, resume=False, full_name=None, user_type=None): self.sid = cstr( frappe.form_dict.get("sid") or unquote(frappe.request.cookies.get("sid", "Guest")) ) self.user = user self.device = frappe.form_dict.get("device") or "desktop" self.user_type = user_type self.full_name = full_name self.data = frappe._dict({"data": frappe._dict({})}) self.time_diff = None # set local session frappe.local.session = self.data if resume: self.resume() else: if self.user: self.start() def start(self): """start a new session""" # generate sid if self.user == "Guest": sid = "Guest" else: sid = frappe.generate_hash() self.data.user = self.user self.data.sid = sid self.data.data.user = self.user self.data.data.session_ip = frappe.local.request_ip if self.user != "Guest": self.data.data.update( { "last_updated": frappe.utils.now(), "session_expiry": get_expiry_period(self.device), "full_name": self.full_name, "user_type": self.user_type, "device": self.device, "session_country": get_geo_ip_country(frappe.local.request_ip) if frappe.local.request_ip else None, } ) # insert session if self.user != "Guest": self.insert_session_record() # update user user = frappe.get_doc("User", self.data["user"]) user_doctype = frappe.qb.DocType("User") ( frappe.qb.update(user_doctype) .set(user_doctype.last_login, frappe.utils.now()) .set(user_doctype.last_ip, frappe.local.request_ip) .set(user_doctype.last_active, frappe.utils.now()) .where(user_doctype.name == self.data["user"]) ).run() user.run_notifications("before_change") user.run_notifications("on_update") frappe.db.commit() def insert_session_record(self): frappe.db.sql( """insert into `tabSessions` (`sessiondata`, `user`, `lastupdate`, `sid`, `status`, `device`) values (%s , %s, NOW(), %s, 'Active', %s)""", (str(self.data["data"]), self.data["user"], self.data["sid"], self.device), ) # also add to memcache frappe.cache().hset("session", self.data.sid, self.data) def resume(self): """non-login request: load a session""" import frappe from frappe.auth import validate_ip_address data = self.get_session_record() if data: self.data.update({"data": data, "user": data.user, "sid": self.sid}) self.user = data.user validate_ip_address(self.user) self.device = data.device else: self.start_as_guest() if self.sid != "Guest": frappe.local.user_lang = frappe.translate.get_user_lang(self.data.user) frappe.local.lang = frappe.local.user_lang def get_session_record(self): """get session record, or return the standard Guest Record""" from frappe.auth import clear_cookies r = self.get_session_data() if not r: frappe.response["session_expired"] = 1 clear_cookies() self.sid = "Guest" r = self.get_session_data() return r def get_session_data(self): if self.sid == "Guest": return frappe._dict({"user": "Guest"}) data = self.get_session_data_from_cache() if not data: data = self.get_session_data_from_db() return data def get_session_data_from_cache(self): data = frappe.cache().hget("session", self.sid) if data: data = frappe._dict(data) session_data = data.get("data", {}) # set user for correct timezone self.time_diff = frappe.utils.time_diff_in_seconds( frappe.utils.now(), session_data.get("last_updated") ) expiry = get_expiry_in_seconds(session_data.get("session_expiry")) if self.time_diff > expiry: self._delete_session() data = None return data and data.data def get_session_data_from_db(self): sessions = DocType("Sessions") self.device = ( frappe.db.get_value( sessions, filters=sessions.sid == self.sid, fieldname="device", order_by=None, ) or "desktop" ) rec = frappe.db.get_values( sessions, filters=(sessions.sid == self.sid) & ( PseudoColumn(f"({Now()} - {sessions.lastupdate.get_sql()})") < get_expiry_period_for_query(self.device) ), fieldname=["user", "sessiondata"], order_by=None, ) if rec: data = frappe._dict(frappe.safe_eval(rec and rec[0][1] or "{}")) data.user = rec[0][0] else: self._delete_session() data = None return data def _delete_session(self): delete_session(self.sid, reason="Session Expired") def start_as_guest(self): """all guests share the same 'Guest' session""" self.user = "Guest" self.start() def update(self, force=False): """extend session expiry""" if frappe.session["user"] == "Guest" or frappe.form_dict.cmd == "logout": return now = frappe.utils.now() self.data["data"]["last_updated"] = now self.data["data"]["lang"] = str(frappe.lang) # update session in db last_updated = frappe.cache().hget("last_db_session_update", self.sid) time_diff = frappe.utils.time_diff_in_seconds(now, last_updated) if last_updated else None # database persistence is secondary, don't update it too often updated_in_db = False if (force or (time_diff is None) or (time_diff > 600)) and not frappe.flags.read_only: # update sessions table frappe.db.sql( """update `tabSessions` set sessiondata=%s, lastupdate=NOW() where sid=%s""", (str(self.data["data"]), self.data["sid"]), ) # update last active in user table frappe.db.sql( """update `tabUser` set last_active=%(now)s where name=%(name)s""", {"now": now, "name": frappe.session.user}, ) frappe.db.commit() frappe.cache().hset("last_db_session_update", self.sid, now) updated_in_db = True frappe.cache().hset("session", self.sid, self.data) return updated_in_db def get_expiry_period_for_query(device=None): if frappe.db.db_type == "postgres": return get_expiry_period(device) else: return get_expiry_in_seconds(device=device) def get_expiry_in_seconds(expiry=None, device=None): if not expiry: expiry = get_expiry_period(device) parts = expiry.split(":") return (cint(parts[0]) * 3600) + (cint(parts[1]) * 60) + cint(parts[2]) def get_expiry_period(device="desktop"): if device == "mobile": key = "session_expiry_mobile" default = "720:00:00" else: key = "session_expiry" default = "06:00:00" exp_sec = frappe.defaults.get_global_default(key) or default # incase seconds is missing if len(exp_sec.split(":")) == 2: exp_sec = exp_sec + ":00" return exp_sec def get_geo_from_ip(ip_addr): try: from geolite2 import geolite2 with geolite2 as f: reader = f.reader() data = reader.get(ip_addr) return frappe._dict(data) except ImportError: return except ValueError: return except TypeError: return def get_geo_ip_country(ip_addr): match = get_geo_from_ip(ip_addr) if match: return match.country
mit
2e356f2870ede5908bd2d0801429ba1a
25.912424
99
0.684804
3.056674
false
false
false
false
frappe/frappe
frappe/utils/password.py
3
6765
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import string from cryptography.fernet import Fernet, InvalidToken from passlib.context import CryptContext from passlib.hash import mysql41, pbkdf2_sha256 from passlib.registry import register_crypt_handler from pypika.terms import Values import frappe from frappe import _ from frappe.query_builder import Table from frappe.utils import cstr, encode Auth = Table("__Auth") class LegacyPassword(pbkdf2_sha256): name = "frappe_legacy" ident = "$frappel$" def _calc_checksum(self, secret): # check if this is a mysql hash # it is possible that we will generate a false positive if the users password happens to be 40 hex chars proceeded # by an * char, but this seems highly unlikely if not ( secret[0] == "*" and len(secret) == 41 and all(c in string.hexdigits for c in secret[1:]) ): secret = mysql41.hash(secret + self.salt.decode("utf-8")) return super()._calc_checksum(secret) register_crypt_handler(LegacyPassword, force=True) passlibctx = CryptContext( schemes=[ "pbkdf2_sha256", "argon2", "frappe_legacy", ], deprecated=[ "frappe_legacy", ], ) def get_decrypted_password(doctype, name, fieldname="password", raise_exception=True): result = ( frappe.qb.from_(Auth) .select(Auth.password) .where( (Auth.doctype == doctype) & (Auth.name == name) & (Auth.fieldname == fieldname) & (Auth.encrypted == 1) ) .limit(1) ).run() if result and result[0][0]: return decrypt(result[0][0]) elif raise_exception: frappe.throw(_("Password not found"), frappe.AuthenticationError) def set_encrypted_password(doctype, name, pwd, fieldname="password"): query = ( frappe.qb.into(Auth) .columns(Auth.doctype, Auth.name, Auth.fieldname, Auth.password, Auth.encrypted) .insert(doctype, name, fieldname, encrypt(pwd), 1) ) # TODO: Simplify this via aliasing methods in `frappe.qb` if frappe.db.db_type == "mariadb": query = query.on_duplicate_key_update(Auth.password, Values(Auth.password)) elif frappe.db.db_type == "postgres": query = query.on_conflict(Auth.doctype, Auth.name, Auth.fieldname).do_update(Auth.password) try: query.run() except frappe.db.DataError as e: if frappe.db.is_data_too_long(e): frappe.throw(_("Most probably your password is too long."), exc=e) raise e def remove_encrypted_password(doctype, name, fieldname="password"): frappe.db.delete("__Auth", {"doctype": doctype, "name": name, "fieldname": fieldname}) def check_password(user, pwd, doctype="User", fieldname="password", delete_tracker_cache=True): """Checks if user and password are correct, else raises frappe.AuthenticationError""" result = ( frappe.qb.from_(Auth) .select(Auth.name, Auth.password) .where( (Auth.doctype == doctype) & (Auth.name == user) & (Auth.fieldname == fieldname) & (Auth.encrypted == 0) ) .limit(1) .run(as_dict=True) ) if not result or not passlibctx.verify(pwd, result[0].password): raise frappe.AuthenticationError(_("Incorrect User or Password")) # lettercase agnostic user = result[0].name # TODO: This need to be deleted after checking side effects of it. # We have a `LoginAttemptTracker` that can take care of tracking related cache. if delete_tracker_cache: delete_login_failed_cache(user) if not passlibctx.needs_update(result[0].password): update_password(user, pwd, doctype, fieldname) return user def delete_login_failed_cache(user): frappe.cache().hdel("last_login_tried", user) frappe.cache().hdel("login_failed_count", user) frappe.cache().hdel("locked_account_time", user) def update_password(user, pwd, doctype="User", fieldname="password", logout_all_sessions=False): """ Update the password for the User :param user: username :param pwd: new password :param doctype: doctype name (for encryption) :param fieldname: fieldname (in given doctype) (for encryption) :param logout_all_session: delete all other session """ hashPwd = passlibctx.hash(pwd) query = ( frappe.qb.into(Auth) .columns(Auth.doctype, Auth.name, Auth.fieldname, Auth.password, Auth.encrypted) .insert(doctype, user, fieldname, hashPwd, 0) ) # TODO: Simplify this via aliasing methods in `frappe.qb` if frappe.db.db_type == "mariadb": query = query.on_duplicate_key_update(Auth.password, hashPwd).on_duplicate_key_update( Auth.encrypted, 0 ) elif frappe.db.db_type == "postgres": query = ( query.on_conflict(Auth.doctype, Auth.name, Auth.fieldname) .do_update(Auth.password, hashPwd) .do_update(Auth.encrypted, 0) ) query.run() # clear all the sessions except current if logout_all_sessions: from frappe.sessions import clear_sessions clear_sessions(user=user, keep_current=True, force=True) def delete_all_passwords_for(doctype, name): try: frappe.db.delete("__Auth", {"doctype": doctype, "name": name}) except Exception as e: if not frappe.db.is_missing_column(e): raise def rename_password(doctype, old_name, new_name): # NOTE: fieldname is not considered, since the document is renamed frappe.qb.update(Auth).set(Auth.name, new_name).where( (Auth.doctype == doctype) & (Auth.name == old_name) ).run() def rename_password_field(doctype, old_fieldname, new_fieldname): frappe.qb.update(Auth).set(Auth.fieldname, new_fieldname).where( (Auth.doctype == doctype) & (Auth.fieldname == old_fieldname) ).run() def create_auth_table(): # same as Framework.sql frappe.db.create_auth_table() def encrypt(txt, encryption_key=None): # Only use Fernet.generate_key().decode() to enter encyption_key value try: cipher_suite = Fernet(encode(encryption_key or get_encryption_key())) except Exception: # encryption_key is not in 32 url-safe base64-encoded format frappe.throw(_("Encryption key is in invalid format!")) cipher_text = cstr(cipher_suite.encrypt(encode(txt))) return cipher_text def decrypt(txt, encryption_key=None): # Only use encryption_key value generated with Fernet.generate_key().decode() try: cipher_suite = Fernet(encode(encryption_key or get_encryption_key())) return cstr(cipher_suite.decrypt(encode(txt))) except InvalidToken: # encryption_key in site_config is changed and not valid frappe.throw(_("Encryption key is invalid! Please check site_config.json")) def get_encryption_key(): if "encryption_key" not in frappe.local.conf: from frappe.installer import update_site_config encryption_key = Fernet.generate_key().decode() update_site_config("encryption_key", encryption_key) frappe.local.conf.encryption_key = encryption_key return frappe.local.conf.encryption_key def get_password_reset_limit(): return frappe.db.get_single_value("System Settings", "password_reset_limit") or 0
mit
8c9d05af3451b7b936e9677316cdb57c
27.910256
116
0.720325
3.192544
false
false
false
false
frappe/frappe
frappe/utils/caching.py
3
4184
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. Check LICENSE import json from collections import defaultdict from datetime import datetime, timedelta from functools import wraps from typing import Callable import frappe _SITE_CACHE = defaultdict(lambda: defaultdict(dict)) def __generate_request_cache_key(args: tuple, kwargs: dict): """Generate a key for the cache.""" if not kwargs: return hash(args) return hash((args, frozenset(kwargs.items()))) def request_cache(func: Callable) -> Callable: """Decorator to cache function calls mid-request. Cache is stored in frappe.local.request_cache. The cache only persists for the current request and is cleared when the request is over. The function is called just once per request with the same set of (kw)arguments. Usage: from frappe.utils.caching import request_cache @request_cache def calculate_pi(num_terms=0): import math, time print(f"{num_terms = }") time.sleep(10) return math.pi calculate_pi(10) # will calculate value calculate_pi(10) # will return value from cache """ @wraps(func) def wrapper(*args, **kwargs): if not getattr(frappe.local, "initialised", None): return func(*args, **kwargs) if not hasattr(frappe.local, "request_cache"): frappe.local.request_cache = defaultdict(dict) try: args_key = __generate_request_cache_key(args, kwargs) except Exception: return func(*args, **kwargs) try: return frappe.local.request_cache[func][args_key] except KeyError: return_val = func(*args, **kwargs) frappe.local.request_cache[func][args_key] = return_val return return_val return wrapper def site_cache(ttl: int | None = None, maxsize: int | None = None) -> Callable: """Decorator to cache method calls across requests. The cache is stored in frappe.utils.caching._SITE_CACHE. The cache persists on the parent process. It offers a light-weight cache for the current process without the additional overhead of serializing / deserializing Python objects. Note: This cache isn't shared among workers. If you need to share data across workers, use redis (frappe.cache API) instead. Usage: from frappe.utils.caching import site_cache @site_cache def calculate_pi(): import math, time precision = get_precision("Math Constant", "Pi") # depends on site data return round(math.pi, precision) calculate_pi(10) # will calculate value calculate_pi(10) # will return value from cache calculate_pi.clear_cache() # clear this function's cache for all sites calculate_pi(10) # will calculate value """ def time_cache_wrapper(func: Callable = None) -> Callable: func_key = f"{func.__module__}.{func.__name__}" def clear_cache(): """Clear cache for this function for all sites if not specified.""" _SITE_CACHE[func_key].clear() func.clear_cache = clear_cache if ttl is not None and not callable(ttl): func.ttl = ttl func.expiration = datetime.utcnow() + timedelta(seconds=func.ttl) if maxsize is not None and not callable(maxsize): func.maxsize = maxsize @wraps(func) def site_cache_wrapper(*args, **kwargs): if getattr(frappe.local, "initialised", None): func_call_key = json.dumps((args, kwargs)) if hasattr(func, "ttl") and datetime.utcnow() >= func.expiration: func.clear_cache() func.expiration = datetime.utcnow() + timedelta(seconds=func.ttl) if hasattr(func, "maxsize") and len(_SITE_CACHE[func_key][frappe.local.site]) >= func.maxsize: _SITE_CACHE[func_key][frappe.local.site].pop( next(iter(_SITE_CACHE[func_key][frappe.local.site])), None ) if func_call_key not in _SITE_CACHE[func_key][frappe.local.site]: _SITE_CACHE[func_key][frappe.local.site][func_call_key] = func(*args, **kwargs) return _SITE_CACHE[func_key][frappe.local.site][func_call_key] return func(*args, **kwargs) return site_cache_wrapper if callable(ttl): return time_cache_wrapper(ttl) return time_cache_wrapper
mit
c2502a3ebc75fd5efef1ba6f78eddf33
31.184615
98
0.680927
3.563884
false
false
false
false
frappe/frappe
frappe/core/doctype/file/file.py
1
21692
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import io import mimetypes import os import re import shutil import zipfile from urllib.parse import quote, unquote from PIL import Image, ImageFile, ImageOps from requests.exceptions import HTTPError, SSLError import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import call_hook_method, cint, get_files_path, get_hook_method, get_url from frappe.utils.file_manager import is_safe_path from frappe.utils.image import optimize_image, strip_exif_data from .exceptions import AttachmentLimitReached, FolderNotEmpty, MaxFileSizeReachedError from .utils import * exclude_from_linked_with = True ImageFile.LOAD_TRUNCATED_IMAGES = True URL_PREFIXES = ("http://", "https://") class File(Document): no_feed_on_delete = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # if content is set, file_url will be generated # decode comes in the picture if content passed has to be decoded before writing to disk self.content = self.get("content") or b"" self.decode = self.get("decode", False) @property def is_remote_file(self): if self.file_url: return self.file_url.startswith(URL_PREFIXES) return not self.content def autoname(self): """Set name for folder""" if self.is_folder: if self.folder: self.name = self.get_name_based_on_parent_folder() else: # home self.name = self.file_name else: self.name = frappe.generate_hash(length=10) def before_insert(self): self.set_folder_name() self.set_file_name() self.validate_attachment_limit() if self.is_folder: return if self.is_remote_file: self.validate_remote_file() else: self.save_file(content=self.get_content()) self.flags.new_file = True frappe.local.rollback_observers.append(self) def after_insert(self): if not self.is_folder: self.create_attachment_record() self.set_is_private() self.set_file_name() self.validate_duplicate_entry() def validate(self): if self.is_folder: return # Ensure correct formatting and type self.file_url = unquote(self.file_url) if self.file_url else "" self.validate_attachment_references() # when dict is passed to get_doc for creation of new_doc, is_new returns None # this case is handled inside handle_is_private_changed if not self.is_new() and self.has_value_changed("is_private"): self.handle_is_private_changed() self.validate_file_path() self.validate_file_url() self.validate_file_on_disk() self.file_size = frappe.form_dict.file_size or self.file_size def validate_attachment_references(self): if not self.attached_to_doctype: return if not self.attached_to_name or not isinstance(self.attached_to_name, (str, int)): frappe.throw(_("Attached To Name must be a string or an integer"), frappe.ValidationError) if not self.attached_to_field: return if not frappe.get_meta(self.attached_to_doctype).has_field(self.attached_to_field): frappe.throw(_("The fieldname you've specified in Attached To Field is invalid")) def after_rename(self, *args, **kwargs): for successor in self.get_successors(): setup_folder_path(successor, self.name) def on_trash(self): if self.is_home_folder or self.is_attachments_folder: frappe.throw(_("Cannot delete Home and Attachments folders")) self.validate_empty_folder() self._delete_file_on_disk() if not self.is_folder: self.add_comment_in_reference_doc("Attachment Removed", _("Removed {0}").format(self.file_name)) def on_rollback(self): # following condition is only executed when an insert has been rolledback if self.flags.new_file: self._delete_file_on_disk() self.flags.pop("new_file") return # if original_content flag is set, this rollback should revert the file to its original state if self.flags.original_content: file_path = self.get_full_path() if isinstance(self.flags.original_content, bytes): mode = "wb+" elif isinstance(self.flags.original_content, str): mode = "w+" with open(file_path, mode) as f: f.write(self.flags.original_content) os.fsync(f.fileno()) self.flags.pop("original_content") # used in case file path (File.file_url) has been changed if self.flags.original_path: target = self.flags.original_path["old"] source = self.flags.original_path["new"] shutil.move(source, target) self.flags.pop("original_path") def get_name_based_on_parent_folder(self) -> str | None: if self.folder: return os.path.join(self.folder, self.file_name) def get_successors(self): return frappe.get_all("File", filters={"folder": self.name}, pluck="name") def validate_file_path(self): if self.is_remote_file: return base_path = os.path.realpath(get_files_path(is_private=self.is_private)) if not os.path.realpath(self.get_full_path()).startswith(base_path): frappe.throw( _("The File URL you've entered is incorrect"), title=_("Invalid File URL"), ) def validate_file_url(self): if self.is_remote_file or not self.file_url: return if not self.file_url.startswith(("/files/", "/private/files/")): # Probably an invalid URL since it doesn't start with http either frappe.throw( _("URL must start with http:// or https://"), title=_("Invalid URL"), ) def handle_is_private_changed(self): if self.is_remote_file: return from pathlib import Path old_file_url = self.file_url file_name = self.file_url.split("/")[-1] private_file_path = Path(frappe.get_site_path("private", "files", file_name)) public_file_path = Path(frappe.get_site_path("public", "files", file_name)) if cint(self.is_private): source = public_file_path target = private_file_path url_starts_with = "/private/files/" else: source = private_file_path target = public_file_path url_starts_with = "/files/" updated_file_url = f"{url_starts_with}{file_name}" # if a file document is created by passing dict throught get_doc and __local is not set, # handle_is_private_changed would be executed; we're checking if updated_file_url is same # as old_file_url to avoid a FileNotFoundError for this case. if updated_file_url == old_file_url: return if not source.exists(): frappe.throw( _("Cannot find file {} on disk").format(source), exc=FileNotFoundError, ) if target.exists(): frappe.throw( _("A file with same name {} already exists").format(target), exc=FileExistsError, ) # Uses os.rename which is an atomic operation shutil.move(source, target) self.flags.original_path = {"old": source, "new": target} frappe.local.rollback_observers.append(self) self.file_url = updated_file_url update_existing_file_docs(self) if ( not self.attached_to_doctype or not self.attached_to_name or not self.fetch_attached_to_field(old_file_url) ): return frappe.db.set_value( self.attached_to_doctype, self.attached_to_name, self.attached_to_field, self.file_url, ) def fetch_attached_to_field(self, old_file_url): if self.attached_to_field: return True reference_dict = frappe.get_doc(self.attached_to_doctype, self.attached_to_name).as_dict() for key, value in reference_dict.items(): if value == old_file_url: self.attached_to_field = key return True def validate_attachment_limit(self): attachment_limit = 0 if self.attached_to_doctype and self.attached_to_name: attachment_limit = cint(frappe.get_meta(self.attached_to_doctype).max_attachments) if attachment_limit: current_attachment_count = len( frappe.get_all( "File", filters={ "attached_to_doctype": self.attached_to_doctype, "attached_to_name": self.attached_to_name, }, limit=attachment_limit + 1, ) ) if current_attachment_count >= attachment_limit: frappe.throw( _("Maximum Attachment Limit of {0} has been reached for {1} {2}.").format( frappe.bold(attachment_limit), self.attached_to_doctype, self.attached_to_name ), exc=AttachmentLimitReached, title=_("Attachment Limit Reached"), ) def validate_remote_file(self): """Validates if file uploaded using URL already exist""" site_url = get_url() if self.file_url and "/files/" in self.file_url and self.file_url.startswith(site_url): self.file_url = self.file_url.split(site_url, 1)[1] def set_folder_name(self): """Make parent folders if not exists based on reference doctype and name""" if self.folder: return if self.attached_to_doctype: self.folder = frappe.db.get_value("File", {"is_attachments_folder": 1}) elif not self.is_home_folder: self.folder = "Home" def validate_file_on_disk(self): """Validates existence file""" full_path = self.get_full_path() if full_path.startswith(URL_PREFIXES): return True if not os.path.exists(full_path): frappe.throw(_("File {0} does not exist").format(self.file_url), IOError) def validate_duplicate_entry(self): if not self.flags.ignore_duplicate_entry_error and not self.is_folder: if not self.content_hash: self.generate_content_hash() # check duplicate name # check duplicate assignment filters = { "content_hash": self.content_hash, "is_private": self.is_private, "name": ("!=", self.name), } if self.attached_to_doctype and self.attached_to_name: filters.update( { "attached_to_doctype": self.attached_to_doctype, "attached_to_name": self.attached_to_name, } ) duplicate_file = frappe.db.get_value("File", filters, ["name", "file_url"], as_dict=1) if duplicate_file: duplicate_file_doc = frappe.get_cached_doc("File", duplicate_file.name) if duplicate_file_doc.exists_on_disk(): # just use the url, to avoid uploading a duplicate self.file_url = duplicate_file.file_url def set_file_name(self): if not self.file_name and self.file_url: self.file_name = self.file_url.split("/")[-1] else: self.file_name = re.sub(r"/", "", self.file_name) def generate_content_hash(self): if self.content_hash or not self.file_url or self.is_remote_file: return file_name = self.file_url.split("/")[-1] try: file_path = get_files_path(file_name, is_private=self.is_private) with open(file_path, "rb") as f: self.content_hash = get_content_hash(f.read()) except OSError: frappe.throw(_("File {0} does not exist").format(file_path)) def make_thumbnail( self, set_as_thumbnail: bool = True, width: int = 300, height: int = 300, suffix: str = "small", crop: bool = False, ) -> str: if not self.file_url: return try: if self.file_url.startswith(("/files", "/private/files")): image, filename, extn = get_local_image(self.file_url) else: image, filename, extn = get_web_image(self.file_url) except (HTTPError, SSLError, OSError, TypeError): return size = width, height if crop: image = ImageOps.fit(image, size, Image.Resampling.LANCZOS) else: image.thumbnail(size, Image.Resampling.LANCZOS) thumbnail_url = f"{filename}_{suffix}.{extn}" path = os.path.abspath(frappe.get_site_path("public", thumbnail_url.lstrip("/"))) try: image.save(path) if set_as_thumbnail: self.db_set("thumbnail_url", thumbnail_url) except OSError: frappe.msgprint(_("Unable to write file format for {0}").format(path)) return return thumbnail_url def validate_empty_folder(self): """Throw exception if folder is not empty""" if self.is_folder and frappe.get_all("File", filters={"folder": self.name}, limit=1): frappe.throw(_("Folder {0} is not empty").format(self.name), FolderNotEmpty) def _delete_file_on_disk(self): """If file not attached to any other record, delete it""" on_disk_file_not_shared = self.content_hash and not frappe.get_all( "File", filters={"content_hash": self.content_hash, "name": ["!=", self.name]}, limit=1, ) if on_disk_file_not_shared: self.delete_file_data_content() else: self.delete_file_data_content(only_thumbnail=True) def unzip(self) -> list["File"]: """Unzip current file and replace it by its children""" if not self.file_url.endswith(".zip"): frappe.throw(_("{0} is not a zip file").format(self.file_name)) zip_path = self.get_full_path() files = [] with zipfile.ZipFile(zip_path) as z: for file in z.filelist: if file.is_dir() or file.filename.startswith("__MACOSX/"): # skip directories and macos hidden directory continue filename = os.path.basename(file.filename) if filename.startswith("."): # skip hidden files continue file_doc = frappe.new_doc("File") file_doc.content = z.read(file.filename) file_doc.file_name = filename file_doc.folder = self.folder file_doc.is_private = self.is_private file_doc.attached_to_doctype = self.attached_to_doctype file_doc.attached_to_name = self.attached_to_name file_doc.save() files.append(file_doc) frappe.delete_doc("File", self.name) return files def exists_on_disk(self): return os.path.exists(self.get_full_path()) def get_content(self) -> bytes: if self.is_folder: frappe.throw(_("Cannot get file contents of a Folder")) if self.get("content"): self._content = self.content if self.decode: self._content = decode_file_content(self._content) self.decode = False # self.content = None # TODO: This needs to happen; make it happen somehow return self._content if self.file_url: self.validate_file_url() file_path = self.get_full_path() # read the file with open(file_path, mode="rb") as f: self._content = f.read() try: # for plain text files self._content = self._content.decode() except UnicodeDecodeError: # for .png, .jpg, etc pass return self._content def get_full_path(self): """Returns file path from given file name""" file_path = self.file_url or self.file_name site_url = get_url() if "/files/" in file_path and file_path.startswith(site_url): file_path = file_path.split(site_url, 1)[1] if "/" not in file_path: if self.is_private: file_path = f"/private/files/{file_path}" else: file_path = f"/files/{file_path}" if file_path.startswith("/private/files/"): file_path = get_files_path(*file_path.split("/private/files/", 1)[1].split("/"), is_private=1) elif file_path.startswith("/files/"): file_path = get_files_path(*file_path.split("/files/", 1)[1].split("/")) elif file_path.startswith(URL_PREFIXES): pass elif not self.file_url: frappe.throw(_("There is some problem with the file url: {0}").format(file_path)) if not is_safe_path(file_path): frappe.throw(_("Cannot access file path {0}").format(file_path)) if os.path.sep in self.file_name: frappe.throw(_("File name cannot have {0}").format(os.path.sep)) return file_path def write_file(self): """write file to disk with a random name (to compare)""" if self.is_remote_file: return file_path = self.get_full_path() if isinstance(self._content, str): self._content = self._content.encode() with open(file_path, "wb+") as f: f.write(self._content) os.fsync(f.fileno()) frappe.local.rollback_observers.append(self) return file_path def save_file( self, content: bytes | str | None = None, decode=False, ignore_existing_file_check=False, overwrite=False, ): if self.is_remote_file: return if not self.flags.new_file: self.flags.original_content = self.get_content() if content: self.content = content self.decode = decode self.get_content() if not self._content: return file_exists = False duplicate_file = None self.is_private = cint(self.is_private) self.content_type = mimetypes.guess_type(self.file_name)[0] # transform file content based on site settings if ( self.content_type and self.content_type == "image/jpeg" and frappe.get_system_settings("strip_exif_metadata_from_uploaded_images") ): self._content = strip_exif_data(self._content, self.content_type) self.file_size = self.check_max_file_size() self.content_hash = get_content_hash(self._content) # check if a file exists with the same content hash and is also in the same folder (public or private) if not ignore_existing_file_check: duplicate_file = frappe.get_value( "File", {"content_hash": self.content_hash, "is_private": self.is_private}, ["file_url", "name"], as_dict=True, ) if duplicate_file: file_doc: "File" = frappe.get_cached_doc("File", duplicate_file.name) if file_doc.exists_on_disk(): self.file_url = duplicate_file.file_url file_exists = True if not file_exists: if not overwrite: self.file_name = generate_file_name( name=self.file_name, suffix=self.content_hash[-6:], is_private=self.is_private, ) call_hook_method("before_write_file", file_size=self.file_size) write_file_method = get_hook_method("write_file") if write_file_method: return write_file_method(self) return self.save_file_on_filesystem() def save_file_on_filesystem(self): if self.is_private: self.file_url = f"/private/files/{self.file_name}" else: self.file_url = f"/files/{self.file_name}" fpath = self.write_file() return {"file_name": os.path.basename(fpath), "file_url": self.file_url} def check_max_file_size(self): from frappe.core.api.file import get_max_file_size max_file_size = get_max_file_size() file_size = len(self._content or b"") if file_size > max_file_size: frappe.throw( _("File size exceeded the maximum allowed size of {0} MB").format(max_file_size / 1048576), exc=MaxFileSizeReachedError, ) return file_size def delete_file_data_content(self, only_thumbnail=False): method = get_hook_method("delete_file_data_content") if method: method(self, only_thumbnail=only_thumbnail) else: self.delete_file_from_filesystem(only_thumbnail=only_thumbnail) def delete_file_from_filesystem(self, only_thumbnail=False): """Delete file, thumbnail from File document""" if only_thumbnail: delete_file(self.thumbnail_url) else: delete_file(self.file_url) delete_file(self.thumbnail_url) def is_downloadable(self): return has_permission(self, "read") def get_extension(self): """returns split filename and extension""" return os.path.splitext(self.file_name) def create_attachment_record(self): icon = ' <i class="fa fa-lock text-warning"></i>' if self.is_private else "" file_url = quote(frappe.safe_encode(self.file_url)) if self.file_url else self.file_name file_name = self.file_name or self.file_url self.add_comment_in_reference_doc( "Attachment", _("Added {0}").format(f"<a href='{file_url}' target='_blank'>{file_name}</a>{icon}"), ) def add_comment_in_reference_doc(self, comment_type, text): if self.attached_to_doctype and self.attached_to_name: try: doc = frappe.get_doc(self.attached_to_doctype, self.attached_to_name) doc.add_comment(comment_type, text) except frappe.DoesNotExistError: frappe.clear_messages() def set_is_private(self): if self.file_url: self.is_private = cint(self.file_url.startswith("/private")) @frappe.whitelist() def optimize_file(self): if self.is_folder: raise TypeError("Folders cannot be optimized") content_type = mimetypes.guess_type(self.file_name)[0] is_local_image = content_type.startswith("image/") and self.file_size > 0 is_svg = content_type == "image/svg+xml" if not is_local_image: raise NotImplementedError("Only local image files can be optimized") if is_svg: raise TypeError("Optimization of SVG images is not supported") original_content = self.get_content() optimized_content = optimize_image( content=original_content, content_type=content_type, ) self.save_file(content=optimized_content, overwrite=True) self.save() @staticmethod def zip_files(files): zip_file = io.BytesIO() zf = zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED) for _file in files: if isinstance(_file, str): _file = frappe.get_doc("File", _file) if not isinstance(_file, File): continue if _file.is_folder: continue zf.writestr(_file.file_name, _file.get_content()) zf.close() return zip_file.getvalue() def on_doctype_update(): frappe.db.add_index("File", ["attached_to_doctype", "attached_to_name"]) def has_permission(doc, ptype=None, user=None): has_access = False user = user or frappe.session.user if ptype == "create": has_access = frappe.has_permission("File", "create", user=user) if not doc.is_private or doc.owner in [user, "Guest"] or user == "Administrator": has_access = True if doc.attached_to_doctype and doc.attached_to_name: attached_to_doctype = doc.attached_to_doctype attached_to_name = doc.attached_to_name try: ref_doc = frappe.get_doc(attached_to_doctype, attached_to_name) if ptype in ["write", "create", "delete"]: has_access = ref_doc.has_permission("write") if ptype == "delete" and not has_access: frappe.throw( _( "Cannot delete file as it belongs to {0} {1} for which you do not have permissions" ).format(doc.attached_to_doctype, doc.attached_to_name), frappe.PermissionError, ) else: has_access = ref_doc.has_permission("read") except frappe.DoesNotExistError: # if parent doc is not created before file is created # we cannot check its permission so we will use file's permission pass return has_access # Note: kept at the end to not cause circular, partial imports & maintain backwards compatibility from frappe.core.api.file import *
mit
514c4e214c84ffb4358b8ac65707bb49
28.392954
104
0.687535
3.073827
false
false
false
false
frappe/frappe
frappe/search/full_text_search.py
3
4437
# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE from whoosh.fields import ID, TEXT, Schema from whoosh.index import EmptyIndexError, create_in, open_dir from whoosh.qparser import FieldsPlugin, MultifieldParser, WildcardPlugin from whoosh.query import FuzzyTerm, Prefix from whoosh.writing import AsyncWriter import frappe from frappe.utils import update_progress_bar class FullTextSearch: """Frappe Wrapper for Whoosh""" def __init__(self, index_name): self.index_name = index_name self.index_path = get_index_path(index_name) self.schema = self.get_schema() self.id = self.get_id() def get_schema(self): return Schema(name=ID(stored=True), content=TEXT(stored=True)) def get_fields_to_search(self): return ["name", "content"] def get_id(self): return "name" def get_items_to_index(self): """Get all documents to be indexed conforming to the schema""" return [] def get_document_to_index(self): return {} def build(self): """Build search index for all documents""" self.documents = self.get_items_to_index() self.build_index() def update_index_by_name(self, doc_name): """Wraps `update_index` method, gets the document from name and updates the index. This function changes the current user and should only be run as administrator or in a background job. Args: self (object): FullTextSearch Instance doc_name (str): name of the document to be updated """ document = self.get_document_to_index(doc_name) if document: self.update_index(document) def remove_document_from_index(self, doc_name): """Remove document from search index Args: self (object): FullTextSearch Instance doc_name (str): name of the document to be removed """ if not doc_name: return ix = self.get_index() with ix.searcher(): writer = AsyncWriter(ix) writer.delete_by_term(self.id, doc_name) writer.commit(optimize=True) def update_index(self, document): """Update search index for a document Args: self (object): FullTextSearch Instance document (_dict): A dictionary with title, path and content """ ix = self.get_index() with ix.searcher(): writer = AsyncWriter(ix) writer.delete_by_term(self.id, document[self.id]) writer.add_document(**document) writer.commit(optimize=True) def get_index(self): try: return open_dir(self.index_path) except EmptyIndexError: return self.create_index() def create_index(self): frappe.create_folder(self.index_path) return create_in(self.index_path, self.schema) def build_index(self): """Build index for all parsed documents""" ix = self.create_index() writer = AsyncWriter(ix) for i, document in enumerate(self.documents): if document: writer.add_document(**document) update_progress_bar("Building Index", i, len(self.documents)) writer.commit(optimize=True) def search(self, text, scope=None, limit=20): """Search from the current index Args: text (str): String to search for scope (str, optional): Scope to limit the search. Defaults to None. limit (int, optional): Limit number of search results. Defaults to 20. Returns: [List(_dict)]: Search results """ ix = self.get_index() results = None out = [] search_fields = self.get_fields_to_search() fieldboosts = {} # apply reducing boost on fields based on order. 1.0, 0.5, 0.33 and so on for idx, field in enumerate(search_fields, start=1): fieldboosts[field] = 1.0 / idx with ix.searcher() as searcher: parser = MultifieldParser( search_fields, ix.schema, termclass=FuzzyTermExtended, fieldboosts=fieldboosts ) parser.remove_plugin_class(FieldsPlugin) parser.remove_plugin_class(WildcardPlugin) query = parser.parse(text) filter_scoped = None if scope: filter_scoped = Prefix(self.id, scope) results = searcher.search(query, limit=limit, filter=filter_scoped) for r in results: out.append(self.parse_result(r)) return out class FuzzyTermExtended(FuzzyTerm): def __init__(self, fieldname, text, boost=1.0, maxdist=2, prefixlength=1, constantscore=True): super().__init__( fieldname, text, boost=boost, maxdist=maxdist, prefixlength=prefixlength, constantscore=constantscore, ) def get_index_path(index_name): return frappe.get_site_path("indexes", index_name)
mit
851b496c8416d32ea3b639e0317ee5cf
25.890909
95
0.697318
3.260103
false
false
false
false
frappe/frappe
frappe/patches/v11_0/replicate_old_user_permissions.py
3
2831
import json import frappe from frappe.permissions import get_valid_perms from frappe.utils import cint def execute(): frappe.reload_doctype("User Permission") user_permissions = frappe.get_all("User Permission", fields=["allow", "name", "user"]) doctype_to_skip_map = {} for permission in user_permissions: if (permission.allow, permission.user) not in doctype_to_skip_map: doctype_to_skip_map[(permission.allow, permission.user)] = get_doctypes_to_skip( permission.allow, permission.user ) if not doctype_to_skip_map: return for key, doctype_to_skip in doctype_to_skip_map.items(): if not doctype_to_skip: continue if not frappe.db.has_column("User Permission", "applicable_for") and frappe.db.has_column( "User Permission", "skip_for_doctype" ): doctype_to_skip = "\n".join(doctype_to_skip) frappe.db.sql( """ update `tabUser Permission` set skip_for_doctype = %s where user=%s and allow=%s """, (doctype_to_skip, key[1], key[0]), ) def get_doctypes_to_skip(doctype, user): """Returns doctypes to be skipped from user permission check""" doctypes_to_skip = [] valid_perms = get_user_valid_perms(user) or [] for perm in valid_perms: parent_doctype = perm.parent try: linked_doctypes = get_linked_doctypes(parent_doctype) if doctype not in linked_doctypes: continue except frappe.DoesNotExistError: # if doctype not found (may be due to rename) it should not be considered for skip continue if not cint(perm.apply_user_permissions): # add doctype to skip list if any of the perm does not apply user permission doctypes_to_skip.append(parent_doctype) elif parent_doctype not in doctypes_to_skip: user_permission_doctypes = get_user_permission_doctypes(perm) # "No doctypes present" indicates that user permission will be applied to each link field if not user_permission_doctypes: continue elif doctype in user_permission_doctypes: continue else: doctypes_to_skip.append(parent_doctype) # to remove possible duplicates doctypes_to_skip = list(set(doctypes_to_skip)) return doctypes_to_skip # store user's valid perms to avoid repeated query user_valid_perm = {} def get_user_valid_perms(user): if not user_valid_perm.get(user): user_valid_perm[user] = get_valid_perms(user=user) return user_valid_perm.get(user) def get_user_permission_doctypes(perm): try: return json.loads(perm.user_permission_doctypes or "[]") except ValueError: return [] def get_linked_doctypes(doctype): from frappe.permissions import get_linked_doctypes linked_doctypes = get_linked_doctypes(doctype) child_doctypes = [d.options for d in frappe.get_meta(doctype).get_table_fields()] for child_dt in child_doctypes: linked_doctypes += get_linked_doctypes(child_dt) return linked_doctypes
mit
3ea95a94772d4cc999fc71a5fbdc38f4
27.31
92
0.722713
3.188063
false
false
false
false
frappe/frappe
frappe/tests/test_exporter_fixtures.py
2
8705
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import os import frappe import frappe.defaults from frappe.core.doctype.data_import.data_import import export_csv from frappe.tests.utils import FrappeTestCase class TestDataImportFixtures(FrappeTestCase): def setUp(self): pass # start test for Client Script def test_Custom_Script_fixture_simple(self): fixture = "Client Script" path = frappe.scrub(fixture) + "_original_style.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_simple_name_equal_default(self): fixture = ["Client Script", {"name": ["Item"]}] path = frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_simple_name_equal(self): fixture = ["Client Script", {"name": ["Item"], "op": "="}] path = frappe.scrub(fixture[0]) + "_simple_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_simple_name_not_equal(self): fixture = ["Client Script", {"name": ["Item"], "op": "!="}] path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # without [] around the name... def test_Custom_Script_fixture_simple_name_at_least_equal(self): fixture = ["Client Script", {"name": "Item-Cli"}] path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_multi_name_equal(self): fixture = ["Client Script", {"name": ["Item", "Customer"], "op": "="}] path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_multi_name_not_equal(self): fixture = ["Client Script", {"name": ["Item", "Customer"], "op": "!="}] path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_empty_object(self): fixture = ["Client Script", {}] path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_just_list(self): fixture = ["Client Script"] path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # Client Script regular expression def test_Custom_Script_fixture_rex_no_flags(self): fixture = ["Client Script", {"name": r"^[i|A]"}] path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Script_fixture_rex_with_flags(self): fixture = ["Client Script", {"name": r"^[i|A]", "flags": "L,M"}] path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # start test for Custom Field def test_Custom_Field_fixture_simple(self): fixture = "Custom Field" path = frappe.scrub(fixture) + "_original_style.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_simple_name_equal_default(self): fixture = ["Custom Field", {"name": ["Item-vat"]}] path = frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_simple_name_equal(self): fixture = ["Custom Field", {"name": ["Item-vat"], "op": "="}] path = frappe.scrub(fixture[0]) + "_simple_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_simple_name_not_equal(self): fixture = ["Custom Field", {"name": ["Item-vat"], "op": "!="}] path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # without [] around the name... def test_Custom_Field_fixture_simple_name_at_least_equal(self): fixture = ["Custom Field", {"name": "Item-va"}] path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_multi_name_equal(self): fixture = ["Custom Field", {"name": ["Item-vat", "Bin-vat"], "op": "="}] path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_multi_name_not_equal(self): fixture = ["Custom Field", {"name": ["Item-vat", "Bin-vat"], "op": "!="}] path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_empty_object(self): fixture = ["Custom Field", {}] path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_just_list(self): fixture = ["Custom Field"] path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # Custom Field regular expression def test_Custom_Field_fixture_rex_no_flags(self): fixture = ["Custom Field", {"name": r"^[r|L]"}] path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Custom_Field_fixture_rex_with_flags(self): fixture = ["Custom Field", {"name": r"^[i|A]", "flags": "L,M"}] path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # start test for Doctype def test_Doctype_fixture_simple(self): fixture = "ToDo" path = "Doctype_" + frappe.scrub(fixture) + "_original_style_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_fixture_simple_name_equal_default(self): fixture = ["ToDo", {"name": ["TDI00000008"]}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_fixture_simple_name_equal(self): fixture = ["ToDo", {"name": ["TDI00000002"], "op": "="}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_simple_name_not_equal(self): fixture = ["ToDo", {"name": ["TDI00000002"], "op": "!="}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # without [] around the name... def test_Doctype_fixture_simple_name_at_least_equal(self): fixture = ["ToDo", {"name": "TDI"}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_multi_name_equal(self): fixture = ["ToDo", {"name": ["TDI00000002", "TDI00000008"], "op": "="}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_multi_name_not_equal(self): fixture = ["ToDo", {"name": ["TDI00000002", "TDI00000008"], "op": "!="}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_fixture_empty_object(self): fixture = ["ToDo", {}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_fixture_just_list(self): fixture = ["ToDo"] path = "Doctype_" + frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) # Doctype regular expression def test_Doctype_fixture_rex_no_flags(self): fixture = ["ToDo", {"name": r"^TDi"}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_rex_no_flags_should_be_all.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path) def test_Doctype_fixture_rex_with_flags(self): fixture = ["ToDo", {"name": r"^TDi", "flags": "L,M"}] path = "Doctype_" + frappe.scrub(fixture[0]) + "_rex_with_flags_should_be_none.csv" export_csv(fixture, path) self.assertTrue(True) os.remove(path)
mit
7e3fb3fc9755d7c9f1e864a82f921b65
29.437063
85
0.674785
2.826299
false
true
false
false
simpeg/discretize
discretize/utils/curvilinear_utils.py
1
18626
import numpy as np from discretize.utils.matrix_utils import mkvc, ndgrid, sub2ind from discretize.utils.code_utils import deprecate_function import warnings def example_curvilinear_grid(nC, exType): """Creates and returns the gridded node locations for a curvilinear mesh. Parameters ---------- nC : list of int list of number of cells in each dimension. Must be length 2 or 3 exType : {"rect", "rotate", "sphere"} String specifying the style of example curvilinear mesh. Returns ------- list of numpy.ndarray List containing the gridded x, y (and z) node locations for the curvilinear mesh. """ if not isinstance(nC, list): raise TypeError("nC must be a list containing the number of nodes") if len(nC) != 2 and len(nC) != 3: raise ValueError("nC must either two or three dimensions") exType = exType.lower() possibleTypes = ["rect", "rotate", "sphere"] if exType not in possibleTypes: raise TypeError("Not a possible example type.") if exType == "rect": return list( ndgrid([np.cumsum(np.r_[0, np.ones(nx) / nx]) for nx in nC], vector=False) ) elif exType == "sphere": nodes = list( ndgrid( [np.cumsum(np.r_[0, np.ones(nx) / nx]) - 0.5 for nx in nC], vector=False ) ) nodes = np.stack(nodes, axis=-1) nodes = 2 * nodes # L_inf distance to center r0 = np.linalg.norm(nodes, ord=np.inf, axis=-1) # L2 distance to center r2 = np.linalg.norm(nodes, axis=-1) r0[r0 == 0.0] = 1.0 r2[r2 == 0.0] = 1.0 scale = r0 / r2 nodes = nodes * scale[..., None] nodes = np.transpose(nodes, (-1, *np.arange(len(nC)))) nodes = [node for node in nodes] # turn it into a list return nodes elif exType == "rotate": if len(nC) == 2: X, Y = ndgrid( [np.cumsum(np.r_[0, np.ones(nx) / nx]) for nx in nC], vector=False ) amt = 0.5 - np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2) amt[amt < 0] = 0 return [X + (-(Y - 0.5)) * amt, Y + (+(X - 0.5)) * amt] elif len(nC) == 3: X, Y, Z = ndgrid( [np.cumsum(np.r_[0, np.ones(nx) / nx]) for nx in nC], vector=False ) amt = 0.5 - np.sqrt((X - 0.5) ** 2 + (Y - 0.5) ** 2 + (Z - 0.5) ** 2) amt[amt < 0] = 0 return [ X + (-(Y - 0.5)) * amt, Y + (-(Z - 0.5)) * amt, Z + (-(X - 0.5)) * amt, ] def volume_tetrahedron(xyz, A, B, C, D): """Returns the tetrahedron volumes for a specified set of verticies. Let *xyz* be an (n, 3) array denoting a set of vertex locations. Any 4 vertex locations *a, b, c* and *d* can be used to define a tetrahedron. For the set of tetrahedra whose verticies are indexed in vectors *A, B, C* and *D*, this function returns the corresponding volumes. See algorithm: https://en.wikipedia.org/wiki/Tetrahedron#Volume .. math:: vol = {1 \\over 6} \\big | ( \\mathbf{a - d} ) \\cdot ( ( \\mathbf{b - d} ) \\times ( \\mathbf{c - d} ) ) \\big | Parameters ---------- xyz : (n_pts, 3) numpy.ndarray x,y, and z locations for all verticies A : (n_tetra) numpy.ndarray of int Vector containing the indicies for the **a** vertex locations B : (n_tetra) numpy.ndarray of int Vector containing the indicies for the **b** vertex locations C : (n_tetra) numpy.ndarray of int Vector containing the indicies for the **c** vertex locations D : (n_tetra) numpy.ndarray of int Vector containing the indicies for the **d** vertex locations Returns ------- (n_tetra) numpy.ndarray Volumes of the tetrahedra whose vertices are indexed by *A, B, C* and *D*. Examples -------- Here we define a small 3D tensor mesh. 4 nodes are chosen to be the verticies of a tetrahedron. We compute the volume of this tetrahedron. Note that xyz locations for the verticies can be scattered and do not require regular spacing. >>> from discretize.utils import volume_tetrahedron >>> from discretize import TensorMesh >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import matplotlib as mpl >>> mpl.rcParams.update({"font.size": 14}) Define corners of a uniform cube >>> h = [1, 1] >>> mesh = TensorMesh([h, h, h]) >>> xyz = mesh.nodes Specify the indicies of the corner points >>> A = np.array([0]) >>> B = np.array([6]) >>> C = np.array([8]) >>> D = np.array([24]) Compute volume for all tetrahedra and the extract first one >>> vol = volume_tetrahedron(xyz, A, B, C, D) >>> vol = vol[0] >>> vol array([1.33333333]) Plotting small mesh and tetrahedron .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(7, 7)) >>> ax = fig.gca(projection='3d') >>> mesh.plot_grid(ax=ax) >>> k = [0, 6, 8, 0, 24, 6, 24, 8] >>> xyz_tetra = xyz[k, :] >>> ax.plot(xyz_tetra[:, 0], xyz_tetra[:, 1], xyz_tetra[:, 2], 'r') >>> ax.text(-0.25, 0., 3., 'Volume of the tetrahedron: {:g} $m^3$'.format(vol)) >>> plt.show() """ AD = xyz[A, :] - xyz[D, :] BD = xyz[B, :] - xyz[D, :] CD = xyz[C, :] - xyz[D, :] V = ( (BD[:, 0] * CD[:, 1] - BD[:, 1] * CD[:, 0]) * AD[:, 2] - (BD[:, 0] * CD[:, 2] - BD[:, 2] * CD[:, 0]) * AD[:, 1] + (BD[:, 1] * CD[:, 2] - BD[:, 2] * CD[:, 1]) * AD[:, 0] ) return np.abs(V / 6) def index_cube(nodes, grid_shape, n=None): """Returns the index of nodes on a tensor (or curvilinear) mesh. For 2D tensor meshes, each cell is defined by nodes *A, B, C* and *D*. And for 3D tensor meshes, each cell is defined by nodes *A* through *H* (see below). *index_cube* outputs the indices for the specified node(s) for all cells in the mesh. TWO DIMENSIONS:: node(i,j+1) node(i+i,j+1) B -------------- C | | | cell(i,j) | | I | | | A -------------- D node(i,j) node(i+1,j) THREE DIMENSIONS:: node(i,j+1,k+1) node(i+1,j+1,k+1) F ---------------- G /| / | / | / | / | / | node(i,j,k+1) node(i+1,j,k+1) E --------------- H | | B -----------|---- C | / cell(i,j,k) | / | / I | / | / | / A --------------- D node(i,j,k) node(i+1,j,k) Parameters ---------- nodes : str String specifying which nodes to return. For 2D meshes, *nodes* must be a string containing combinations of the characters 'A', 'B', 'C', or 'D'. For 3D meshes, *nodes* can also be 'E', 'F', 'G', or 'H'. Note that order is preserved. E.g. if we want to return the C, D and A node indices in that particular order, we input *nodes* = 'CDA'. grid_shape : list of int Number of nodes along the i,j,k directions; e.g. [ni,nj,nk] nc : list of int Number of cells along the i,j,k directions; e.g. [nci,ncj,nck] Returns ------- index : tuple of numpy.ndarray Each entry of the tuple is a 1D :class:`numpy.ndarray` containing the indices of the nodes specified in the input *nodes* in the order asked; e.g. if *nodes* = 'DCBA', the tuple returned is ordered (D,C,B,A). Examples -------- Here, we construct a small 2D tensor mesh (works for a curvilinear mesh as well) and use *index_cube* to find the indices of the 'A' and 'C' nodes. We then plot the mesh, as well as the 'A' and 'C' node locations. >>> from discretize import TensorMesh >>> from discretize.utils import index_cube >>> from matplotlib import pyplot as plt >>> import numpy as np Create a simple tensor mesh. >>> n_cells = 5 >>> h = 2*np.ones(n_cells) >>> mesh = TensorMesh([h, h], x0='00') Get indices of 'A' and 'C' nodes for all cells. >>> A, C = index_cube('AC', [n_cells+1, n_cells+1]) Plot mesh and the locations of the A and C nodes .. collapse:: Expand to show scripting for plot >>> fig1 = plt.figure(figsize=(5, 5)) >>> ax1 = fig1.add_axes([0.1, 0.1, 0.8, 0.8]) >>> mesh.plot_grid(ax=ax1) >>> ax1.scatter(mesh.nodes[A, 0], mesh.nodes[A, 1], 100, 'r', marker='^') >>> ax1.scatter(mesh.nodes[C, 0], mesh.nodes[C, 1], 100, 'g', marker='v') >>> ax1.set_title('A nodes (red) and C nodes (green)') >>> plt.show() """ if not isinstance(nodes, str): raise TypeError("Nodes must be a str variable: e.g. 'ABCD'") nodes = nodes.upper() try: dim = len(grid_shape) if n is None: n = tuple(x - 1 for x in grid_shape) except TypeError: return TypeError("grid_shape must be iterable") # Make sure that we choose from the possible nodes. possibleNodes = "ABCD" if dim == 2 else "ABCDEFGH" for node in nodes: if node not in possibleNodes: raise ValueError("Nodes must be chosen from: '{0!s}'".format(possibleNodes)) if dim == 2: ij = ndgrid(np.arange(n[0]), np.arange(n[1])) i, j = ij[:, 0], ij[:, 1] elif dim == 3: ijk = ndgrid(np.arange(n[0]), np.arange(n[1]), np.arange(n[2])) i, j, k = ijk[:, 0], ijk[:, 1], ijk[:, 2] else: raise Exception("Only 2 and 3 dimensions supported.") nodeMap = { "A": [0, 0, 0], "B": [0, 1, 0], "C": [1, 1, 0], "D": [1, 0, 0], "E": [0, 0, 1], "F": [0, 1, 1], "G": [1, 1, 1], "H": [1, 0, 1], } out = () for node in nodes: shift = nodeMap[node] if dim == 2: out += (sub2ind(grid_shape, np.c_[i + shift[0], j + shift[1]]).flatten(),) elif dim == 3: out += ( sub2ind( grid_shape, np.c_[i + shift[0], j + shift[1], k + shift[2]] ).flatten(), ) return out def face_info(xyz, A, B, C, D, average=True, normalize_normals=True, **kwargs): """Returns normal surface vector and area for a given set of faces. Let *xyz* be an (n, 3) array denoting a set of vertex locations. Now let vertex locations *a, b, c* and *d* define a quadrilateral (regular or irregular) in 2D or 3D space. For this quadrilateral, we organize the vertices as follows: CELL VERTICES:: a -------Vab------- b / / / / Vda (X) Vbc / / / / d -------Vcd------- c where the normal vector *(X)* is pointing into the page. For a set of quadrilaterals whose vertices are indexed in arrays *A, B, C* and *D* , this function returns the normal surface vector(s) and the area for each quadrilateral. At each vertex, there are 4 cross-products that can be used to compute the vector normal the surface defined by the quadrilateral. In 3D space however, the vertices indexed may not define a quadrilateral exactly and thus the normal vectors computed at each vertex might not be identical. In this case, you may choose output the normal vector at *a, b, c* and *d* or compute the average normal surface vector as follows: .. math:: \\bf{n} = \\frac{1}{4} \\big ( \\bf{v_{ab} \\times v_{da}} + \\bf{v_{bc} \\times v_{ab}} + \\bf{v_{cd} \\times v_{bc}} + \\bf{v_{da} \\times v_{cd}} \\big ) For computing the surface area, we assume the vertices define a quadrilateral. Parameters ---------- xyz : (n, 3) numpy.ndarray The x,y, and z locations for all verticies A : (n_face) numpy.ndarray Vector containing the indicies for the **a** vertex locations B : (n_face) numpy.ndarray Vector containing the indicies for the **b** vertex locations C : (n_face) numpy.ndarray Vector containing the indicies for the **c** vertex locations D : (n_face) numpy.ndarray Vector containing the indicies for the **d** vertex locations average : bool, optional If *True*, the function returns the average surface normal vector for each surface. If *False* , the function will return the normal vectors computed at the *A, B, C* and *D* vertices in a cell array {nA,nB,nC,nD}. normalize_normal : bool, optional If *True*, the function will normalize the surface normal vectors. This is applied regardless of whether the *average* parameter is set to *True* or *False*. If *False*, the vectors are not normalized. Returns ------- N : (n_face) numpy.ndarray or (4) list of (n_face) numpy.ndarray Normal vector(s) for each surface. If *average* = *True*, the function returns an ndarray with the average surface normal vectos. If *average* = *False* , the function returns a cell array {nA,nB,nC,nD} containing the normal vectors computed using each vertex of the surface. area : (n_face) numpy.ndarray The surface areas. Examples -------- Here we define a set of vertices for a tensor mesh. We then index 4 vertices for an irregular quadrilateral. The function *face_info* is used to compute the normal vector and the surface area. >>> from discretize.utils import face_info >>> from discretize import TensorMesh >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import matplotlib as mpl >>> mpl.rcParams.update({"font.size": 14}) Define Corners of a uniform cube. >>> h = [1, 1] >>> mesh = TensorMesh([h, h, h]) >>> xyz = mesh.nodes Choose the face indices, >>> A = np.array([0]) >>> B = np.array([4]) >>> C = np.array([26]) >>> D = np.array([18]) Compute average surface normal vector (normalized), >>> nvec, area = face_info(xyz, A, B, C, D) >>> nvec, area (array([[-0.70710678, 0.70710678, 0. ]]), array([4.24264069])) Plot surface for example 1 on mesh .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(7, 7)) >>> ax = fig.gca(projection='3d') >>> mesh.plot_grid(ax=ax) >>> k = [0, 4, 26, 18, 0] >>> xyz_quad = xyz[k, :] >>> ax.plot(xyz_quad[:, 0], xyz_quad[:, 1], xyz_quad[:, 2], 'r') >>> ax.text(-0.25, 0., 3., 'Area of the surface: {:g} $m^2$'.format(area[0])) >>> ax.text(-0.25, 0., 2.8, 'Normal vector: ({:.2f}, {:.2f}, {:.2f})'.format( ... nvec[0, 0], nvec[0, 1], nvec[0, 2]) ... ) >>> plt.show() In our second example, the vertices are unable to define a flat surface in 3D space. However, we will demonstrate the *face_info* returns the average normal vector and an approximate surface area. Define the face indicies >>> A = np.array([0]) >>> B = np.array([5]) >>> C = np.array([26]) >>> D = np.array([18]) Compute average surface normal vector >>> nvec, area = face_info(xyz, A, B, C, D) >>> nvec, area (array([[-0.4472136 , 0.89442719, 0. ]]), array([2.23606798])) Plot surface for example 2 on mesh .. collapse:: Expand to show scripting for plot >>> fig = plt.figure(figsize=(7, 7)) >>> ax = fig.gca(projection='3d') >>> mesh.plot_grid(ax=ax) >>> k = [0, 5, 26, 18, 0] >>> xyz_quad = xyz[k, :] >>> ax.plot(xyz_quad[:, 0], xyz_quad[:, 1], xyz_quad[:, 2], 'g') >>> ax.text(-0.25, 0., 3., 'Area of the surface: {:g} $m^2$'.format(area[0])) >>> ax.text(-0.25, 0., 2.8, 'Average normal vector: ({:.2f}, {:.2f}, {:.2f})'.format( ... nvec[0, 0], nvec[0, 1], nvec[0, 2]) ... ) >>> plt.show() """ if "normalizeNormals" in kwargs: warnings.warn( "The normalizeNormals keyword argument has been deprecated, please use normalize_normals. " "This will be removed in discretize 1.0.0", FutureWarning, ) normalize_normals = kwargs["normalizeNormals"] if not isinstance(average, bool): raise TypeError("average must be a boolean") if not isinstance(normalize_normals, bool): raise TypeError("normalize_normals must be a boolean") AB = xyz[B, :] - xyz[A, :] BC = xyz[C, :] - xyz[B, :] CD = xyz[D, :] - xyz[C, :] DA = xyz[A, :] - xyz[D, :] def cross(X, Y): return np.c_[ X[:, 1] * Y[:, 2] - X[:, 2] * Y[:, 1], X[:, 2] * Y[:, 0] - X[:, 0] * Y[:, 2], X[:, 0] * Y[:, 1] - X[:, 1] * Y[:, 0], ] nA = cross(AB, DA) nB = cross(BC, AB) nC = cross(CD, BC) nD = cross(DA, CD) length = lambda x: np.sqrt(x[:, 0] ** 2 + x[:, 1] ** 2 + x[:, 2] ** 2) normalize = lambda x: x / np.kron(np.ones((1, x.shape[1])), mkvc(length(x), 2)) if average: # average the normals at each vertex. N = (nA + nB + nC + nD) / 4 # this is intrinsically weighted by area # normalize N = normalize(N) else: if normalize_normals: N = [normalize(nA), normalize(nB), normalize(nC), normalize(nD)] else: N = [nA, nB, nC, nD] # Area calculation # # Approximate by 4 different triangles, and divide by 2. # Each triangle is one half of the length of the cross product # # So also could be viewed as the average parallelogram. # # TODO: This does not compute correctly for concave quadrilaterals area = (length(nA) + length(nB) + length(nC) + length(nD)) / 4 return N, area exampleLrmGrid = deprecate_function( example_curvilinear_grid, "exampleLrmGrid", removal_version="1.0.0", future_warn=True, ) volTetra = deprecate_function( volume_tetrahedron, "volTetra", removal_version="1.0.0", future_warn=True ) indexCube = deprecate_function( index_cube, "indexCube", removal_version="1.0.0", future_warn=True ) faceInfo = deprecate_function( face_info, "faceInfo", removal_version="1.0.0", future_warn=True )
mit
c288eb3f8e200f0166b28afd1757b2cf
34.077213
103
0.538172
3.351205
false
false
false
false
richardkiss/pycoin
pycoin/crack/ecdsa.py
1
1028
def crack_secret_exponent_from_k(generator, signed_value, sig, k): """ Given a signature of a signed_value and a known k, return the secret exponent. """ r, s = sig return ((s * k - signed_value) * generator.inverse(r)) % generator.order() def crack_k_from_sigs(generator, sig1, val1, sig2, val2): """ Given two signatures with the same secret exponent and K value, return that K value. """ # s1 = v1 / k1 + (se * r1) / k1 # s2 = v2 / k2 + (se * r2) / k2 # and k = k1 = k2 # so # k * s1 = v1 + (se * r1) # k * s2 = v2 + (se * r2) # so # k * s1 * r2 = r2 * v1 + (se * r1 * r2) # k * s2 * r1 = r1 * v2 + (se * r2 * r1) # so # k (s1 * r2 - s2 * r1) = r2 * v1 - r1 * v2 # so # k = (r2 * v1 - r1 * v2) / (s1 * r2 - s2 * r1) r1, s1 = sig1 r2, s2 = sig2 if r1 != r2: raise ValueError("r values of signature do not match") k = (r2 * val1 - r1 * val2) * generator.inverse(r2 * s1 - r1 * s2) return k % generator.order()
mit
185d4f29d87308b998dc55c3f08efef3
29.235294
88
0.508755
2.53202
false
false
false
false
frappe/frappe
frappe/core/doctype/server_script/server_script_utils.py
3
2283
import frappe # this is a separate file since it is imported in frappe.model.document # to avoid circular imports EVENT_MAP = { "before_insert": "Before Insert", "after_insert": "After Insert", "before_validate": "Before Validate", "validate": "Before Save", "on_update": "After Save", "before_submit": "Before Submit", "on_submit": "After Submit", "before_cancel": "Before Cancel", "on_cancel": "After Cancel", "on_trash": "Before Delete", "after_delete": "After Delete", "before_update_after_submit": "Before Save (Submitted Document)", "on_update_after_submit": "After Save (Submitted Document)", "on_payment_authorized": "On Payment Authorization", } def run_server_script_for_doc_event(doc, event): # run document event method if not event in EVENT_MAP: return if frappe.flags.in_install: return if frappe.flags.in_migrate: return scripts = get_server_script_map().get(doc.doctype, {}).get(EVENT_MAP[event], None) if scripts: # run all scripts for this doctype + event for script_name in scripts: frappe.get_doc("Server Script", script_name).execute_doc(doc) def get_server_script_map(): # fetch cached server script methods # { # '[doctype]': { # 'Before Insert': ['[server script 1]', '[server script 2]'] # }, # '_api': { # '[path]': '[server script]' # }, # 'permission_query': { # 'DocType': '[server script]' # } # } if frappe.flags.in_patch and not frappe.db.table_exists("Server Script"): return {} script_map = frappe.cache().get_value("server_script_map") if script_map is None: script_map = {"permission_query": {}} enabled_server_scripts = frappe.get_all( "Server Script", fields=("name", "reference_doctype", "doctype_event", "api_method", "script_type"), filters={"disabled": 0}, ) for script in enabled_server_scripts: if script.script_type == "DocType Event": script_map.setdefault(script.reference_doctype, {}).setdefault( script.doctype_event, [] ).append(script.name) elif script.script_type == "Permission Query": script_map["permission_query"][script.reference_doctype] = script.name else: script_map.setdefault("_api", {})[script.api_method] = script.name frappe.cache().set_value("server_script_map", script_map) return script_map
mit
64007fc1bfb821628ec9d310e77a93f9
28.269231
86
0.674113
3.080972
false
false
false
false
frappe/frappe
frappe/patches/v11_0/make_all_prepared_report_attachments_private.py
3
1044
import frappe def execute(): if ( frappe.db.count("File", filters={"attached_to_doctype": "Prepared Report", "is_private": 0}) > 10000 ): frappe.db.auto_commit_on_many_writes = True files = frappe.get_all( "File", fields=["name", "attached_to_name"], filters={"attached_to_doctype": "Prepared Report", "is_private": 0}, ) for file_dict in files: # For some reason Prepared Report doc might not exist, check if it exists first if frappe.db.exists("Prepared Report", file_dict.attached_to_name): try: file_doc = frappe.get_doc("File", file_dict.name) file_doc.is_private = 1 file_doc.save() except Exception: # File might not exist on the file system in that case delete both Prepared Report and File doc frappe.delete_doc("Prepared Report", file_dict.attached_to_name) else: # If Prepared Report doc doesn't exist then the file doc is useless. Delete it. frappe.delete_doc("File", file_dict.name) if frappe.db.auto_commit_on_many_writes: frappe.db.auto_commit_on_many_writes = False
mit
60cb745428223f98f459755cc9a599f1
32.677419
99
0.694444
3.135135
false
false
false
false
frappe/frappe
frappe/website/doctype/help_article/help_article.py
3
3237
# Copyright (c) 2013, Frappe and contributors # License: MIT. See LICENSE import frappe from frappe import _ from frappe.utils import cint, is_markdown, markdown from frappe.website.utils import get_comment_list from frappe.website.website_generator import WebsiteGenerator class HelpArticle(WebsiteGenerator): def validate(self): self.set_route() def set_route(self): """Set route from category and title if missing""" if not self.route: self.route = "/".join( [frappe.get_value("Help Category", self.category, "route"), self.scrub(self.title)] ) def on_update(self): self.update_category() clear_cache() def update_category(self): cnt = frappe.db.sql( """select count(*) from `tabHelp Article` where category=%s and ifnull(published,0)=1""", self.category, )[0][0] cat = frappe.get_doc("Help Category", self.category) cat.help_articles = cnt cat.save() def get_context(self, context): if is_markdown(context.content): context.content = markdown(context.content) context.login_required = True context.category = frappe.get_doc("Help Category", self.category) context.level_class = get_level_class(self.level) context.comment_list = get_comment_list(self.doctype, self.name) context.show_sidebar = True context.sidebar_items = get_sidebar_items() context.parents = self.get_parents(context) def get_parents(self, context): return [{"title": context.category.category_name, "route": context.category.route}] def get_list_context(context=None): filters = dict(published=1) category = frappe.db.get_value("Help Category", {"route": frappe.local.path}) if category: filters["category"] = category list_context = frappe._dict( title=category or _("Knowledge Base"), get_level_class=get_level_class, show_sidebar=True, sidebar_items=get_sidebar_items(), hide_filters=True, filters=filters, category=frappe.local.form_dict.category, no_breadcrumbs=True, ) if frappe.local.form_dict.txt: list_context.blog_subtitle = _('Filtered by "{0}"').format(frappe.local.form_dict.txt) # # list_context.update(frappe.get_doc("Blog Settings", "Blog Settings").as_dict()) return list_context def get_level_class(level): return {"Beginner": "green", "Intermediate": "orange", "Expert": "red"}[level] def get_sidebar_items(): def _get(): return frappe.db.sql( """select concat(category_name, " (", help_articles, ")") as title, concat('/', route) as route from `tabHelp Category` where ifnull(published,0)=1 and help_articles > 0 order by help_articles desc""", as_dict=True, ) return frappe.cache().get_value("knowledge_base:category_sidebar", _get) def clear_cache(): clear_website_cache() from frappe.website.utils import clear_cache clear_cache() def clear_website_cache(path=None): frappe.cache().delete_value("knowledge_base:category_sidebar") frappe.cache().delete_value("knowledge_base:faq") @frappe.whitelist(allow_guest=True) def add_feedback(article, helpful): field = "helpful" if helpful == "No": field = "not_helpful" value = cint(frappe.db.get_value("Help Article", article, field)) frappe.db.set_value("Help Article", article, field, value + 1, update_modified=False)
mit
93da5d772fca4714b60906c7651f5812
26.201681
88
0.707136
3.130561
false
false
false
false
frappe/frappe
frappe/deferred_insert.py
3
1493
import json from typing import TYPE_CHECKING, Union import redis import frappe from frappe.utils import cstr if TYPE_CHECKING: from frappe.model.document import Document queue_prefix = "insert_queue_for_" def deferred_insert(doctype: str, records: list[Union[dict, "Document"]] | str): if isinstance(records, (dict, list)): _records = json.dumps(records) else: _records = records try: frappe.cache().rpush(f"{queue_prefix}{doctype}", _records) except redis.exceptions.ConnectionError: for record in records: insert_record(record, doctype) def save_to_db(): queue_keys = frappe.cache().get_keys(queue_prefix) for key in queue_keys: record_count = 0 queue_key = get_key_name(key) doctype = get_doctype_name(key) while frappe.cache().llen(queue_key) > 0 and record_count <= 500: records = frappe.cache().lpop(queue_key) records = json.loads(records.decode("utf-8")) if isinstance(records, dict): record_count += 1 insert_record(records, doctype) continue for record in records: record_count += 1 insert_record(record, doctype) def insert_record(record: Union[dict, "Document"], doctype: str): try: record.update({"doctype": doctype}) frappe.get_doc(record).insert() except Exception as e: frappe.logger().error(f"Error while inserting deferred {doctype} record: {e}") def get_key_name(key: str) -> str: return cstr(key).split("|")[1] def get_doctype_name(key: str) -> str: return cstr(key).split(queue_prefix)[1]
mit
16150148f94554d2585555ced9023bfb
24.305085
80
0.701942
3.110417
false
false
false
false
frappe/frappe
frappe/query_builder/custom.py
3
3433
from typing import Any from pypika.functions import DistinctOptionFunction from pypika.terms import Term from pypika.utils import builder, format_alias_sql, format_quotes import frappe class GROUP_CONCAT(DistinctOptionFunction): def __init__(self, column: str, alias: str | None = None): """[ Implements the group concat function read more about it at https://www.geeksforgeeks.org/mysql-group_concat-function ] Args: column (str): [ name of the column you want to concat] alias (Optional[str], optional): [ is this an alias? ]. Defaults to None. """ super().__init__("GROUP_CONCAT", column, alias=alias) class STRING_AGG(DistinctOptionFunction): def __init__(self, column: str, separator: str = ",", alias: str | None = None): """[ Implements the group concat function read more about it at https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15 ] Args: column (str): [ name of the column you want to concat ] separator (str, optional): [separator to be used]. Defaults to ",". alias (Optional[str], optional): [description]. Defaults to None. """ super().__init__("STRING_AGG", column, separator, alias=alias) class MATCH(DistinctOptionFunction): def __init__(self, column: str, *args, **kwargs): """[ Implementation of Match Against read more about it https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html#function_match ] Args: column (str):[ column to search in ] """ alias = kwargs.get("alias") super().__init__(" MATCH", column, *args, alias=alias) self._Against = False def get_function_sql(self, **kwargs): s = super(DistinctOptionFunction, self).get_function_sql(**kwargs) if self._Against: return f"{s} AGAINST ({frappe.db.escape(f'+{self._Against}*')} IN BOOLEAN MODE)" raise Exception("Chain the `Against()` method with match to complete the query") @builder def Against(self, text: str): """[ Text that has to be searched against ] Args: text (str): [ the text string that we match it against ] """ self._Against = text class TO_TSVECTOR(DistinctOptionFunction): def __init__(self, column: str, *args, **kwargs): """[ Implementation of TO_TSVECTOR read more about it https://www.postgresql.org/docs/9.1/textsearch-controls.html] Args: column (str): [ column to search in ] """ alias = kwargs.get("alias") super().__init__("TO_TSVECTOR", column, *args, alias=alias) self._PLAINTO_TSQUERY = False def get_function_sql(self, **kwargs): s = super(DistinctOptionFunction, self).get_function_sql(**kwargs) if self._PLAINTO_TSQUERY: return f"{s} @@ PLAINTO_TSQUERY({frappe.db.escape(self._PLAINTO_TSQUERY)})" return s @builder def Against(self, text: str): """[ Text that has to be searched against ] Args: text (str): [ the text string that we match it against ] """ self._PLAINTO_TSQUERY = text class ConstantColumn(Term): alias = None def __init__(self, value: str) -> None: """[ Returns a pseudo column with a constant value in all the rows] Args: value (str): [ Value of the column ] """ self.value = value def get_sql(self, quote_char: str | None = None, **kwargs: Any) -> str: return format_alias_sql( format_quotes(self.value, kwargs.get("secondary_quote_char") or ""), self.alias or self.value, quote_char=quote_char, **kwargs, )
mit
986d9382657b4aab902ec7a7aacb9e53
32.009615
166
0.669094
3.208411
false
false
false
false
frappe/frappe
frappe/integrations/doctype/webhook/__init__.py
2
2323
# Copyright (c) 2017, Frappe Technologies and contributors # License: MIT. See LICENSE import frappe def run_webhooks(doc, method): """Run webhooks for this method""" if ( frappe.flags.in_import or frappe.flags.in_patch or frappe.flags.in_install or frappe.flags.in_migrate ): return if frappe.flags.webhooks_executed is None: frappe.flags.webhooks_executed = {} # TODO: remove this hazardous unnecessary cache in flags if frappe.flags.webhooks is None: # load webhooks from cache webhooks = frappe.cache().get_value("webhooks") if webhooks is None: # query webhooks webhooks_list = frappe.get_all( "Webhook", fields=["name", "condition", "webhook_docevent", "webhook_doctype"], filters={"enabled": True}, ) # make webhooks map for cache webhooks = {} for w in webhooks_list: webhooks.setdefault(w.webhook_doctype, []).append(w) frappe.cache().set_value("webhooks", webhooks) frappe.flags.webhooks = webhooks # get webhooks for this doctype webhooks_for_doc = frappe.flags.webhooks.get(doc.doctype, None) if not webhooks_for_doc: # no webhooks, quit return def _webhook_request(webhook): if webhook.name not in frappe.flags.webhooks_executed.get(doc.name, []): frappe.enqueue( "frappe.integrations.doctype.webhook.webhook.enqueue_webhook", enqueue_after_commit=True, doc=doc, webhook=webhook, ) # keep list of webhooks executed for this doc in this request # so that we don't run the same webhook for the same document multiple times # in one request frappe.flags.webhooks_executed.setdefault(doc.name, []).append(webhook.name) event_list = ["on_update", "after_insert", "on_submit", "on_cancel", "on_trash"] if not doc.flags.in_insert: # value change is not applicable in insert event_list.append("on_change") event_list.append("before_update_after_submit") from frappe.integrations.doctype.webhook.webhook import get_context for webhook in webhooks_for_doc: trigger_webhook = False event = method if method in event_list else None if not webhook.condition: trigger_webhook = True elif frappe.safe_eval(webhook.condition, eval_locals=get_context(doc)): trigger_webhook = True if trigger_webhook and event and webhook.webhook_docevent == event: _webhook_request(webhook)
mit
7ea03fb3538319f23ddb9d3b23752258
28.405063
81
0.717176
3.258065
false
false
false
false
frappe/frappe
frappe/utils/__init__.py
2
26864
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import functools import hashlib import io import json import os import re import sys import traceback from collections.abc import ( Container, Generator, Iterable, MutableMapping, MutableSequence, Sequence, ) from email.header import decode_header, make_header from email.utils import formataddr, parseaddr from gzip import GzipFile from typing import Any, Literal from urllib.parse import quote, urlparse from redis.exceptions import ConnectionError from traceback_with_variables import iter_exc_lines from werkzeug.test import Client import frappe # utility functions like cint, int, flt, etc. from frappe.utils.data import * from frappe.utils.html_utils import sanitize_html EMAIL_NAME_PATTERN = re.compile(r"[^A-Za-z0-9\u00C0-\u024F\/\_\' ]+") EMAIL_STRING_PATTERN = re.compile(r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)") NON_MD_HTML_PATTERN = re.compile(r"<p[\s]*>|<br[\s]*>") HTML_TAGS_PATTERN = re.compile(r"\<[^>]*\>") INCLUDE_DIRECTIVE_PATTERN = re.compile("""({% include ['"]([^'"]*)['"] %})""") PHONE_NUMBER_PATTERN = re.compile(r"([0-9\ \+\_\-\,\.\*\#\(\)]){1,20}$") PERSON_NAME_PATTERN = re.compile(r"^[\w][\w\'\-]*( \w[\w\'\-]*)*$") WHITESPACE_PATTERN = re.compile(r"[\t\n\r]") MULTI_EMAIL_STRING_PATTERN = re.compile(r'[,\n](?=(?:[^"]|"[^"]*")*$)') def get_fullname(user=None): """get the full name (first name + last name) of the user from User""" if not user: user = frappe.session.user if not hasattr(frappe.local, "fullnames"): frappe.local.fullnames = {} if not frappe.local.fullnames.get(user): p = frappe.db.get_value("User", user, ["first_name", "last_name"], as_dict=True) if p: frappe.local.fullnames[user] = ( " ".join(filter(None, [p.get("first_name"), p.get("last_name")])) or user ) else: frappe.local.fullnames[user] = user return frappe.local.fullnames.get(user) def get_email_address(user=None): """get the email address of the user from User""" if not user: user = frappe.session.user return frappe.db.get_value("User", user, "email") def get_formatted_email(user, mail=None): """get Email Address of user formatted as: `John Doe <johndoe@example.com>`""" fullname = get_fullname(user) method = get_hook_method("get_sender_details") if method: sender_name, mail = method() # if method exists but sender_name is "" fullname = sender_name or fullname if not mail: mail = get_email_address(user) or validate_email_address(user) if not mail: return "" else: return cstr(make_header(decode_header(formataddr((fullname, mail))))) def extract_email_id(email): """fetch only the email part of the Email Address""" return cstr(parse_addr(email)[1]) def validate_phone_number_with_country_code(phone_number: str, fieldname: str) -> None: from phonenumbers import NumberParseException, is_valid_number, parse from frappe import _ if not phone_number: return valid_number = False error_message = _("Phone Number {0} set in field {1} is not valid.") error_title = _("Invalid Phone Number") try: if valid_number := is_valid_number(parse(phone_number)): return True except NumberParseException as e: if e.error_type == NumberParseException.INVALID_COUNTRY_CODE: error_message = _("Please select a country code for field {1}.") error_title = _("Country Code Required") finally: if not valid_number: frappe.throw( error_message.format(frappe.bold(phone_number), frappe.bold(fieldname)), title=error_title, exc=frappe.InvalidPhoneNumberError, ) def validate_phone_number(phone_number, throw=False): """Returns True if valid phone number""" if not phone_number: return False phone_number = phone_number.strip() match = PHONE_NUMBER_PATTERN.match(phone_number) if not match and throw: frappe.throw( frappe._("{0} is not a valid Phone Number").format(phone_number), frappe.InvalidPhoneNumberError ) return bool(match) def validate_name(name, throw=False): """Returns True if the name is valid valid names may have unicode and ascii characters, dash, quotes, numbers anything else is considered invalid Note: "Name" here is name of a person, not the primary key in Frappe doctypes. """ if not name: return False name = name.strip() match = PERSON_NAME_PATTERN.match(name) if not match and throw: frappe.throw(frappe._("{0} is not a valid Name").format(name), frappe.InvalidNameError) return bool(match) def validate_email_address(email_str, throw=False): """Validates the email string""" email = email_str = (email_str or "").strip() def _check(e): _valid = True if not e: _valid = False if "undisclosed-recipient" in e: return False elif " " in e and "<" not in e: # example: "test@example.com test2@example.com" will return "test@example.comtest2" after parseaddr!!! _valid = False else: email_id = extract_email_id(e) match = ( re.match( r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", email_id.lower(), ) if email_id else None ) if not match: _valid = False else: matched = match.group(0) if match: match = matched == email_id.lower() if not _valid: if throw: invalid_email = frappe.utils.escape_html(e) frappe.throw( frappe._("{0} is not a valid Email Address").format(invalid_email), frappe.InvalidEmailAddressError, ) return None else: return matched out = [] for e in email_str.split(","): email = _check(e.strip()) if email: out.append(email) return ", ".join(out) def split_emails(txt): email_list = [] # emails can be separated by comma or newline s = WHITESPACE_PATTERN.sub(" ", cstr(txt)) for email in MULTI_EMAIL_STRING_PATTERN.split(s): email = strip(cstr(email)) if email: email_list.append(email) return email_list def validate_url( txt: str, throw: bool = False, valid_schemes: str | Container[str] | None = None, ) -> bool: """ Checks whether `txt` has a valid URL string Parameters: throw (`bool`): throws a validationError if URL is not valid valid_schemes (`str` or `list`): if provided checks the given URL's scheme against this Returns: bool: if `txt` represents a valid URL """ url = urlparse(txt) is_valid = bool(url.netloc) # Handle scheme validation if isinstance(valid_schemes, str): is_valid = is_valid and (url.scheme == valid_schemes) elif isinstance(valid_schemes, (list, tuple, set)): is_valid = is_valid and (url.scheme in valid_schemes) if not is_valid and throw: frappe.throw(frappe._("'{0}' is not a valid URL").format(frappe.bold(txt))) return is_valid def random_string(length: int) -> str: """generate a random string""" import string from random import choice return "".join(choice(string.ascii_letters + string.digits) for i in range(length)) def has_gravatar(email: str) -> str: """Returns gravatar url if user has set an avatar at gravatar.com""" import requests if frappe.flags.in_import or frappe.flags.in_install or frappe.flags.in_test: # no gravatar if via upload # since querying gravatar for every item will be slow return "" gravatar_url = get_gravatar_url(email, "404") try: res = requests.get(gravatar_url) if res.status_code == 200: return gravatar_url else: return "" except requests.exceptions.ConnectionError: return "" def get_gravatar_url(email: str, default: Literal["mm", "404"] = "mm") -> str: hexdigest = hashlib.md5(frappe.as_unicode(email).encode("utf-8")).hexdigest() return f"https://secure.gravatar.com/avatar/{hexdigest}?d={default}&s=200" def get_gravatar(email: str) -> str: from frappe.utils.identicon import Identicon return has_gravatar(email) or Identicon(email).base64() def get_traceback(with_context=False) -> str: """ Returns the traceback of the Exception """ exc_type, exc_value, exc_tb = sys.exc_info() if not any([exc_type, exc_value, exc_tb]): return "" if with_context: trace_list = iter_exc_lines() tb = "\n".join(trace_list) else: trace_list = traceback.format_exception(exc_type, exc_value, exc_tb) tb = "".join(cstr(t) for t in trace_list) bench_path = get_bench_path() + "/" return tb.replace(bench_path, "") def log(event, details): frappe.logger(event).info(details) def dict_to_str(args: dict[str, Any], sep: str = "&") -> str: """ Converts a dictionary to URL """ t = [] for k in list(args): t.append(str(k) + "=" + quote(str(args[k] or ""))) return sep.join(t) def list_to_str(seq, sep=", "): """Convert a sequence into a string using seperator. Same as str.join, but does type conversion and strip extra spaces. """ return sep.join(map(str.strip, map(str, seq))) # Get Defaults # ============================================================================== def get_defaults(key=None): """ Get dictionary of default values from the defaults, or a value if key is passed """ return frappe.db.get_defaults(key) def set_default(key, val): """ Set / add a default value to defaults` """ return frappe.db.set_default(key, val) def remove_blanks(d: dict) -> dict: """ Returns d with empty ('' or None) values stripped. Mutates inplace. """ for k, v in tuple(d.items()): if v == "" or v == None: del d[k] return d def strip_html_tags(text): """Remove html tags from text""" return HTML_TAGS_PATTERN.sub("", text) def get_file_timestamp(fn): """ Returns timestamp of the given file """ from frappe.utils import cint try: return str(cint(os.stat(fn).st_mtime)) except OSError as e: if e.args[0] != 2: raise else: return None # to be deprecated def make_esc(esc_chars): """ Function generator for Escaping special characters """ return lambda s: "".join("\\" + c if c in esc_chars else c for c in s) # esc / unescape characters -- used for command line def esc(s, esc_chars): """ Escape special characters """ if not s: return "" for c in esc_chars: esc_str = "\\" + c s = s.replace(c, esc_str) return s def unesc(s, esc_chars): """ UnEscape special characters """ for c in esc_chars: esc_str = "\\" + c s = s.replace(esc_str, c) return s def execute_in_shell(cmd, verbose=False, low_priority=False, check_exit_code=False): # using Popen instead of os.system - as recommended by python docs import tempfile from subprocess import Popen with (tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr): kwargs = {"shell": True, "stdout": stdout, "stderr": stderr} if low_priority: kwargs["preexec_fn"] = lambda: os.nice(10) p = Popen(cmd, **kwargs) exit_code = p.wait() stdout.seek(0) out = stdout.read() stderr.seek(0) err = stderr.read() failed = check_exit_code and exit_code if verbose or failed: if err: print(err) if out: print(out) if failed: raise Exception("Command failed") return err, out def get_path(*path, **kwargs): base = kwargs.get("base") if not base: base = frappe.local.site_path return os.path.join(base, *path) def get_site_base_path(): return frappe.local.site_path def get_site_path(*path): return get_path(*path, base=get_site_base_path()) def get_files_path(*path, **kwargs): return get_site_path("private" if kwargs.get("is_private") else "public", "files", *path) def get_bench_path(): return os.path.realpath(os.path.join(os.path.dirname(frappe.__file__), "..", "..", "..")) def get_bench_id(): return frappe.get_conf().get("bench_id", get_bench_path().strip("/").replace("/", "-")) def get_site_id(site=None): return f"{site or frappe.local.site}@{get_bench_id()}" def get_backups_path(): return get_site_path("private", "backups") def get_request_site_address(full_address=False): return get_url(full_address=full_address) def get_site_url(site): return f"http://{site}:{frappe.get_conf(site).webserver_port}" def encode_dict(d, encoding="utf-8"): for key in d: if isinstance(d[key], str) and isinstance(d[key], str): d[key] = d[key].encode(encoding) return d def decode_dict(d, encoding="utf-8"): for key in d: if isinstance(d[key], str) and not isinstance(d[key], str): d[key] = d[key].decode(encoding, "ignore") return d @functools.lru_cache def get_site_name(hostname): return hostname.split(":")[0] def get_disk_usage(): """get disk usage of files folder""" files_path = get_files_path() if not os.path.exists(files_path): return 0 err, out = execute_in_shell(f"du -hsm {files_path}") return cint(out.split("\n")[-2].split("\t")[0]) def touch_file(path): with open(path, "a"): os.utime(path, None) return path def get_test_client(use_cookies=True) -> Client: """Returns an test instance of the Frappe WSGI""" from frappe.app import application return Client(application, use_cookies=use_cookies) def get_hook_method(hook_name, fallback=None): method = frappe.get_hooks().get(hook_name) if method: method = frappe.get_attr(method[0]) return method if fallback: return fallback def call_hook_method(hook, *args, **kwargs): out = None for method_name in frappe.get_hooks(hook): out = out or frappe.get_attr(method_name)(*args, **kwargs) return out def is_cli() -> bool: """Returns True if current instance is being run via a terminal""" invoked_from_terminal = False try: invoked_from_terminal = bool(os.get_terminal_size()) except Exception: invoked_from_terminal = sys.stdin and sys.stdin.isatty() return invoked_from_terminal def update_progress_bar(txt, i, l, absolute=False): if os.environ.get("CI"): if i == 0: sys.stdout.write(txt) sys.stdout.write(".") sys.stdout.flush() return if not getattr(frappe.local, "request", None) or is_cli(): # pragma: no cover lt = len(txt) try: col = 40 if os.get_terminal_size().columns > 80 else 20 except OSError: # in case function isn't being called from a terminal col = 40 if lt < 36: txt = txt + " " * (36 - lt) complete = int(float(i + 1) / l * col) completion_bar = ("=" * complete).ljust(col, " ") percent_complete = f"{str(int(float(i + 1) / l * 100))}%" status = f"{i} of {l}" if absolute else percent_complete sys.stdout.write(f"\r{txt}: [{completion_bar}] {status}") sys.stdout.flush() def get_html_format(print_path): html_format = None if os.path.exists(print_path): with open(print_path) as f: html_format = f.read() for include_directive, path in INCLUDE_DIRECTIVE_PATTERN.findall(html_format): for app_name in frappe.get_installed_apps(): include_path = frappe.get_app_path(app_name, *path.split(os.path.sep)) if os.path.exists(include_path): with open(include_path) as f: html_format = html_format.replace(include_directive, f.read()) break return html_format def is_markdown(text): if "<!-- markdown -->" in text: return True elif "<!-- html -->" in text: return False else: return not NON_MD_HTML_PATTERN.search(text) def get_sites(sites_path=None): if not sites_path: sites_path = getattr(frappe.local, "sites_path", None) or "." sites = [] for site in os.listdir(sites_path): path = os.path.join(sites_path, site) if ( os.path.isdir(path) and not os.path.islink(path) and os.path.exists(os.path.join(path, "site_config.json")) ): # is a dir and has site_config.json sites.append(site) return sorted(sites) def get_request_session(max_retries=5): import requests from requests.adapters import HTTPAdapter, Retry session = requests.Session() http_adapter = HTTPAdapter(max_retries=Retry(total=max_retries, status_forcelist=[500])) session.mount("http://", http_adapter) session.mount("https://", http_adapter) return session def markdown(text, sanitize=True, linkify=True): html = text if is_html(text) else frappe.utils.md_to_html(text) if sanitize: html = html.replace("<!-- markdown -->", "") html = sanitize_html(html, linkify=linkify) return html def sanitize_email(emails): sanitized = [] for e in split_emails(emails): if not validate_email_address(e): continue full_name, email_id = parse_addr(e) sanitized.append(formataddr((full_name, email_id))) return ", ".join(sanitized) def parse_addr(email_string): """ Return email_id and user_name based on email string Raise error if email string is not valid """ name, email = parseaddr(email_string) if check_format(email): name = get_name_from_email_string(email_string, email, name) return (name, email) else: email_list = EMAIL_STRING_PATTERN.findall(email_string) if len(email_list) > 0 and check_format(email_list[0]): # take only first email address email = email_list[0] name = get_name_from_email_string(email_string, email, name) return (name, email) return (None, email) def check_format(email_id): """ Check if email_id is valid. valid email:text@example.com String check ensures that email_id contains both '.' and '@' and index of '@' is less than '.' """ is_valid = False try: pos = email_id.rindex("@") is_valid = pos > 0 and (email_id.rindex(".") > pos) and (len(email_id) - pos > 4) except Exception: # print(e) pass return is_valid def get_name_from_email_string(email_string, email_id, name): name = email_string.replace(email_id, "") name = EMAIL_NAME_PATTERN.sub("", name).strip() if not name: name = email_id return name def get_installed_apps_info(): out = [] from frappe.utils.change_log import get_versions for app, version_details in get_versions().items(): out.append( { "app_name": app, "version": version_details.get("branch_version") or version_details.get("version"), "branch": version_details.get("branch"), } ) return out def get_site_info(): from frappe.email.queue import get_emails_sent_this_month from frappe.utils.user import get_system_managers # only get system users users = frappe.get_all( "User", filters={"user_type": "System User", "name": ("not in", frappe.STANDARD_USERS)}, fields=["name", "enabled", "last_login", "last_active", "language", "time_zone"], ) system_managers = get_system_managers(only_name=True) for u in users: # tag system managers u.is_system_manager = 1 if u.name in system_managers else 0 u.full_name = get_fullname(u.name) u.email = u.name del u["name"] system_settings = frappe.db.get_singles_dict("System Settings") space_usage = frappe._dict((frappe.local.conf.limits or {}).get("space_usage", {})) kwargs = { "fields": ["user", "creation", "full_name"], "filters": {"operation": "Login", "status": "Success"}, "limit": "10", } site_info = { "installed_apps": get_installed_apps_info(), "users": users, "country": system_settings.country, "language": system_settings.language or "english", "time_zone": system_settings.time_zone, "setup_complete": cint(system_settings.setup_complete), "scheduler_enabled": system_settings.enable_scheduler, # usage "emails_sent": get_emails_sent_this_month(), "space_used": flt((space_usage.total or 0) / 1024.0, 2), "database_size": space_usage.database_size, "backup_size": space_usage.backup_size, "files_size": space_usage.files_size, "last_logins": frappe.get_all("Activity Log", **kwargs), } # from other apps for method_name in frappe.get_hooks("get_site_info"): site_info.update(frappe.get_attr(method_name)(site_info) or {}) # dumps -> loads to prevent datatype conflicts return json.loads(frappe.as_json(site_info)) def parse_json(val): """ Parses json if string else return """ if isinstance(val, str): val = json.loads(val) if isinstance(val, dict): val = frappe._dict(val) return val def get_db_count(*args): """ Pass a doctype or a series of doctypes to get the count of docs in them Parameters: *args: Variable length argument list of doctype names whose doc count you need Returns: dict: A dict with the count values. Example: via terminal: bench --site erpnext.local execute frappe.utils.get_db_count --args "['DocType', 'Communication']" """ db_count = {} for doctype in args: db_count[doctype] = frappe.db.count(doctype) return json.loads(frappe.as_json(db_count)) def call(fn, *args, **kwargs): """ Pass a doctype or a series of doctypes to get the count of docs in them Parameters: fn: frappe function to be called Returns: based on the function you call: output of the function you call Example: via terminal: bench --site erpnext.local execute frappe.utils.call --args '''["frappe.get_all", "Activity Log"]''' --kwargs '''{"fields": ["user", "creation", "full_name"], "filters":{"Operation": "Login", "Status": "Success"}, "limit": "10"}''' """ return json.loads(frappe.as_json(frappe.call(fn, *args, **kwargs))) # Following methods are aken as-is from Python 3 codebase # since gzip.compress and gzip.decompress are not available in Python 2.7 def gzip_compress(data, compresslevel=9): """Compress data in one shot and return the compressed string. Optional argument is the compression level, in range of 0-9. """ buf = io.BytesIO() with GzipFile(fileobj=buf, mode="wb", compresslevel=compresslevel) as f: f.write(data) return buf.getvalue() def gzip_decompress(data): """Decompress a gzip compressed string in one shot. Return the decompressed string. """ with GzipFile(fileobj=io.BytesIO(data)) as f: return f.read() def get_safe_filters(filters): try: filters = json.loads(filters) if isinstance(filters, (int, float)): filters = frappe.as_unicode(filters) except (TypeError, ValueError): # filters are not passed, not json pass return filters def create_batch(iterable: Iterable, size: int) -> Generator[Iterable, None, None]: """Convert an iterable to multiple batches of constant size of batch_size Args: iterable (Iterable): Iterable object which is subscriptable size (int): Maximum size of batches to be generated Yields: Generator[List]: Batched iterable of maximum length `size` """ total_count = len(iterable) for i in range(0, total_count, size): yield iterable[i : min(i + size, total_count)] def set_request(**kwargs): from werkzeug.test import EnvironBuilder from werkzeug.wrappers import Request builder = EnvironBuilder(**kwargs) frappe.local.request = Request(builder.get_environ()) def get_html_for_route(route): from frappe.website.serve import get_response set_request(method="GET", path=route) response = get_response() html = frappe.safe_decode(response.get_data()) return html def get_file_size(path, format=False): num = os.path.getsize(path) if not format: return num suffix = "B" for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024: return f"{num:3.1f}{unit}{suffix}" num /= 1024 return "{:.1f}{}{}".format(num, "Yi", suffix) def get_build_version(): try: return str(os.path.getmtime(os.path.join(frappe.local.sites_path, ".build"))) except OSError: # .build can sometimes not exist # this is not a major problem so send fallback return frappe.utils.random_string(8) def get_assets_json(): def _get_assets(): # get merged assets.json and assets-rtl.json assets = frappe.parse_json(frappe.read_file("assets/assets.json")) if assets_rtl := frappe.read_file("assets/assets-rtl.json"): assets.update(frappe.parse_json(assets_rtl)) return assets if not hasattr(frappe.local, "assets_json"): if not frappe.conf.developer_mode: frappe.local.assets_json = frappe.cache().get_value( "assets_json", _get_assets, shared=True, ) else: frappe.local.assets_json = _get_assets() return frappe.local.assets_json def get_bench_relative_path(file_path): """Fixes paths relative to the bench root directory if exists and returns the absolute path Args: file_path (str, Path): Path of a file that exists on the file system Returns: str: Absolute path of the file_path """ if not os.path.exists(file_path): base_path = ".." elif file_path.startswith(os.sep): base_path = os.sep else: base_path = "." file_path = os.path.join(base_path, file_path) if not os.path.exists(file_path): print(f"Invalid path {file_path[3:]}") sys.exit(1) return os.path.abspath(file_path) def groupby_metric(iterable: dict[str, list], key: str): """Group records by a metric. Usecase: Lets assume we got country wise players list with the ranking given for each player(multiple players in a country can have same ranking aswell). We can group the players by ranking(can be any other metric) using this function. >>> d = { 'india': [{'id':1, 'name': 'iplayer-1', 'ranking': 1}, {'id': 2, 'ranking': 1, 'name': 'iplayer-2'}, {'id': 2, 'ranking': 2, 'name': 'iplayer-3'}], 'Aus': [{'id':1, 'name': 'aplayer-1', 'ranking': 1}, {'id': 2, 'ranking': 1, 'name': 'aplayer-2'}, {'id': 2, 'ranking': 2, 'name': 'aplayer-3'}] } >>> groupby(d, key='ranking') {1: {'Aus': [{'id': 1, 'name': 'aplayer-1', 'ranking': 1}, {'id': 2, 'name': 'aplayer-2', 'ranking': 1}], 'india': [{'id': 1, 'name': 'iplayer-1', 'ranking': 1}, {'id': 2, 'name': 'iplayer-2', 'ranking': 1}]}, 2: {'Aus': [{'id': 2, 'name': 'aplayer-3', 'ranking': 2}], 'india': [{'id': 2, 'name': 'iplayer-3', 'ranking': 2}]}} """ records = {} for category, items in iterable.items(): for item in items: records.setdefault(item[key], {}).setdefault(category, []).append(item) return records def get_table_name(table_name: str) -> str: return f"tab{table_name}" if not table_name.startswith("__") else table_name def squashify(what): if isinstance(what, Sequence) and len(what) == 1: return what[0] return what def safe_json_loads(*args): results = [] for arg in args: try: arg = json.loads(arg) except Exception: pass results.append(arg) return squashify(results) def dictify(arg): if isinstance(arg, MutableSequence): for i, a in enumerate(arg): arg[i] = dictify(a) elif isinstance(arg, MutableMapping): arg = frappe._dict(arg) return arg def add_user_info(user, user_info): if user not in user_info: info = ( frappe.db.get_value( "User", user, ["full_name", "user_image", "name", "email", "time_zone"], as_dict=True ) or frappe._dict() ) user_info[user] = frappe._dict( fullname=info.full_name or user, image=info.user_image, name=user, email=info.email, time_zone=info.time_zone, ) def is_git_url(url: str) -> bool: # modified to allow without the tailing .git from https://github.com/jonschlinkert/is-git-url.git pattern = r"(?:git|ssh|https?|\w*@[-\w.]+):(\/\/)?(.*?)(\.git)?(\/?|\#[-\d\w._]+?)$" return bool(re.match(pattern, url))
mit
513a78ad8f6e1f88e777c235f18fe6bd
24.584762
248
0.665873
2.9829
false
false
false
false
richardkiss/pycoin
tests/btc/bip32_test.py
1
12737
import unittest from pycoin.encoding.hexbytes import h2b from pycoin.symbols.btc import network as BTC from pycoin.symbols.xtn import network as XTN class Bip0032TestCase(unittest.TestCase): def test_vector_1(self): master = BTC.keys.bip32_seed(h2b("000102030405060708090a0b0c0d0e0f")) self.assertEqual( master.hwif(as_private=True), "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPG" "JxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi") self.assertEqual(master.address(), "15mKKb2eos1hWa6tisdPwwDC1a5J1y9nma") self.assertEqual(master.wif(), "L52XzL2cMkHxqxBXRyEpnPQZGUs3uKiL3R11XbAdHigRzDozKZeW") self.assertEqual( master.hwif(), "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJo" "Cu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8") m0p = master.subkey(is_hardened=True) self.assertEqual( m0p.hwif(), "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1" "VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw") self.assertEqual( m0p.hwif(as_private=True), "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6K" "CesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7") self.assertEqual(master.subkey_for_path("0p").hwif(), m0p.hwif()) pub_mp0 = master.subkey(is_hardened=True, as_private=False) self.assertEqual(pub_mp0.hwif(), m0p.hwif()) self.assertEqual(master.subkey_for_path("0p.pub").hwif(), pub_mp0.hwif()) m0p1 = m0p.subkey(i=1) self.assertEqual( m0p1.hwif(), "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj" "7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ") self.assertEqual( m0p1.hwif(as_private=True), "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYP" "xLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs") self.assertEqual(master.subkey_for_path("0p/1").hwif(), m0p1.hwif()) pub_m0p1 = m0p.subkey(i=1, as_private=False) self.assertEqual(pub_m0p1.hwif(), m0p1.hwif()) self.assertEqual(master.subkey_for_path("0p/1.pub").hwif(), pub_m0p1.hwif()) m0p1_1_2p = m0p1.subkey(i=2, is_hardened=True) self.assertEqual( m0p1_1_2p.hwif(), "xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dF" "DFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5") self.assertEqual( m0p1_1_2p.hwif(as_private=True), "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3r" "yjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM") self.assertEqual(master.subkey_for_path("0p/1/2p").hwif(), m0p1_1_2p.hwif()) pub_m0p1_1_2p = m0p1.subkey(i=2, as_private=False, is_hardened=True) self.assertEqual(pub_m0p1_1_2p.hwif(), m0p1_1_2p.hwif()) self.assertEqual(master.subkey_for_path("0p/1/2p.pub").hwif(), pub_m0p1_1_2p.hwif()) m0p1_1_2p_2 = m0p1_1_2p.subkey(i=2) self.assertEqual( m0p1_1_2p_2.hwif(), "xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6Z" "LRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV") self.assertEqual( m0p1_1_2p_2.hwif(as_private=True), "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f" "7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334") self.assertEqual(master.subkey_for_path("0p/1/2p/2").hwif(), m0p1_1_2p_2.hwif()) pub_m0p1_1_2p_2 = m0p1_1_2p.subkey(i=2, as_private=False) self.assertEqual(pub_m0p1_1_2p_2.hwif(), m0p1_1_2p_2.hwif()) self.assertEqual(master.subkey_for_path("0p/1/2p/2.pub").hwif(), pub_m0p1_1_2p_2.hwif()) m0p1_1_2p_2_1000000000 = m0p1_1_2p_2.subkey(i=1000000000) self.assertEqual( m0p1_1_2p_2_1000000000.hwif(), "xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaF" "cxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy") self.assertEqual( m0p1_1_2p_2_1000000000.hwif(as_private=True), "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4" "WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76") self.assertEqual(master.subkey_for_path("0p/1/2p/2/1000000000").hwif(), m0p1_1_2p_2_1000000000.hwif()) pub_m0p1_1_2p_2_1000000000 = m0p1_1_2p_2.subkey(i=1000000000, as_private=False) self.assertEqual(pub_m0p1_1_2p_2_1000000000.hwif(), m0p1_1_2p_2_1000000000.hwif()) self.assertEqual(master.subkey_for_path("0p/1/2p/2/1000000000.pub").hwif(), pub_m0p1_1_2p_2_1000000000.hwif()) def test_vector_2(self): master = BTC.keys.bip32_seed(h2b( "fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c99" "9693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")) self.assertEqual( master.hwif(as_private=True), "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK" "4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U") self.assertEqual( master.hwif(), "xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDM" "Sgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB") m0 = master.subkey() self.assertEqual( m0.hwif(), "xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERf" "vrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH") self.assertEqual( m0.hwif(as_private=True), "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2y" "JD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt") pub_m0 = master.subkey(as_private=False) self.assertEqual(pub_m0.hwif(), m0.hwif()) m0_2147483647p = m0.subkey(i=2147483647, is_hardened=True) self.assertEqual( m0_2147483647p.hwif(), "xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDB" "rQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a") self.assertEqual( m0_2147483647p.hwif(as_private=True), "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwC" "d6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9") pub_m0_2147483647p = m0.subkey(i=2147483647, is_hardened=True, as_private=False) self.assertEqual(pub_m0_2147483647p.hwif(), m0_2147483647p.hwif()) m0_2147483647p_1 = m0_2147483647p.subkey(i=1) self.assertEqual( m0_2147483647p_1.hwif(), "xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoN" "JxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon") self.assertEqual( m0_2147483647p_1.hwif(as_private=True), "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9" "yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef") pub_m0_2147483647p_1 = m0_2147483647p.subkey(i=1, as_private=False) self.assertEqual(pub_m0_2147483647p_1.hwif(), m0_2147483647p_1.hwif()) pub_m0_2147483647p_1 = pub_m0_2147483647p.subkey(i=1, as_private=False) self.assertEqual(pub_m0_2147483647p_1.hwif(), m0_2147483647p_1.hwif()) m0_2147483647p_1_2147483646p = m0_2147483647p_1.subkey(i=2147483646, is_hardened=True) self.assertEqual( m0_2147483647p_1_2147483646p.hwif(), "xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4ko" "xb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL") self.assertEqual( m0_2147483647p_1_2147483646p.hwif(as_private=True), "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39nj" "GVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc") pub_m0_2147483647p_1_2147483646p = m0_2147483647p_1.subkey(i=2147483646, as_private=False, is_hardened=True) self.assertEqual(pub_m0_2147483647p_1_2147483646p.hwif(), m0_2147483647p_1_2147483646p.hwif()) m0_2147483647p_1_2147483646p_2 = m0_2147483647p_1_2147483646p.subkey(i=2) self.assertEqual(m0_2147483647p_1_2147483646p_2.wif(), "L3WAYNAZPxx1fr7KCz7GN9nD5qMBnNiqEJNJMU1z9MMaannAt4aK") self.assertEqual( m0_2147483647p_1_2147483646p_2.hwif(), "xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGs" "ApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt") self.assertEqual( m0_2147483647p_1_2147483646p_2.hwif(as_private=True), "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq3" "8EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j") pub_m0_2147483647p_1_2147483646p_2 = m0_2147483647p_1_2147483646p.subkey(i=2, as_private=False) self.assertEqual(pub_m0_2147483647p_1_2147483646p_2.hwif(), m0_2147483647p_1_2147483646p_2.hwif()) pub_m0_2147483647p_1_2147483646p_2 = pub_m0_2147483647p_1_2147483646p.subkey(i=2, as_private=False) self.assertEqual(pub_m0_2147483647p_1_2147483646p_2.hwif(), m0_2147483647p_1_2147483646p_2.hwif()) self.assertEqual(master.subkey_for_path("0/2147483647p/1/2147483646p/2").hwif(), m0_2147483647p_1_2147483646p_2.hwif()) self.assertEqual(master.subkey_for_path("0/2147483647p/1/2147483646p/2.pub").hwif(), pub_m0_2147483647p_1_2147483646p_2.hwif()) def test_testnet(self): # WARNING: these values have not been verified independently. TODO: do so master = XTN.keys.bip32_seed(h2b("000102030405060708090a0b0c0d0e0f")) self.assertEqual( master.hwif(as_private=True), "tprv8ZgxMBicQKsPeDgjzdC36fs6bMjGApWDNLR9erAXMs5skhMv36j9MV5ecvfavji5kh" "qjWaWSFhN3YcCUUdiKH6isR4Pwy3U5y5egddBr16m") self.assertEqual(master.address(), "mkHGce7dctSxHgaWSSbmmrRWsZfzz7MxMk") self.assertEqual(master.wif(), "cVPXTF2TnozE1PenpP3x9huctiATZmp27T9Ue1d8nqLSExoPwfN5") def test_streams(self): m0 = BTC.keys.bip32_seed(b"foo bar baz") pm0 = m0.public_copy() self.assertEqual(m0.hwif(), pm0.hwif()) m1 = m0.subkey() pm1 = pm0.subkey() for i in range(4): m = m1.subkey(i=i) pm = pm1.subkey(i=i) self.assertEqual(m.hwif(), pm.hwif()) self.assertEqual(m.address(), pm.address()) m2 = BTC.parse.secret(m.hwif(as_private=True)) m3 = m2.public_copy() self.assertEqual(m.hwif(as_private=True), m2.hwif(as_private=True)) self.assertEqual(m.hwif(), m3.hwif()) print(m.hwif(as_private=True)) for j in range(2): k = m.subkey(i=j) k2 = BTC.parse.secret(k.hwif(as_private=True)) k3 = BTC.parse.secret(k.hwif()) k4 = k.public_copy() self.assertEqual(k.hwif(as_private=True), k2.hwif(as_private=True)) self.assertEqual(k.hwif(), k2.hwif()) self.assertEqual(k.hwif(), k3.hwif()) self.assertEqual(k.hwif(), k4.hwif()) print(" %s %s" % (k.address(), k.wif())) def test_public_subkey(self): my_prv = BTC.keys.bip32_seed(b"foo") uag = my_prv.subkey(i=0, is_hardened=True, as_private=True) self.assertEqual(None, uag.subkey(i=0, as_private=False).secret_exponent()) with self.assertRaises(ValueError) as cm: my_prv.subkey(i=-1) err = cm.exception self.assertEqual(err.args, ("i can't be negative", )) for p in ('-1', '0/-1', '0H/-1'): with self.assertRaises(ValueError) as cm: my_prv.subkey_for_path(p) err = cm.exception self.assertEqual(err.args, ("i can't be negative", )) self.assertRaises(ValueError, list, my_prv.subkeys('-1')) self.assertRaises(ValueError, list, my_prv.subkeys('-1-0')) def test_repr(self): key = XTN.keys.private(secret_exponent=273) wallet = XTN.keys.bip32_seed(bytes(key.wif().encode('utf8'))) address = wallet.address() pub_k = XTN.parse.address(address) self.assertEqual(repr(pub_k), '<myb5gZNXePNf2E2ksrjnHRFCwyuvt7oEay>') wif = wallet.wif() priv_k = XTN.parse.secret(wif) self.assertEqual(repr(priv_k), 'private_for <XTNSEC:03ad094b1dc9fdce5d3648ca359b4e210a89d049532fdd39d9ccdd8ca393ac82f4>') if __name__ == '__main__': unittest.main()
mit
9bac660ff20715e5e6c7d89d878f8549
48.560311
118
0.663971
2.281799
false
false
false
false
richardkiss/pycoin
tests/script/stackops_test.py
1
3267
import binascii import unittest from pycoin.satoshi import stackops def b2h(b): return binascii.hexlify(b).decode("utf8") class StackOpsTest(unittest.TestCase): def test_do_OP_2DROP(self): s = [1, 2, 3] stackops.do_OP_2DROP(s) self.assertEqual(s, [1]) def test_do_OP_2DUP(self): s = [1, 2] stackops.do_OP_2DUP(s) self.assertEqual(s, [1, 2, 1, 2]) def test_do_OP_3DUP(self): s = [1, 2, 3] stackops.do_OP_3DUP(s) self.assertEqual(s, [1, 2, 3, 1, 2, 3]) def test_do_OP_2OVER(self): s = [1, 2, 3, 4] stackops.do_OP_2OVER(s) self.assertEqual(s, [1, 2, 3, 4, 1, 2]) def test_do_OP_2ROT(self): s = [1, 2, 3, 4, 5, 6] stackops.do_OP_2ROT(s) self.assertEqual(s, [3, 4, 5, 6, 1, 2]) def test_do_OP_2SWAP(self): s = [1, 2, 3, 4] stackops.do_OP_2SWAP(s) self.assertEqual(s, [3, 4, 1, 2]) def test_do_OP_IFDUP(self): s = [1, 2] stackops.do_OP_IFDUP(s) self.assertEqual(s, [1, 2, 2]) s = [1, 2, 0] stackops.do_OP_IFDUP(s) self.assertEqual(s, [1, 2, 0]) def test_do_OP_DROP(self): s = [1, 2] stackops.do_OP_DROP(s) self.assertEqual(s, [1]) def test_do_OP_DUP(self): s = [1, 2] stackops.do_OP_DUP(s) self.assertEqual(s, [1, 2, 2]) def test_do_OP_NIP(self): s = [1, 2] stackops.do_OP_NIP(s) self.assertEqual(s, [2]) def test_do_OP_OVER(self): s = [1, 2] stackops.do_OP_OVER(s) self.assertEqual(s, [1, 2, 1]) def test_do_OP_ROT(self): s = [1, 2, 3] stackops.do_OP_ROT(s) self.assertEqual(s, [2, 3, 1]) def test_do_OP_SWAP(self): s = [1, 2, 3] stackops.do_OP_SWAP(s) self.assertEqual(s, [1, 3, 2]) def test_do_OP_TUCK(self): s = [1, 2, 3] stackops.do_OP_TUCK(s) self.assertEqual(s, [1, 3, 2, 3]) def test_do_OP_CAT(self): s = ["foo", "bar"] stackops.do_OP_CAT(s) self.assertEqual(s, ['foobar']) def test_do_OP_RIPEMD160(self): s = [b'foo'] stackops.do_OP_RIPEMD160(s) self.assertEqual(len(s), 1) self.assertEqual(b2h(s[0]), "42cfa211018ea492fdee45ac637b7972a0ad6873") def test_do_OP_SHA1(self): s = [b'foo'] stackops.do_OP_SHA1(s) self.assertEqual(len(s), 1) self.assertEqual(b2h(s[0]), "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33") def test_do_OP_SHA256(self): s = [b'foo'] stackops.do_OP_SHA256(s) self.assertEqual(len(s), 1) self.assertEqual(b2h(s[0]), "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae") def test_do_OP_HASH160(self): s = [b'foo'] stackops.do_OP_HASH160(s) self.assertEqual(len(s), 1) self.assertEqual(b2h(s[0]), "e1cf7c8103476b6d7fe9e4979aa10e7c531fcf42") def test_do_OP_HASH256(self): s = [b'foo'] stackops.do_OP_HASH256(s) self.assertEqual(len(s), 1) self.assertEqual(b2h(s[0]), "c7ade88fc7a21498a6a5e5c385e1f68bed822b72aa63c4a9a48a02c2466ee29e") if __name__ == "__main__": unittest.main()
mit
eca2b1e3cd7602a98489834c060c5b91
25.560976
103
0.541475
2.497706
false
true
false
false
simpeg/discretize
discretize/operators/inner_products.py
1
28521
from scipy import sparse as sp from discretize.utils import ( sub2ind, sdiag, inverse_property_tensor, TensorType, make_property_tensor, ndgrid, inverse_2x2_block_diagonal, get_subarray, inverse_3x3_block_diagonal, spzeros, sdinv, ) import numpy as np from discretize.utils.code_utils import deprecate_method import warnings class InnerProducts(object): """Class for constructing inner product matrices. ``InnerProducts`` is a mixin class for constructing inner product matrices, their inverses and their derivatives with respect to model parameters. The ``InnerProducts`` class is inherited by all ``discretize`` mesh classes. In practice, we don't create instances of the ``InnerProducts`` class in order to construct inner product matrices, their inverses or their derivatives. These quantities are instead constructed from instances of ``discretize`` meshes using the appropriate method. """ def get_face_inner_product( self, model=None, invert_model=False, invert_matrix=False, do_fast=True, **kwargs ): if "invProp" in kwargs: warnings.warn( "The invProp keyword argument has been deprecated, please use invert_model. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_model = kwargs["invProp"] if "invMat" in kwargs: warnings.warn( "The invMat keyword argument has been deprecated, please use invert_matrix. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_matrix = kwargs["invMat"] if "doFast" in kwargs: warnings.warn( "The doFast keyword argument has been deprecated, please use do_fast. " "This will be removed in discretize 1.0.0", FutureWarning, ) do_fast = kwargs["doFast"] return self._getInnerProduct( "F", model=model, invert_model=invert_model, invert_matrix=invert_matrix, do_fast=do_fast, ) def get_edge_inner_product( self, model=None, invert_model=False, invert_matrix=False, do_fast=True, **kwargs ): if "invProp" in kwargs: warnings.warn( "The invProp keyword argument has been deprecated, please use invert_model. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_model = kwargs["invProp"] if "invMat" in kwargs: warnings.warn( "The invMat keyword argument has been deprecated, please use invert_matrix. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_matrix = kwargs["invMat"] if "doFast" in kwargs: warnings.warn( "The doFast keyword argument has been deprecated, please use do_fast. " "This will be removed in discretize 1.0.0", FutureWarning, ) do_fast = kwargs["doFast"] return self._getInnerProduct( "E", model=model, invert_model=invert_model, invert_matrix=invert_matrix, do_fast=do_fast, ) def _getInnerProduct( self, projection_type, model=None, invert_model=False, invert_matrix=False, do_fast=True, **kwargs ): """get the inner product matrix Parameters ---------- str : projection_type 'F' for faces 'E' for edges numpy.ndarray : model material property (tensor properties are possible) at each cell center (nC, (1, 3, or 6)) bool : invert_model inverts the material property bool : invert_matrix inverts the matrix bool : do_fast do a faster implementation if available. Returns ------- scipy.sparse.csr_matrix M, the inner product matrix (nE, nE) """ if "invProp" in kwargs: warnings.warn( "The invProp keyword argument has been deprecated, please use invert_model. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_model = kwargs["invProp"] if "invMat" in kwargs: warnings.warn( "The invMat keyword argument has been deprecated, please use invert_matrix. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_matrix = kwargs["invMat"] if "doFast" in kwargs: warnings.warn( "The doFast keyword argument has been deprecated, please use do_fast. " "This will be removed in discretize 1.0.0", FutureWarning, ) do_fast = kwargs["doFast"] if projection_type not in ["F", "E"]: raise TypeError("projection_type must be 'F' for faces or 'E' for edges") fast = None if hasattr(self, "_fastInnerProduct") and do_fast: fast = self._fastInnerProduct( projection_type, model=model, invert_model=invert_model, invert_matrix=invert_matrix, ) if fast is not None: return fast if invert_model: model = inverse_property_tensor(self, model) tensorType = TensorType(self, model) Mu = make_property_tensor(self, model) Ps = self._getInnerProductProjectionMatrices(projection_type, tensorType) A = np.sum([P.T * Mu * P for P in Ps]) if invert_matrix and tensorType < 3: A = sdinv(A) elif invert_matrix and tensorType == 3: raise Exception("Solver needed to invert A.") return A def _getInnerProductProjectionMatrices(self, projection_type, tensorType): """ Parameters ---------- projection_type : str 'F' for faces 'E' for edges tensorType : TensorType type of the tensor: TensorType(mesh, sigma) """ if not isinstance(tensorType, TensorType): raise TypeError("tensorType must be an instance of TensorType.") if projection_type not in ["F", "E"]: raise TypeError("projection_type must be 'F' for faces or 'E' for edges") d = self.dim # We will multiply by sqrt on each side to keep symmetry V = sp.kron(sp.identity(d), sdiag(np.sqrt((2 ** (-d)) * self.cell_volumes))) nodes = ["000", "100", "010", "110", "001", "101", "011", "111"][: 2 ** d] if projection_type == "F": locs = { "000": [("fXm",), ("fXm", "fYm"), ("fXm", "fYm", "fZm")], "100": [("fXp",), ("fXp", "fYm"), ("fXp", "fYm", "fZm")], "010": [None, ("fXm", "fYp"), ("fXm", "fYp", "fZm")], "110": [None, ("fXp", "fYp"), ("fXp", "fYp", "fZm")], "001": [None, None, ("fXm", "fYm", "fZp")], "101": [None, None, ("fXp", "fYm", "fZp")], "011": [None, None, ("fXm", "fYp", "fZp")], "111": [None, None, ("fXp", "fYp", "fZp")], } proj = getattr(self, "_getFaceP" + ("x" * d))() elif projection_type == "E": locs = { "000": [("eX0",), ("eX0", "eY0"), ("eX0", "eY0", "eZ0")], "100": [("eX0",), ("eX0", "eY1"), ("eX0", "eY1", "eZ1")], "010": [None, ("eX1", "eY0"), ("eX1", "eY0", "eZ2")], "110": [None, ("eX1", "eY1"), ("eX1", "eY1", "eZ3")], "001": [None, None, ("eX2", "eY2", "eZ0")], "101": [None, None, ("eX2", "eY3", "eZ1")], "011": [None, None, ("eX3", "eY2", "eZ2")], "111": [None, None, ("eX3", "eY3", "eZ3")], } proj = getattr(self, "_getEdgeP" + ("x" * d))() return [V * proj(*locs[node][d - 1]) for node in nodes] def get_face_inner_product_deriv( self, model, do_fast=True, invert_model=False, invert_matrix=False, **kwargs ): if "invProp" in kwargs: warnings.warn( "The invProp keyword argument has been deprecated, please use invert_model. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_model = kwargs["invProp"] if "invMat" in kwargs: warnings.warn( "The invMat keyword argument has been deprecated, please use invert_matrix. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_matrix = kwargs["invMat"] if "doFast" in kwargs: warnings.warn( "The doFast keyword argument has been deprecated, please use do_fast. " "This will be removed in discretize 1.0.0", FutureWarning, ) do_fast = kwargs["doFast"] return self._getInnerProductDeriv( model, "F", do_fast=do_fast, invert_model=invert_model, invert_matrix=invert_matrix, ) def get_edge_inner_product_deriv( self, model, do_fast=True, invert_model=False, invert_matrix=False, **kwargs ): if "invProp" in kwargs: warnings.warn( "The invProp keyword argument has been deprecated, please use invert_model. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_model = kwargs["invProp"] if "invMat" in kwargs: warnings.warn( "The invMat keyword argument has been deprecated, please use invert_matrix. " "This will be removed in discretize 1.0.0", FutureWarning, ) invert_matrix = kwargs["invMat"] if "doFast" in kwargs: warnings.warn( "The doFast keyword argument has been deprecated, please use do_fast. " "This will be removed in discretize 1.0.0", FutureWarning, ) do_fast = kwargs["doFast"] return self._getInnerProductDeriv( model, "E", do_fast=do_fast, invert_model=invert_model, invert_matrix=invert_matrix, ) def _getInnerProductDeriv( self, model, projection_type, do_fast=True, invert_model=False, invert_matrix=False, ): """ Parameters ---------- model : numpy.ndarray material property (tensor properties are possible) at each cell center (nC, (1, 3, or 6)) projection_type : str 'F' for faces 'E' for edges do_fast : bool do a faster implementation if available. invert_model : bool inverts the material property invert_matrix : bool inverts the matrix Returns ------- scipy.sparse.csr_matrix dMdm, the derivative of the inner product matrix (nE, nC*nA) """ fast = None if hasattr(self, "_fastInnerProductDeriv") and do_fast: fast = self._fastInnerProductDeriv( projection_type, model, invert_model=invert_model, invert_matrix=invert_matrix, ) if fast is not None: return fast if invert_model or invert_matrix: raise NotImplementedError( "inverting the property or the matrix is not yet implemented for this mesh/tensorType. You should write it!" ) tensorType = TensorType(self, model) P = self._getInnerProductProjectionMatrices( projection_type, tensorType=tensorType ) def innerProductDeriv(v): return self._getInnerProductDerivFunction(tensorType, P, projection_type, v) return innerProductDeriv def _getInnerProductDerivFunction(self, tensorType, P, projection_type, v): """ Parameters ---------- model : numpy.ndarray material property (tensor properties are possible) at each cell center (nC, (1, 3, or 6)) v : numpy.ndarray vector to multiply (required in the general implementation) P : list list of projection matrices projection_type : str 'F' for faces 'E' for edges Returns ------- scipy.sparse.csr_matrix dMdm, the derivative of the inner product matrix (n, nC*nA) """ if projection_type not in ["F", "E"]: raise TypeError("projection_type must be 'F' for faces or 'E' for edges") n = getattr(self, "n" + projection_type) if tensorType == -1: return None if v is None: raise Exception("v must be supplied for this implementation.") d = self.dim Z = spzeros(self.nC, self.nC) if tensorType == 0: dMdm = spzeros(n, 1) for i, p in enumerate(P): dMdm = dMdm + sp.csr_matrix( (p.T * (p * v), (range(n), np.zeros(n))), shape=(n, 1) ) if d == 1: if tensorType == 1: dMdm = spzeros(n, self.nC) for i, p in enumerate(P): dMdm = dMdm + p.T * sdiag(p * v) elif d == 2: if tensorType == 1: dMdm = spzeros(n, self.nC) for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC :] dMdm = dMdm + p.T * sp.vstack((sdiag(y1), sdiag(y2))) elif tensorType == 2: dMdms = [spzeros(n, self.nC) for _ in range(2)] for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC :] dMdms[0] = dMdms[0] + p.T * sp.vstack((sdiag(y1), Z)) dMdms[1] = dMdms[1] + p.T * sp.vstack((Z, sdiag(y2))) dMdm = sp.hstack(dMdms) elif tensorType == 3: dMdms = [spzeros(n, self.nC) for _ in range(3)] for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC :] dMdms[0] = dMdms[0] + p.T * sp.vstack((sdiag(y1), Z)) dMdms[1] = dMdms[1] + p.T * sp.vstack((Z, sdiag(y2))) dMdms[2] = dMdms[2] + p.T * sp.vstack((sdiag(y2), sdiag(y1))) dMdm = sp.hstack(dMdms) elif d == 3: if tensorType == 1: dMdm = spzeros(n, self.nC) for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC : self.nC * 2] y3 = Y[self.nC * 2 :] dMdm = dMdm + p.T * sp.vstack((sdiag(y1), sdiag(y2), sdiag(y3))) elif tensorType == 2: dMdms = [spzeros(n, self.nC) for _ in range(3)] for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC : self.nC * 2] y3 = Y[self.nC * 2 :] dMdms[0] = dMdms[0] + p.T * sp.vstack((sdiag(y1), Z, Z)) dMdms[1] = dMdms[1] + p.T * sp.vstack((Z, sdiag(y2), Z)) dMdms[2] = dMdms[2] + p.T * sp.vstack((Z, Z, sdiag(y3))) dMdm = sp.hstack(dMdms) elif tensorType == 3: dMdms = [spzeros(n, self.nC) for _ in range(6)] for i, p in enumerate(P): Y = p * v y1 = Y[: self.nC] y2 = Y[self.nC : self.nC * 2] y3 = Y[self.nC * 2 :] dMdms[0] = dMdms[0] + p.T * sp.vstack((sdiag(y1), Z, Z)) dMdms[1] = dMdms[1] + p.T * sp.vstack((Z, sdiag(y2), Z)) dMdms[2] = dMdms[2] + p.T * sp.vstack((Z, Z, sdiag(y3))) dMdms[3] = dMdms[3] + p.T * sp.vstack((sdiag(y2), sdiag(y1), Z)) dMdms[4] = dMdms[4] + p.T * sp.vstack((sdiag(y3), Z, sdiag(y1))) dMdms[5] = dMdms[5] + p.T * sp.vstack((Z, sdiag(y3), sdiag(y2))) dMdm = sp.hstack(dMdms) return dMdm # ------------------------ Geometries ------------------------------ # # # node(i,j,k+1) ------ edge2(i,j,k+1) ----- node(i,j+1,k+1) # / / # / / | # edge3(i,j,k) face1(i,j,k) edge3(i,j+1,k) # / / | # / / | # node(i,j,k) ------ edge2(i,j,k) ----- node(i,j+1,k) # | | | # | | node(i+1,j+1,k+1) # | | / # edge1(i,j,k) face3(i,j,k) edge1(i,j+1,k) # | | / # | | / # | |/ # node(i+1,j,k) ------ edge2(i+1,j,k) ----- node(i+1,j+1,k) def _getFacePx(M): """Returns a function for creating projection matrices""" ii = np.arange(M.shape_cells[0]) def Px(xFace): """ xFace is 'fXp' or 'fXm' """ posFx = 0 if xFace == "fXm" else 1 IND = ii + posFx PX = sp.csr_matrix((np.ones(M.nC), (range(M.nC), IND)), shape=(M.nC, M.nF)) return PX return Px def _getFacePxx(M): """returns a function for creating projection matrices Mats takes you from faces a subset of all faces on only the faces that you ask for. These are centered around a single nodes. For example, if this was your entire mesh: f3(Yp) 2_______________3 | | | | | | f0(Xm) | x | f1(Xp) | | | | |_______________| 0 1 f2(Ym) Pxx('fXm','fYm') = | 1, 0, 0, 0 | | 0, 0, 1, 0 | Pxx('fXp','fYm') = | 0, 1, 0, 0 | | 0, 0, 1, 0 | """ i, j = np.arange(M.shape_cells[0]), np.arange(M.shape_cells[1]) iijj = ndgrid(i, j) ii, jj = iijj[:, 0], iijj[:, 1] if M._meshType == "Curv": fN1 = M.reshape(M.face_normals, "F", "Fx", "M") fN2 = M.reshape(M.face_normals, "F", "Fy", "M") def Pxx(xFace, yFace): """ xFace is 'fXp' or 'fXm' yFace is 'fYp' or 'fYm' """ # no | node | f1 | f2 # 00 | i ,j | i , j | i, j # 10 | i+1,j | i+1, j | i, j # 01 | i ,j+1 | i , j | i, j+1 # 11 | i+1,j+1 | i+1, j | i, j+1 posFx = 0 if xFace == "fXm" else 1 posFy = 0 if yFace == "fYm" else 1 ind1 = sub2ind(M.vnFx, np.c_[ii + posFx, jj]) ind2 = sub2ind(M.vnFy, np.c_[ii, jj + posFy]) + M.nFx IND = np.r_[ind1, ind2].flatten() PXX = sp.csr_matrix( (np.ones(2 * M.nC), (range(2 * M.nC), IND)), shape=(2 * M.nC, M.nF) ) if M._meshType == "Curv": I2x2 = inverse_2x2_block_diagonal( get_subarray(fN1[0], [i + posFx, j]), get_subarray(fN1[1], [i + posFx, j]), get_subarray(fN2[0], [i, j + posFy]), get_subarray(fN2[1], [i, j + posFy]), ) PXX = I2x2 * PXX return PXX return Pxx def _getFacePxxx(M): """returns a function for creating projection matrices Mats takes you from faces a subset of all faces on only the faces that you ask for. These are centered around a single nodes. """ i, j, k = ( np.arange(M.shape_cells[0]), np.arange(M.shape_cells[1]), np.arange(M.shape_cells[2]), ) iijjkk = ndgrid(i, j, k) ii, jj, kk = iijjkk[:, 0], iijjkk[:, 1], iijjkk[:, 2] if M._meshType == "Curv": fN1 = M.reshape(M.face_normals, "F", "Fx", "M") fN2 = M.reshape(M.face_normals, "F", "Fy", "M") fN3 = M.reshape(M.face_normals, "F", "Fz", "M") def Pxxx(xFace, yFace, zFace): """ xFace is 'fXp' or 'fXm' yFace is 'fYp' or 'fYm' zFace is 'fZp' or 'fZm' """ # no | node | f1 | f2 | f3 # 000 | i ,j ,k | i , j, k | i, j , k | i, j, k # 100 | i+1,j ,k | i+1, j, k | i, j , k | i, j, k # 010 | i ,j+1,k | i , j, k | i, j+1, k | i, j, k # 110 | i+1,j+1,k | i+1, j, k | i, j+1, k | i, j, k # 001 | i ,j ,k+1 | i , j, k | i, j , k | i, j, k+1 # 101 | i+1,j ,k+1 | i+1, j, k | i, j , k | i, j, k+1 # 011 | i ,j+1,k+1 | i , j, k | i, j+1, k | i, j, k+1 # 111 | i+1,j+1,k+1 | i+1, j, k | i, j+1, k | i, j, k+1 posX = 0 if xFace == "fXm" else 1 posY = 0 if yFace == "fYm" else 1 posZ = 0 if zFace == "fZm" else 1 ind1 = sub2ind(M.vnFx, np.c_[ii + posX, jj, kk]) ind2 = sub2ind(M.vnFy, np.c_[ii, jj + posY, kk]) + M.nFx ind3 = sub2ind(M.vnFz, np.c_[ii, jj, kk + posZ]) + M.nFx + M.nFy IND = np.r_[ind1, ind2, ind3].flatten() PXXX = sp.coo_matrix( (np.ones(3 * M.nC), (range(3 * M.nC), IND)), shape=(3 * M.nC, M.nF) ).tocsr() if M._meshType == "Curv": I3x3 = inverse_3x3_block_diagonal( get_subarray(fN1[0], [i + posX, j, k]), get_subarray(fN1[1], [i + posX, j, k]), get_subarray(fN1[2], [i + posX, j, k]), get_subarray(fN2[0], [i, j + posY, k]), get_subarray(fN2[1], [i, j + posY, k]), get_subarray(fN2[2], [i, j + posY, k]), get_subarray(fN3[0], [i, j, k + posZ]), get_subarray(fN3[1], [i, j, k + posZ]), get_subarray(fN3[2], [i, j, k + posZ]), ) PXXX = I3x3 * PXXX return PXXX return Pxxx def _getEdgePx(M): """Returns a function for creating projection matrices""" def Px(xEdge): if xEdge != "eX0": raise TypeError("xEdge = {0!s}, not eX0".format(xEdge)) return sp.identity(M.nC) return Px def _getEdgePxx(M): i, j = np.arange(M.shape_cells[0]), np.arange(M.shape_cells[1]) iijj = ndgrid(i, j) ii, jj = iijj[:, 0], iijj[:, 1] if M._meshType == "Curv": eT1 = M.reshape(M.edge_tangents, "E", "Ex", "M") eT2 = M.reshape(M.edge_tangents, "E", "Ey", "M") def Pxx(xEdge, yEdge): """ no | node | e1 | e2 00 | i ,j | i ,j | i ,j 10 | i+1,j | i ,j | i+1,j 01 | i ,j+1 | i ,j+1 | i ,j 11 | i+1,j+1 | i ,j+1 | i+1,j """ posX = 0 if xEdge == "eX0" else 1 posY = 0 if yEdge == "eY0" else 1 ind1 = sub2ind(M.vnEx, np.c_[ii, jj + posX]) ind2 = sub2ind(M.vnEy, np.c_[ii + posY, jj]) + M.nEx IND = np.r_[ind1, ind2].flatten() PXX = sp.coo_matrix( (np.ones(2 * M.nC), (range(2 * M.nC), IND)), shape=(2 * M.nC, M.nE) ).tocsr() if M._meshType == "Curv": I2x2 = inverse_2x2_block_diagonal( get_subarray(eT1[0], [i, j + posX]), get_subarray(eT1[1], [i, j + posX]), get_subarray(eT2[0], [i + posY, j]), get_subarray(eT2[1], [i + posY, j]), ) PXX = I2x2 * PXX return PXX return Pxx def _getEdgePxxx(M): i, j, k = ( np.arange(M.shape_cells[0]), np.arange(M.shape_cells[1]), np.arange(M.shape_cells[2]), ) iijjkk = ndgrid(i, j, k) ii, jj, kk = iijjkk[:, 0], iijjkk[:, 1], iijjkk[:, 2] if M._meshType == "Curv": eT1 = M.reshape(M.edge_tangents, "E", "Ex", "M") eT2 = M.reshape(M.edge_tangents, "E", "Ey", "M") eT3 = M.reshape(M.edge_tangents, "E", "Ez", "M") def Pxxx(xEdge, yEdge, zEdge): """ no | node | e1 | e2 | e3 000 | i ,j ,k | i ,j ,k | i ,j ,k | i ,j ,k 100 | i+1,j ,k | i ,j ,k | i+1,j ,k | i+1,j ,k 010 | i ,j+1,k | i ,j+1,k | i ,j ,k | i ,j+1,k 110 | i+1,j+1,k | i ,j+1,k | i+1,j ,k | i+1,j+1,k 001 | i ,j ,k+1 | i ,j ,k+1 | i ,j ,k+1 | i ,j ,k 101 | i+1,j ,k+1 | i ,j ,k+1 | i+1,j ,k+1 | i+1,j ,k 011 | i ,j+1,k+1 | i ,j+1,k+1 | i ,j ,k+1 | i ,j+1,k 111 | i+1,j+1,k+1 | i ,j+1,k+1 | i+1,j ,k+1 | i+1,j+1,k """ posX = ( [0, 0] if xEdge == "eX0" else [1, 0] if xEdge == "eX1" else [0, 1] if xEdge == "eX2" else [1, 1] ) posY = ( [0, 0] if yEdge == "eY0" else [1, 0] if yEdge == "eY1" else [0, 1] if yEdge == "eY2" else [1, 1] ) posZ = ( [0, 0] if zEdge == "eZ0" else [1, 0] if zEdge == "eZ1" else [0, 1] if zEdge == "eZ2" else [1, 1] ) ind1 = sub2ind(M.vnEx, np.c_[ii, jj + posX[0], kk + posX[1]]) ind2 = sub2ind(M.vnEy, np.c_[ii + posY[0], jj, kk + posY[1]]) + M.nEx ind3 = ( sub2ind(M.vnEz, np.c_[ii + posZ[0], jj + posZ[1], kk]) + M.nEx + M.nEy ) IND = np.r_[ind1, ind2, ind3].flatten() PXXX = sp.coo_matrix( (np.ones(3 * M.nC), (range(3 * M.nC), IND)), shape=(3 * M.nC, M.nE) ).tocsr() if M._meshType == "Curv": I3x3 = inverse_3x3_block_diagonal( get_subarray(eT1[0], [i, j + posX[0], k + posX[1]]), get_subarray(eT1[1], [i, j + posX[0], k + posX[1]]), get_subarray(eT1[2], [i, j + posX[0], k + posX[1]]), get_subarray(eT2[0], [i + posY[0], j, k + posY[1]]), get_subarray(eT2[1], [i + posY[0], j, k + posY[1]]), get_subarray(eT2[2], [i + posY[0], j, k + posY[1]]), get_subarray(eT3[0], [i + posZ[0], j + posZ[1], k]), get_subarray(eT3[1], [i + posZ[0], j + posZ[1], k]), get_subarray(eT3[2], [i + posZ[0], j + posZ[1], k]), ) PXXX = I3x3 * PXXX return PXXX return Pxxx
mit
225a837e29797a5eded827843246abf8
34.830402
124
0.436205
3.316395
false
false
false
false
richardkiss/pycoin
pycoin/services/blockchain_info.py
1
2769
import io import json import warnings from .agent import request, urlencode, urlopen from pycoin.coins.bitcoin.Tx import Tx from pycoin.encoding.hexbytes import b2h, h2b, b2h_rev class BlockchainInfoProvider(object): def __init__(self, netcode): if netcode == "BTC": self.api_domain = "https://blockchain.info" elif netcode == "XTN": self.api_domain = "https://testnet.blockchain.info" elif netcode == "BCH": self.api_domain = "http://api.blockchain.info/bch" else: raise ValueError("unsupported netcode %s" % netcode) def tx_for_tx_hash(self, tx_hash): "Get a Tx by its hash." URL = self.api_domain + ("/rawtx/%s?format=hex" % b2h_rev(tx_hash)) tx = Tx.from_hex(urlopen(URL).read().decode("utf8")) return tx def payments_for_address(self, address): "return an array of (TX ids, net_payment)" URL = self.api_domain + ("/address/%s?format=json" % address) d = urlopen(URL).read() json_response = json.loads(d.decode("utf8")) response = [] for tx in json_response.get("txs", []): total_out = 0 for tx_out in tx.get("out", []): if tx_out.get("addr") == address: total_out += tx_out.get("value", 0) if total_out > 0: response.append((tx.get("hash"), total_out)) return response def spendables_for_address(self, address): """ Return a list of Spendable objects for the given bitcoin address. """ URL = self.api_domain + "/unspent?active=%s" % address r = json.loads(urlopen(URL).read().decode("utf8")) spendables = [] for u in r["unspent_outputs"]: coin_value = u["value"] script = h2b(u["script"]) previous_hash = h2b(u["tx_hash"]) previous_index = u["tx_output_n"] spendables.append(Tx.Spendable(coin_value, script, previous_hash, previous_index)) return spendables def broadcast_tx(self, tx): s = io.BytesIO() tx.stream(s) tx_as_hex = b2h(s.getvalue()) data = urlencode(dict(tx=tx_as_hex)).encode("utf8") URL = self.api_domain + "/pushtx" try: d = urlopen(URL, data=data).read() return d except request.HTTPError as ex: try: d = ex.read() ex.message = d except Exception: pass raise ex def send_tx(self, tx): warnings.warn("use BlockchainInfoProvider.broadcast_tx instead of send_tx", category=DeprecationWarning) return BlockchainInfoProvider().broadcast_tx(tx)
mit
70f457ab021204d7f41bcc676e09f026
33.6125
94
0.555796
3.653034
false
false
false
false
richardkiss/pycoin
pycoin/ecdsa/intstream.py
1
1243
from pycoin.intbytes import iterbytes, byte2int def _to_bytes(v, length, byteorder="big"): """This is the same functionality as ``int.to_bytes`` in python 3""" return v.to_bytes(length, byteorder=byteorder) def _from_bytes(bytes, byteorder="big", signed=False): """This is the same functionality as ``int.from_bytes`` in python 3""" return int.from_bytes(bytes, byteorder=byteorder, signed=signed) if hasattr(int, "to_bytes"): to_bytes = _to_bytes from_bytes = _from_bytes else: def to_bytes(v, length, byteorder="big"): """This is the same functionality as ``int.to_bytes`` in python 3""" ba = bytearray() for i in range(length): mod = v & 0xff v >>= 8 ba.append(mod) if byteorder == "big": ba.reverse() return bytes(ba) def from_bytes(bytes, byteorder="big", signed=False): """This is the same functionality as ``int.from_bytes`` in python 3""" if byteorder != "big": bytes = reversed(bytes) v = 0 for c in iterbytes(bytes): v <<= 8 v += c if signed and byte2int(bytes) & 0x80: v = v - (1 << (8*len(bytes))) return v
mit
49e0ea47ed45ad02cd10ce0e4bbc84c6
30.075
78
0.568785
3.666667
false
false
false
false
frappe/frappe
frappe/app.py
1
10706
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import logging import os from werkzeug.exceptions import HTTPException, NotFound from werkzeug.local import LocalManager from werkzeug.middleware.profiler import ProfilerMiddleware from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.wrappers import Request, Response import frappe import frappe.api import frappe.handler import frappe.monitor import frappe.rate_limiter import frappe.recorder import frappe.utils.response from frappe import _ from frappe.auth import SAFE_HTTP_METHODS, UNSAFE_HTTP_METHODS, HTTPRequest from frappe.core.doctype.comment.comment import update_comments_in_parent_after_request from frappe.middlewares import StaticDataMiddleware from frappe.utils import cint, get_site_name, sanitize_html from frappe.utils.error import make_error_snapshot from frappe.website.serve import get_response local_manager = LocalManager(frappe.local) _site = None _sites_path = os.environ.get("SITES_PATH", ".") @local_manager.middleware @Request.application def application(request: Request): response = None try: rollback = True init_request(request) frappe.recorder.record() frappe.monitor.start() frappe.rate_limiter.apply() frappe.api.validate_auth() if request.method == "OPTIONS": response = Response() elif frappe.form_dict.cmd: response = frappe.handler.handle() elif request.path.startswith("/api/"): response = frappe.api.handle() elif request.path.startswith("/backups"): response = frappe.utils.response.download_backup(request.path) elif request.path.startswith("/private/files/"): response = frappe.utils.response.download_private_file(request.path) elif request.method in ("GET", "HEAD", "POST"): response = get_response() else: raise NotFound except HTTPException as e: return e except Exception as e: response = handle_exception(e) else: rollback = after_request(rollback) finally: if request.method in ("POST", "PUT") and frappe.db and rollback: frappe.db.rollback() frappe.rate_limiter.update() frappe.monitor.stop(response) frappe.recorder.dump() log_request(request, response) process_response(response) if frappe.db: frappe.db.close() return response def init_request(request): frappe.local.request = request frappe.local.is_ajax = frappe.get_request_header("X-Requested-With") == "XMLHttpRequest" site = _site or request.headers.get("X-Frappe-Site-Name") or get_site_name(request.host) frappe.init(site=site, sites_path=_sites_path) if not (frappe.local.conf and frappe.local.conf.db_name): # site does not exist raise NotFound if frappe.local.conf.maintenance_mode: frappe.connect() if frappe.local.conf.allow_reads_during_maintenance: setup_read_only_mode() else: raise frappe.SessionStopped("Session Stopped") else: frappe.connect(set_admin_as_user=False) request.max_content_length = cint(frappe.local.conf.get("max_file_size")) or 10 * 1024 * 1024 make_form_dict(request) if request.method != "OPTIONS": frappe.local.http_request = HTTPRequest() def setup_read_only_mode(): """During maintenance_mode reads to DB can still be performed to reduce downtime. This function sets up read only mode - Setting global flag so other pages, desk and database can know that we are in read only mode. - Setup read only database access either by: - Connecting to read replica if one exists - Or setting up read only SQL transactions. """ frappe.flags.read_only = True # If replica is available then just connect replica, else setup read only transaction. if frappe.conf.read_from_replica: frappe.connect_replica() else: frappe.db.begin(read_only=True) def log_request(request, response): if hasattr(frappe.local, "conf") and frappe.local.conf.enable_frappe_logger: frappe.logger("frappe.web", allow_site=frappe.local.site).info( { "site": get_site_name(request.host), "remote_addr": getattr(request, "remote_addr", "NOTFOUND"), "base_url": getattr(request, "base_url", "NOTFOUND"), "full_path": getattr(request, "full_path", "NOTFOUND"), "method": getattr(request, "method", "NOTFOUND"), "scheme": getattr(request, "scheme", "NOTFOUND"), "http_status_code": getattr(response, "status_code", "NOTFOUND"), } ) def process_response(response): if not response: return # set cookies if hasattr(frappe.local, "cookie_manager"): frappe.local.cookie_manager.flush_cookies(response=response) # rate limiter headers if hasattr(frappe.local, "rate_limiter"): response.headers.extend(frappe.local.rate_limiter.headers()) # CORS headers if hasattr(frappe.local, "conf"): set_cors_headers(response) def set_cors_headers(response): if not ( (allowed_origins := frappe.conf.allow_cors) and (request := frappe.local.request) and (origin := request.headers.get("Origin")) ): return if allowed_origins != "*": if not isinstance(allowed_origins, list): allowed_origins = [allowed_origins] if origin not in allowed_origins: return cors_headers = { "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Origin": origin, "Vary": "Origin", } # only required for preflight requests if request.method == "OPTIONS": cors_headers["Access-Control-Allow-Methods"] = request.headers.get( "Access-Control-Request-Method" ) if allowed_headers := request.headers.get("Access-Control-Request-Headers"): cors_headers["Access-Control-Allow-Headers"] = allowed_headers # allow browsers to cache preflight requests for upto a day if not frappe.conf.developer_mode: cors_headers["Access-Control-Max-Age"] = "86400" response.headers.extend(cors_headers) def make_form_dict(request): import json request_data = request.get_data(as_text=True) if "application/json" in (request.content_type or "") and request_data: args = json.loads(request_data) else: args = {} args.update(request.args or {}) args.update(request.form or {}) if not isinstance(args, dict): frappe.throw(_("Invalid request arguments")) frappe.local.form_dict = frappe._dict(args) if "_" in frappe.local.form_dict: # _ is passed by $.ajax so that the request is not cached by the browser. So, remove _ from form_dict frappe.local.form_dict.pop("_") def handle_exception(e): response = None http_status_code = getattr(e, "http_status_code", 500) return_as_message = False accept_header = frappe.get_request_header("Accept") or "" respond_as_json = ( frappe.get_request_header("Accept") and (frappe.local.is_ajax or "application/json" in accept_header) or (frappe.local.request.path.startswith("/api/") and not accept_header.startswith("text")) ) if not frappe.session.user: # If session creation fails then user won't be unset. This causes a lot of code that # assumes presence of this to fail. Session creation fails => guest or expired login # usually. frappe.session.user = "Guest" if respond_as_json: # handle ajax responses first # if the request is ajax, send back the trace or error message response = frappe.utils.response.report_error(http_status_code) elif isinstance(e, frappe.SessionStopped): response = frappe.utils.response.handle_session_stopped() elif ( http_status_code == 500 and (frappe.db and isinstance(e, frappe.db.InternalError)) and (frappe.db and (frappe.db.is_deadlocked(e) or frappe.db.is_timedout(e))) ): http_status_code = 508 elif http_status_code == 401: frappe.respond_as_web_page( _("Session Expired"), _("Your session has expired, please login again to continue."), http_status_code=http_status_code, indicator_color="red", ) return_as_message = True elif http_status_code == 403: frappe.respond_as_web_page( _("Not Permitted"), _("You do not have enough permissions to complete the action"), http_status_code=http_status_code, indicator_color="red", ) return_as_message = True elif http_status_code == 404: frappe.respond_as_web_page( _("Not Found"), _("The resource you are looking for is not available"), http_status_code=http_status_code, indicator_color="red", ) return_as_message = True elif http_status_code == 429: response = frappe.rate_limiter.respond() else: traceback = "<pre>" + sanitize_html(frappe.get_traceback()) + "</pre>" # disable traceback in production if flag is set if frappe.local.flags.disable_traceback and not frappe.local.dev_server: traceback = "" frappe.respond_as_web_page( "Server Error", traceback, http_status_code=http_status_code, indicator_color="red", width=640 ) return_as_message = True if e.__class__ == frappe.AuthenticationError: if hasattr(frappe.local, "login_manager"): frappe.local.login_manager.clear_cookies() if http_status_code >= 500: make_error_snapshot(e) if return_as_message: response = get_response("message", http_status_code=http_status_code) if frappe.conf.get("developer_mode") and not respond_as_json: # don't fail silently for non-json response errors print(frappe.get_traceback()) return response def after_request(rollback): # if HTTP method would change server state, commit if necessary if frappe.db and ( frappe.local.flags.commit or frappe.local.request.method in UNSAFE_HTTP_METHODS ): if frappe.db.transaction_writes: frappe.db.commit() rollback = False # update session if getattr(frappe.local, "session_obj", None): updated_in_db = frappe.local.session_obj.update() if updated_in_db: frappe.db.commit() rollback = False update_comments_in_parent_after_request() return rollback def serve( port=8000, profile=False, no_reload=False, no_threading=False, site=None, sites_path="." ): global application, _site, _sites_path _site = site _sites_path = sites_path from werkzeug.serving import run_simple if profile or os.environ.get("USE_PROFILER"): application = ProfilerMiddleware(application, sort_by=("cumtime", "calls")) if not os.environ.get("NO_STATICS"): application = SharedDataMiddleware( application, {"/assets": str(os.path.join(sites_path, "assets"))} ) application = StaticDataMiddleware(application, {"/files": str(os.path.abspath(sites_path))}) application.debug = True application.config = {"SERVER_NAME": "localhost:8000"} log = logging.getLogger("werkzeug") log.propagate = False in_test_env = os.environ.get("CI") if in_test_env: log.setLevel(logging.ERROR) run_simple( "0.0.0.0", int(port), application, use_reloader=False if in_test_env else not no_reload, use_debugger=not in_test_env, use_evalex=not in_test_env, threaded=not no_threading, )
mit
0e583cb568f992dfbd3eec2bbdfcfc9c
27.248021
103
0.723052
3.26502
false
false
false
false
frappe/frappe
frappe/automation/doctype/milestone_tracker/test_milestone_tracker.py
2
1371
# Copyright (c) 2019, Frappe Technologies and Contributors # License: MIT. See LICENSE import frappe import frappe.cache_manager from frappe.tests.utils import FrappeTestCase class TestMilestoneTracker(FrappeTestCase): def test_milestone(self): frappe.db.delete("Milestone Tracker") frappe.cache().delete_key("milestone_tracker_map") milestone_tracker = frappe.get_doc( dict(doctype="Milestone Tracker", document_type="ToDo", track_field="status") ).insert() todo = frappe.get_doc(dict(doctype="ToDo", description="test milestone", status="Open")).insert() milestones = frappe.get_all( "Milestone", fields=["track_field", "value", "milestone_tracker"], filters=dict(reference_type=todo.doctype, reference_name=todo.name), ) self.assertEqual(len(milestones), 1) self.assertEqual(milestones[0].track_field, "status") self.assertEqual(milestones[0].value, "Open") todo.status = "Closed" todo.save() milestones = frappe.get_all( "Milestone", fields=["track_field", "value", "milestone_tracker"], filters=dict(reference_type=todo.doctype, reference_name=todo.name), order_by="modified desc", ) self.assertEqual(len(milestones), 2) self.assertEqual(milestones[0].track_field, "status") self.assertEqual(milestones[0].value, "Closed") # cleanup frappe.db.delete("Milestone") milestone_tracker.delete()
mit
c3b1e408576962b2f8c0b184dd0649ae
28.804348
99
0.723559
3.272076
false
true
false
false
sqlalchemy/mako
doc/build/conf.py
2
9571
# # Mako documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("../..")) sys.path.insert(0, os.path.abspath(".")) if True: import mako # noqa # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. # extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', # 'sphinx.ext.doctest', 'builder.builders'] extensions = [ "sphinx.ext.autodoc", "changelog", "sphinx_paramlinks", "zzzeeksphinx", ] changelog_render_ticket = "https://github.com/sqlalchemy/mako/issues/%s" changelog_render_pullreq = { "default": "https://github.com/sqlalchemy/mako/pull/%s", "github": "https://github.com/sqlalchemy/mako/pull/%s", } # tags to sort on inside of sections changelog_sections = [ "changed", "feature", "bug", "usecase", "moved", "removed", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["templates"] nitpicky = True site_base = os.environ.get("RTD_SITE_BASE", "http://www.makotemplates.org") site_adapter_template = "docs_adapter.mako" site_adapter_py = "docs_adapter.py" # The suffix of source filenames. source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "Mako" copyright = "the Mako authors and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = mako.__version__ # The full version, including alpha/beta/rc tags. release = "1.2.4" release_date = "Tue Nov 15 2022" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["build"] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "zsmako" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = "default.css" # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = "%s %s Documentation" % (project, release) # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%m/%d/%Y %H:%M:%S" # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. html_domain_indices = False # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. # html_copy_source = True html_copy_source = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Makodoc" # autoclass_content = 'both' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). # latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). # latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ( "index", "mako_%s.tex" % release.replace(".", "_"), "Mako Documentation", "Mike Bayer", "manual", ) ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Additional stuff for the LaTeX preamble. # sets TOC depth to 2. latex_preamble = r"\setcounter{tocdepth}{3}" # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # latex_elements = { # 'papersize': 'letterpaper', # 'pointsize': '10pt', # } # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [("index", "mako", "Mako Documentation", ["Mako authors"], 1)] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = "Mako" epub_author = "Mako authors" epub_publisher = "Mako authors" epub_copyright = "Mako authors" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True
mit
cd7239d22d53994078092d70a6a34895
29.77492
80
0.693867
3.664242
false
true
false
false
sqlalchemy/mako
test/test_inheritance.py
9
10782
from mako import lookup from mako.testing.helpers import result_lines class InheritanceTest: def test_basic(self): collection = lookup.TemplateLookup() collection.put_string( "main", """ <%inherit file="base"/> <%def name="header()"> main header. </%def> this is the content. """, ) collection.put_string( "base", """ This is base. header: ${self.header()} body: ${self.body()} footer: ${self.footer()} <%def name="footer()"> this is the footer. header again ${next.header()} </%def> """, ) assert result_lines(collection.get_template("main").render()) == [ "This is base.", "header:", "main header.", "body:", "this is the content.", "footer:", "this is the footer. header again", "main header.", ] def test_multilevel_nesting(self): collection = lookup.TemplateLookup() collection.put_string( "main", """ <%inherit file="layout"/> <%def name="d()">main_d</%def> main_body ${parent.d()} full stack from the top: ${self.name} ${parent.name} ${parent.context['parent'].name} """ """${parent.context['parent'].context['parent'].name} """, ) collection.put_string( "layout", """ <%inherit file="general"/> <%def name="d()">layout_d</%def> layout_body parent name: ${parent.name} ${parent.d()} ${parent.context['parent'].d()} ${next.body()} """, ) collection.put_string( "general", """ <%inherit file="base"/> <%def name="d()">general_d</%def> general_body ${next.d()} ${next.context['next'].d()} ${next.body()} """, ) collection.put_string( "base", """ base_body full stack from the base: ${self.name} ${self.context['parent'].name} """ """${self.context['parent'].context['parent'].name} """ """${self.context['parent'].context['parent'].context['parent'].name} ${next.body()} <%def name="d()">base_d</%def> """, ) assert result_lines(collection.get_template("main").render()) == [ "base_body", "full stack from the base:", "self:main self:layout self:general self:base", "general_body", "layout_d", "main_d", "layout_body", "parent name: self:general", "general_d", "base_d", "main_body layout_d", "full stack from the top:", "self:main self:layout self:general self:base", ] def test_includes(self): """test that an included template also has its full hierarchy invoked.""" collection = lookup.TemplateLookup() collection.put_string( "base", """ <%def name="a()">base_a</%def> This is the base. ${next.body()} End base. """, ) collection.put_string( "index", """ <%inherit file="base"/> this is index. a is: ${self.a()} <%include file="secondary"/> """, ) collection.put_string( "secondary", """ <%inherit file="base"/> this is secondary. a is: ${self.a()} """, ) assert result_lines(collection.get_template("index").render()) == [ "This is the base.", "this is index.", "a is: base_a", "This is the base.", "this is secondary.", "a is: base_a", "End base.", "End base.", ] def test_namespaces(self): """test that templates used via <%namespace> have access to an inheriting 'self', and that the full 'self' is also exported.""" collection = lookup.TemplateLookup() collection.put_string( "base", """ <%def name="a()">base_a</%def> <%def name="b()">base_b</%def> This is the base. ${next.body()} """, ) collection.put_string( "layout", """ <%inherit file="base"/> <%def name="a()">layout_a</%def> This is the layout.. ${next.body()} """, ) collection.put_string( "index", """ <%inherit file="base"/> <%namespace name="sc" file="secondary"/> this is index. a is: ${self.a()} sc.a is: ${sc.a()} sc.b is: ${sc.b()} sc.c is: ${sc.c()} sc.body is: ${sc.body()} """, ) collection.put_string( "secondary", """ <%inherit file="layout"/> <%def name="c()">secondary_c. a is ${self.a()} b is ${self.b()} """ """d is ${self.d()}</%def> <%def name="d()">secondary_d.</%def> this is secondary. a is: ${self.a()} c is: ${self.c()} """, ) assert result_lines(collection.get_template("index").render()) == [ "This is the base.", "this is index.", "a is: base_a", "sc.a is: layout_a", "sc.b is: base_b", "sc.c is: secondary_c. a is layout_a b is base_b d is " "secondary_d.", "sc.body is:", "this is secondary.", "a is: layout_a", "c is: secondary_c. a is layout_a b is base_b d is secondary_d.", ] def test_pageargs(self): collection = lookup.TemplateLookup() collection.put_string( "base", """ this is the base. <% sorted_ = pageargs.items() sorted_ = sorted(sorted_) %> pageargs: (type: ${type(pageargs)}) ${sorted_} <%def name="foo()"> ${next.body(**context.kwargs)} </%def> ${foo()} """, ) collection.put_string( "index", """ <%inherit file="base"/> <%page args="x, y, z=7"/> print ${x}, ${y}, ${z} """, ) assert result_lines( collection.get_template("index").render_unicode(x=5, y=10) ) == [ "this is the base.", "pageargs: (type: <class 'dict'>) [('x', 5), ('y', 10)]", "print 5, 10, 7", ] def test_pageargs_2(self): collection = lookup.TemplateLookup() collection.put_string( "base", """ this is the base. ${next.body(**context.kwargs)} <%def name="foo(**kwargs)"> ${next.body(**kwargs)} </%def> <%def name="bar(**otherargs)"> ${next.body(z=16, **context.kwargs)} </%def> ${foo(x=12, y=15, z=8)} ${bar(x=19, y=17)} """, ) collection.put_string( "index", """ <%inherit file="base"/> <%page args="x, y, z=7"/> pageargs: ${x}, ${y}, ${z} """, ) assert result_lines( collection.get_template("index").render(x=5, y=10) ) == [ "this is the base.", "pageargs: 5, 10, 7", "pageargs: 12, 15, 8", "pageargs: 5, 10, 16", ] def test_pageargs_err(self): collection = lookup.TemplateLookup() collection.put_string( "base", """ this is the base. ${next.body()} """, ) collection.put_string( "index", """ <%inherit file="base"/> <%page args="x, y, z=7"/> print ${x}, ${y}, ${z} """, ) try: print(collection.get_template("index").render(x=5, y=10)) assert False except TypeError: assert True def test_toplevel(self): collection = lookup.TemplateLookup() collection.put_string( "base", """ this is the base. ${next.body()} """, ) collection.put_string( "index", """ <%inherit file="base"/> this is the body """, ) assert result_lines(collection.get_template("index").render()) == [ "this is the base.", "this is the body", ] assert result_lines( collection.get_template("index").get_def("body").render() ) == ["this is the body"] def test_dynamic(self): collection = lookup.TemplateLookup() collection.put_string( "base", """ this is the base. ${next.body()} """, ) collection.put_string( "index", """ <%! def dyn(context): if context.get('base', None) is not None: return 'base' else: return None %> <%inherit file="${dyn(context)}"/> this is index. """, ) assert result_lines(collection.get_template("index").render()) == [ "this is index." ] assert result_lines( collection.get_template("index").render(base=True) ) == ["this is the base.", "this is index."] def test_in_call(self): collection = lookup.TemplateLookup() collection.put_string( "/layout.html", """ Super layout! <%call expr="self.grid()"> ${next.body()} </%call> Oh yea! <%def name="grid()"> Parent grid ${caller.body()} End Parent </%def> """, ) collection.put_string( "/subdir/layout.html", """ ${next.body()} <%def name="grid()"> Subdir grid ${caller.body()} End subdir </%def> <%inherit file="/layout.html"/> """, ) collection.put_string( "/subdir/renderedtemplate.html", """ Holy smokes! <%inherit file="/subdir/layout.html"/> """, ) assert result_lines( collection.get_template("/subdir/renderedtemplate.html").render() ) == [ "Super layout!", "Subdir grid", "Holy smokes!", "End subdir", "Oh yea!", ]
mit
0e3094435a252ce56ff62b8ace98bab2
24.191589
81
0.433779
4.135788
false
false
false
false
frappe/frappe
frappe/permissions.py
2
21422
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import copy import frappe import frappe.share from frappe import _, msgprint from frappe.query_builder import DocType from frappe.utils import cint, cstr rights = ( "select", "read", "write", "create", "delete", "submit", "cancel", "amend", "print", "email", "report", "import", "export", "set_user_permissions", "share", ) def check_admin_or_system_manager(user=None): from frappe.utils.commands import warn warn( "The function check_admin_or_system_manager will be deprecated in version 15." 'Please use frappe.only_for("System Manager") instead.', category=PendingDeprecationWarning, ) if not user: user = frappe.session.user if ("System Manager" not in frappe.get_roles(user)) and (user != "Administrator"): frappe.throw(_("Not permitted"), frappe.PermissionError) def print_has_permission_check_logs(func): def inner(*args, **kwargs): frappe.flags["has_permission_check_logs"] = [] result = func(*args, **kwargs) self_perm_check = True if not kwargs.get("user") else kwargs.get("user") == frappe.session.user raise_exception = False if kwargs.get("raise_exception") is False else True # print only if access denied # and if user is checking his own permission if not result and self_perm_check and raise_exception: msgprint(("<br>").join(frappe.flags.get("has_permission_check_logs", []))) frappe.flags.pop("has_permission_check_logs", None) return result return inner @print_has_permission_check_logs def has_permission( doctype, ptype="read", doc=None, verbose=False, user=None, raise_exception=True, *, parent_doctype=None, ): """Returns True if user has permission `ptype` for given `doctype`. If `doc` is passed, it also checks user, share and owner permissions. :param doctype: DocType to check permission for :param ptype: Permission Type to check :param doc: Check User Permissions for specified document. :param verbose: DEPRECATED, will be removed in a future release. :param user: User to check permission for. Defaults to current user. :param raise_exception: DOES NOT raise an exception. If not False, will display a message using frappe.msgprint which explains why the permission check failed. :param parent_doctype: Required when checking permission for a child DocType (unless doc is specified) """ if not user: user = frappe.session.user if user == "Administrator": return True if not doc and hasattr(doctype, "doctype"): # first argument can be doc or doctype doc = doctype doctype = doc.doctype if frappe.is_table(doctype): return has_child_permission(doctype, ptype, doc, user, raise_exception, parent_doctype) meta = frappe.get_meta(doctype) if doc: if isinstance(doc, str): doc = frappe.get_doc(meta.name, doc) perm = get_doc_permissions(doc, user=user, ptype=ptype).get(ptype) if not perm: push_perm_check_log( _("User {0} does not have access to this document").format(frappe.bold(user)) ) else: if ptype == "submit" and not cint(meta.is_submittable): push_perm_check_log(_("Document Type is not submittable")) return False if ptype == "import" and not cint(meta.allow_import): push_perm_check_log(_("Document Type is not importable")) return False role_permissions = get_role_permissions(meta, user=user) perm = role_permissions.get(ptype) if not perm: push_perm_check_log( _("User {0} does not have doctype access via role permission for document {1}").format( frappe.bold(user), frappe.bold(doctype) ) ) def false_if_not_shared(): if ptype in ("read", "write", "share", "submit", "email", "print"): shared = frappe.share.get_shared( doctype, user, ["read" if ptype in ("email", "print") else ptype] ) if doc: doc_name = get_doc_name(doc) if doc_name in shared: if ptype in ("read", "write", "share", "submit") or meta.permissions[0].get(ptype): return True elif shared: # if atleast one shared doc of that type, then return True # this is used in db_query to check if permission on DocType return True return False if not perm: perm = false_if_not_shared() return bool(perm) def get_doc_permissions(doc, user=None, ptype=None): """Returns a dict of evaluated permissions for given `doc` like `{"read":1, "write":1}`""" if not user: user = frappe.session.user if frappe.is_table(doc.doctype): return {"read": 1, "write": 1} meta = frappe.get_meta(doc.doctype) def is_user_owner(): return (doc.get("owner") or "").lower() == user.lower() if has_controller_permissions(doc, ptype, user=user) is False: push_perm_check_log("Not allowed via controller permission check") return {ptype: 0} permissions = copy.deepcopy(get_role_permissions(meta, user=user, is_owner=is_user_owner())) if not cint(meta.is_submittable): permissions["submit"] = 0 if not cint(meta.allow_import): permissions["import"] = 0 # Override with `if_owner` perms irrespective of user if permissions.get("has_if_owner_enabled"): # apply owner permissions on top of existing permissions # some access might be only for the owner # eg. everyone might have read access but only owner can delete permissions.update(permissions.get("if_owner", {})) if not has_user_permission(doc, user): if is_user_owner(): # replace with owner permissions permissions = permissions.get("if_owner", {}) # if_owner does not come with create rights... permissions["create"] = 0 else: permissions = {} return permissions def get_role_permissions(doctype_meta, user=None, is_owner=None): """ Returns dict of evaluated role permissions like { "read": 1, "write": 0, // if "if_owner" is enabled "if_owner": { "read": 1, "write": 0 } } """ if isinstance(doctype_meta, str): doctype_meta = frappe.get_meta(doctype_meta) # assuming doctype name was passed if not user: user = frappe.session.user cache_key = (doctype_meta.name, user) if user == "Administrator": return allow_everything() if not frappe.local.role_permissions.get(cache_key): perms = frappe._dict(if_owner={}) roles = frappe.get_roles(user) def is_perm_applicable(perm): return perm.role in roles and cint(perm.permlevel) == 0 def has_permission_without_if_owner_enabled(ptype): return any(p.get(ptype, 0) and not p.get("if_owner", 0) for p in applicable_permissions) applicable_permissions = list( filter(is_perm_applicable, getattr(doctype_meta, "permissions", [])) ) has_if_owner_enabled = any(p.get("if_owner", 0) for p in applicable_permissions) perms["has_if_owner_enabled"] = has_if_owner_enabled for ptype in rights: pvalue = any(p.get(ptype, 0) for p in applicable_permissions) # check if any perm object allows perm type perms[ptype] = cint(pvalue) if ( pvalue and has_if_owner_enabled and not has_permission_without_if_owner_enabled(ptype) and ptype != "create" ): perms["if_owner"][ptype] = cint(pvalue and is_owner) # has no access if not owner # only provide select or read access so that user is able to at-least access list # (and the documents will be filtered based on owner sin further checks) perms[ptype] = 1 if ptype in ("select", "read") else 0 frappe.local.role_permissions[cache_key] = perms return frappe.local.role_permissions[cache_key] def get_user_permissions(user): from frappe.core.doctype.user_permission.user_permission import get_user_permissions return get_user_permissions(user) def has_user_permission(doc, user=None): """Returns True if User is allowed to view considering User Permissions""" from frappe.core.doctype.user_permission.user_permission import get_user_permissions user_permissions = get_user_permissions(user) if not user_permissions: # no user permission rules specified for this doctype return True # user can create own role permissions, so nothing applies if get_role_permissions("User Permission", user=user).get("write"): return True apply_strict_user_permissions = frappe.get_system_settings("apply_strict_user_permissions") doctype = doc.get("doctype") docname = doc.get("name") # STEP 1: --------------------- # check user permissions on self if doctype in user_permissions: allowed_docs = get_allowed_docs_for_doctype(user_permissions.get(doctype, []), doctype) # if allowed_docs is empty it states that there is no applicable permission under the current doctype # only check if allowed_docs is not empty if allowed_docs and docname not in allowed_docs: # no user permissions for this doc specified push_perm_check_log(_("Not allowed for {0}: {1}").format(_(doctype), docname)) return False # STEP 2: --------------------------------- # check user permissions in all link fields def check_user_permission_on_link_fields(d): # check user permissions for all the link fields of the given # document object d # # called for both parent and child records meta = frappe.get_meta(d.get("doctype")) # check all link fields for user permissions for field in meta.get_link_fields(): if field.ignore_user_permissions: continue # empty value, do you still want to apply user permissions? if not d.get(field.fieldname) and not apply_strict_user_permissions: # nah, not strict continue if field.options not in user_permissions: continue # get the list of all allowed values for this link allowed_docs = get_allowed_docs_for_doctype(user_permissions.get(field.options, []), doctype) if allowed_docs and d.get(field.fieldname) not in allowed_docs: # restricted for this link field, and no matching values found # make the right message and exit if d.get("parentfield"): # "Not allowed for Company = Restricted Company in Row 3. Restricted field: reference_type" msg = _("Not allowed for {0}: {1} in Row {2}. Restricted field: {3}").format( _(field.options), d.get(field.fieldname), d.idx, field.fieldname ) else: # "Not allowed for Company = Restricted Company. Restricted field: reference_type" msg = _("Not allowed for {0}: {1}. Restricted field: {2}").format( _(field.options), d.get(field.fieldname), field.fieldname ) push_perm_check_log(msg) return False return True if not check_user_permission_on_link_fields(doc): return False for d in doc.get_all_children(): if not check_user_permission_on_link_fields(d): return False return True def has_controller_permissions(doc, ptype, user=None): """Returns controller permissions if defined. None if not defined""" if not user: user = frappe.session.user methods = frappe.get_hooks("has_permission").get(doc.doctype, []) if not methods: return None for method in reversed(methods): controller_permission = frappe.call(frappe.get_attr(method), doc=doc, ptype=ptype, user=user) if controller_permission is not None: return controller_permission # controller permissions could not decide on True or False return None def get_doctypes_with_read(): return list({cstr(p.parent) for p in get_valid_perms() if p.parent}) def get_valid_perms(doctype=None, user=None): """Get valid permissions for the current user from DocPerm and Custom DocPerm""" roles = get_roles(user) perms = get_perms_for(roles) custom_perms = get_perms_for(roles, "Custom DocPerm") doctypes_with_custom_perms = get_doctypes_with_custom_docperms() for p in perms: if not p.parent in doctypes_with_custom_perms: custom_perms.append(p) if doctype: return [p for p in custom_perms if p.parent == doctype] else: return custom_perms def get_all_perms(role): """Returns valid permissions for a given role""" perms = frappe.get_all("DocPerm", fields="*", filters=dict(role=role)) custom_perms = frappe.get_all("Custom DocPerm", fields="*", filters=dict(role=role)) doctypes_with_custom_perms = frappe.get_all("Custom DocPerm", pluck="parent", distinct=True) for p in perms: if p.parent not in doctypes_with_custom_perms: custom_perms.append(p) return custom_perms def get_roles(user=None, with_standard=True): """get roles of current user""" if not user: user = frappe.session.user if user == "Guest": return ["Guest"] def get(): if user == "Administrator": return frappe.get_all("Role", pluck="name") # return all available roles else: table = DocType("Has Role") roles = ( frappe.qb.from_(table) .where((table.parent == user) & (table.role.notin(["All", "Guest"]))) .select(table.role) .run(pluck=True) ) return roles + ["All", "Guest"] roles = frappe.cache().hget("roles", user, get) # filter standard if required if not with_standard: roles = [r for r in roles if r not in ["All", "Guest", "Administrator"]] return roles def get_doctype_roles(doctype, access_type="read"): """Returns a list of roles that are allowed to access passed doctype.""" meta = frappe.get_meta(doctype) return [d.role for d in meta.get("permissions") if d.get(access_type)] def get_perms_for(roles, perm_doctype="DocPerm"): """Get perms for given roles""" filters = {"permlevel": 0, "docstatus": 0, "role": ["in", roles]} return frappe.get_all(perm_doctype, fields=["*"], filters=filters) def get_doctypes_with_custom_docperms(): """Returns all the doctypes with Custom Docperms""" doctypes = frappe.get_all("Custom DocPerm", fields=["parent"], distinct=1) return [d.parent for d in doctypes] def can_set_user_permissions(doctype, docname=None): # System Manager can always set user permissions if frappe.session.user == "Administrator" or "System Manager" in frappe.get_roles(): return True meta = frappe.get_meta(doctype) # check if current user has read permission for docname if docname and not has_permission(doctype, "read", docname): return False # check if current user has a role that can set permission if get_role_permissions(meta).set_user_permissions != 1: return False return True def set_user_permission_if_allowed(doctype, name, user, with_message=False): if get_role_permissions(frappe.get_meta(doctype), user).set_user_permissions != 1: add_user_permission(doctype, name, user) def add_user_permission( doctype, name, user, ignore_permissions=False, applicable_for=None, is_default=0, hide_descendants=0, ): """Add user permission""" from frappe.core.doctype.user_permission.user_permission import user_permission_exists if not user_permission_exists(user, doctype, name, applicable_for): if not frappe.db.exists(doctype, name): frappe.throw(_("{0} {1} not found").format(_(doctype), name), frappe.DoesNotExistError) frappe.get_doc( dict( doctype="User Permission", user=user, allow=doctype, for_value=name, is_default=is_default, applicable_for=applicable_for, apply_to_all_doctypes=0 if applicable_for else 1, hide_descendants=hide_descendants, ) ).insert(ignore_permissions=ignore_permissions) def remove_user_permission(doctype, name, user): user_permission_name = frappe.db.get_value( "User Permission", dict(user=user, allow=doctype, for_value=name) ) frappe.delete_doc("User Permission", user_permission_name) def clear_user_permissions_for_doctype(doctype, user=None): filters = {"allow": doctype} if user: filters["user"] = user user_permissions_for_doctype = frappe.get_all("User Permission", filters=filters) for d in user_permissions_for_doctype: frappe.delete_doc("User Permission", d.name) def can_import(doctype, raise_exception=False): if not ("System Manager" in frappe.get_roles() or has_permission(doctype, "import")): if raise_exception: raise frappe.PermissionError(f"You are not allowed to import: {doctype}") else: return False return True def can_export(doctype, raise_exception=False): if "System Manager" in frappe.get_roles(): return True else: role_permissions = frappe.permissions.get_role_permissions(doctype) has_access = role_permissions.get("export") or role_permissions.get("if_owner").get("export") if not has_access and raise_exception: raise frappe.PermissionError(_("You are not allowed to export {} doctype").format(doctype)) return has_access def update_permission_property(doctype, role, permlevel, ptype, value=None, validate=True): """Update a property in Custom Perm""" from frappe.core.doctype.doctype.doctype import validate_permissions_for_doctype out = setup_custom_perms(doctype) name = frappe.get_value("Custom DocPerm", dict(parent=doctype, role=role, permlevel=permlevel)) table = DocType("Custom DocPerm") frappe.qb.update(table).set(ptype, value).where(table.name == name).run() if validate: validate_permissions_for_doctype(doctype) return out def setup_custom_perms(parent): """if custom permssions are not setup for the current doctype, set them up""" if not frappe.db.exists("Custom DocPerm", dict(parent=parent)): copy_perms(parent) return True def add_permission(doctype, role, permlevel=0, ptype=None): """Add a new permission rule to the given doctype for the given Role and Permission Level""" from frappe.core.doctype.doctype.doctype import validate_permissions_for_doctype setup_custom_perms(doctype) if frappe.db.get_value( "Custom DocPerm", dict(parent=doctype, role=role, permlevel=permlevel, if_owner=0) ): return if not ptype: ptype = "read" custom_docperm = frappe.get_doc( { "doctype": "Custom DocPerm", "__islocal": 1, "parent": doctype, "parenttype": "DocType", "parentfield": "permissions", "role": role, "permlevel": permlevel, ptype: 1, } ) custom_docperm.save() validate_permissions_for_doctype(doctype) return custom_docperm.name def copy_perms(parent): """Copy all DocPerm in to Custom DocPerm for the given document""" for d in frappe.get_all("DocPerm", fields="*", filters=dict(parent=parent)): custom_perm = frappe.new_doc("Custom DocPerm") custom_perm.update(d) custom_perm.insert(ignore_permissions=True) def reset_perms(doctype): """Reset permissions for given doctype.""" from frappe.desk.notifications import delete_notification_count_for delete_notification_count_for(doctype) frappe.db.delete("Custom DocPerm", {"parent": doctype}) def get_linked_doctypes(dt: str) -> list: meta = frappe.get_meta(dt) linked_doctypes = [dt] + [ d.options for d in meta.get( "fields", {"fieldtype": "Link", "ignore_user_permissions": ("!=", 1), "options": ("!=", "[Select]")}, ) ] return list(set(linked_doctypes)) def get_doc_name(doc): if not doc: return None return doc if isinstance(doc, str) else doc.name def allow_everything(): """ returns a dict with access to everything eg. {"read": 1, "write": 1, ...} """ perm = {ptype: 1 for ptype in rights} return perm def get_allowed_docs_for_doctype(user_permissions, doctype): """Returns all the docs from the passed user_permissions that are allowed under provided doctype""" return filter_allowed_docs_for_doctype(user_permissions, doctype, with_default_doc=False) def filter_allowed_docs_for_doctype(user_permissions, doctype, with_default_doc=True): """Returns all the docs from the passed user_permissions that are allowed under provided doctype along with default doc value if with_default_doc is set""" allowed_doc = [] default_doc = None for doc in user_permissions: if not doc.get("applicable_for") or doc.get("applicable_for") == doctype: allowed_doc.append(doc.get("doc")) if doc.get("is_default") or len(user_permissions) == 1 and with_default_doc: default_doc = doc.get("doc") return (allowed_doc, default_doc) if with_default_doc else allowed_doc def push_perm_check_log(log): if frappe.flags.get("has_permission_check_logs") is None: return frappe.flags.get("has_permission_check_logs").append(_(log)) def has_child_permission( child_doctype, ptype="read", child_doc=None, user=None, raise_exception=True, parent_doctype=None, ): if isinstance(child_doc, str): child_doc = frappe.db.get_value( child_doctype, child_doc, ("parent", "parenttype", "parentfield"), as_dict=True, ) if child_doc: parent_doctype = child_doc.parenttype if not parent_doctype: push_perm_check_log( _("Please specify a valid parent DocType for {0}").format(frappe.bold(child_doctype)) ) return False parent_meta = frappe.get_meta(parent_doctype) if parent_meta.istable or all( df.options != child_doctype for df in parent_meta.get_table_fields() ): push_perm_check_log( _("{0} is not a valid parent DocType for {1}").format( frappe.bold(parent_doctype), frappe.bold(child_doctype) ) ) return False if ( child_doc and (permlevel := parent_meta.get_field(child_doc.parentfield).permlevel) > 0 and permlevel not in parent_meta.get_permlevel_access(ptype, user=user) ): push_perm_check_log( _("Insufficient Permission Level for {0}").format(frappe.bold(parent_doctype)) ) return False return has_permission( parent_doctype, ptype=ptype, doc=child_doc and getattr(child_doc, "parent_doc", child_doc.parent), user=user, raise_exception=raise_exception, )
mit
64070fde3c0134f0645c7e9fdaffc165
28.185286
103
0.698954
3.29063
false
false
false
false
frappe/frappe
frappe/database/postgres/setup_db.py
2
3317
import os import frappe def setup_database(force, source_sql=None, verbose=False): root_conn = get_root_connection(frappe.flags.root_login, frappe.flags.root_password) root_conn.commit() root_conn.sql("end") root_conn.sql(f"DROP DATABASE IF EXISTS `{frappe.conf.db_name}`") root_conn.sql(f"DROP USER IF EXISTS {frappe.conf.db_name}") root_conn.sql(f"CREATE DATABASE `{frappe.conf.db_name}`") root_conn.sql(f"CREATE user {frappe.conf.db_name} password '{frappe.conf.db_password}'") root_conn.sql("GRANT ALL PRIVILEGES ON DATABASE `{0}` TO {0}".format(frappe.conf.db_name)) root_conn.close() bootstrap_database(frappe.conf.db_name, verbose, source_sql=source_sql) frappe.connect() def bootstrap_database(db_name, verbose, source_sql=None): frappe.connect(db_name=db_name) import_db_from_sql(source_sql, verbose) frappe.connect(db_name=db_name) if "tabDefaultValue" not in frappe.db.get_tables(): import sys from click import secho secho( "Table 'tabDefaultValue' missing in the restored site. " "This may be due to incorrect permissions or the result of a restore from a bad backup file. " "Database not installed correctly.", fg="red", ) sys.exit(1) def import_db_from_sql(source_sql=None, verbose=False): from shutil import which from subprocess import PIPE, run # we can't pass psql password in arguments in postgresql as mysql. So # set password connection parameter in environment variable subprocess_env = os.environ.copy() subprocess_env["PGPASSWORD"] = str(frappe.conf.db_password) # bootstrap db if not source_sql: source_sql = os.path.join(os.path.dirname(__file__), "framework_postgres.sql") pv = which("pv") _command = ( f"psql {frappe.conf.db_name} " f"-h {frappe.conf.db_host or 'localhost'} -p {str(frappe.conf.db_port or '5432')} " f"-U {frappe.conf.db_name}" ) if pv: command = f"{pv} {source_sql} | " + _command else: command = _command + f" -f {source_sql}" print("Restoring Database file...") if verbose: print(command) restore_proc = run(command, env=subprocess_env, shell=True, stdout=PIPE) if verbose: print( f"\nSTDOUT by psql:\n{restore_proc.stdout.decode()}\nImported from Database File: {source_sql}" ) def get_root_connection(root_login=None, root_password=None): if not frappe.local.flags.root_connection: if not root_login: root_login = frappe.conf.get("root_login") or None if not root_login: root_login = input("Enter postgres super user: ") if not root_password: root_password = frappe.conf.get("root_password") or None if not root_password: from getpass import getpass root_password = getpass("Postgres super user password: ") frappe.local.flags.root_connection = frappe.database.get_db( user=root_login, password=root_password ) return frappe.local.flags.root_connection def drop_user_and_database(db_name, root_login, root_password): root_conn = get_root_connection( frappe.flags.root_login or root_login, frappe.flags.root_password or root_password ) root_conn.commit() root_conn.sql( "SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = %s", (db_name,), ) root_conn.sql("end") root_conn.sql(f"DROP DATABASE IF EXISTS {db_name}") root_conn.sql(f"DROP USER IF EXISTS {db_name}")
mit
64d5e2ecbb20d0d2dc9886c60007545d
28.616071
113
0.714501
2.966905
false
false
false
false
frappe/frappe
frappe/website/doctype/web_form/web_form.py
1
17704
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # License: MIT. See LICENSE import json import os import frappe from frappe import _, scrub from frappe.core.api.file import get_max_file_size from frappe.core.doctype.file import remove_file_by_url from frappe.desk.form.meta import get_code_files_via_hooks from frappe.modules.utils import export_module_json, get_doc_module from frappe.rate_limiter import rate_limit from frappe.utils import cstr, dict_with_keys, strip_html from frappe.website.utils import get_boot_data, get_comment_list, get_sidebar_items from frappe.website.website_generator import WebsiteGenerator class WebForm(WebsiteGenerator): website = frappe._dict(no_cache=1) def onload(self): super().onload() def validate(self): super().validate() if not self.module: self.module = frappe.db.get_value("DocType", self.doc_type, "module") in_user_env = not ( frappe.flags.in_install or frappe.flags.in_patch or frappe.flags.in_test or frappe.flags.in_fixtures ) if in_user_env and self.is_standard and not frappe.conf.developer_mode: # only published can be changed for standard web forms if self.has_value_changed("published"): published_value = self.published self.reload() self.published = published_value else: frappe.throw(_("You need to be in developer mode to edit a Standard Web Form")) if not frappe.flags.in_import: self.validate_fields() def validate_fields(self): """Validate all fields are present""" from frappe.model import no_value_fields missing = [] meta = frappe.get_meta(self.doc_type) for df in self.web_form_fields: if df.fieldname and (df.fieldtype not in no_value_fields and not meta.has_field(df.fieldname)): missing.append(df.fieldname) if missing: frappe.throw(_("Following fields are missing:") + "<br>" + "<br>".join(missing)) def reset_field_parent(self): """Convert link fields to select with names as options""" for df in self.web_form_fields: df.parent = self.doc_type # export def on_update(self): """ Writes the .txt for this page and if write_content is checked, it will write out a .html file """ path = export_module_json(self, self.is_standard, self.module) if path: # js if not os.path.exists(path + ".js"): with open(path + ".js", "w") as f: f.write( """frappe.ready(function() { // bind events here })""" ) # py if not os.path.exists(path + ".py"): with open(path + ".py", "w") as f: f.write( """import frappe def get_context(context): # do your magic here pass """ ) def get_context(self, context): """Build context to render the `web_form.html` template""" context.in_edit_mode = False context.in_view_mode = False if frappe.form_dict.is_list: context.template = "website/doctype/web_form/templates/web_list.html" else: context.template = "website/doctype/web_form/templates/web_form.html" # check permissions if frappe.form_dict.name: if frappe.session.user == "Guest": frappe.throw( _("You need to be logged in to access this {0}.").format(self.doc_type), frappe.PermissionError, ) if not frappe.db.exists(self.doc_type, frappe.form_dict.name): raise frappe.PageDoesNotExistError() if not self.has_web_form_permission(self.doc_type, frappe.form_dict.name): frappe.throw( _("You don't have the permissions to access this document"), frappe.PermissionError ) if frappe.local.path == self.route: path = f"/{self.route}/list" if self.show_list else f"/{self.route}/new" frappe.redirect(path) if frappe.form_dict.is_list and not self.show_list: frappe.redirect(f"/{self.route}/new") if frappe.form_dict.is_edit and not self.allow_edit: context.in_view_mode = True frappe.redirect(f"/{self.route}/{frappe.form_dict.name}") if frappe.form_dict.is_edit: context.in_edit_mode = True if frappe.form_dict.is_read: context.in_view_mode = True if ( not frappe.form_dict.is_edit and not frappe.form_dict.is_read and self.allow_edit and frappe.form_dict.name ): context.in_edit_mode = True frappe.redirect(f"/{frappe.local.path}/edit") if ( frappe.session.user != "Guest" and self.login_required and not self.allow_multiple and not frappe.form_dict.name and not frappe.form_dict.is_list ): name = frappe.db.get_value(self.doc_type, {"owner": frappe.session.user}, "name") if name: context.in_view_mode = True frappe.redirect(f"/{self.route}/{name}") # Show new form when # - User is Guest # - Login not required route_to_new = frappe.session.user == "Guest" or not self.login_required if not frappe.form_dict.is_new and route_to_new: frappe.redirect(f"/{self.route}/new") self.reset_field_parent() # add keys from form_dict to context context.update(dict_with_keys(frappe.form_dict, ["is_list", "is_new", "is_edit", "is_read"])) for df in self.web_form_fields: if df.fieldtype == "Column Break": context.has_column_break = True break # load web form doc context.web_form_doc = self.as_dict(no_nulls=True) context.web_form_doc.update( dict_with_keys(context, ["is_list", "is_new", "in_edit_mode", "in_view_mode"]) ) if self.show_sidebar and self.website_sidebar: context.sidebar_items = get_sidebar_items(self.website_sidebar) if frappe.form_dict.is_list: self.load_list_data(context) else: self.load_form_data(context) self.add_custom_context_and_script(context) self.load_translations(context) context.boot = get_boot_data() context.boot["link_title_doctypes"] = frappe.boot.get_link_title_doctypes() def load_translations(self, context): translated_messages = frappe.translate.get_dict("doctype", self.doc_type) # Sr is not added by default, had to be added manually translated_messages["Sr"] = _("Sr") context.translated_messages = frappe.as_json(translated_messages) def load_list_data(self, context): if not self.list_columns: self.list_columns = get_in_list_view_fields(self.doc_type) context.web_form_doc.list_columns = self.list_columns def load_form_data(self, context): """Load document `doc` and `layout` properties for template""" context.parents = [] if self.show_list: context.parents.append( { "label": _(self.title), "route": f"{self.route}/list", } ) context.parents = self.get_parents(context) if self.breadcrumbs: context.parents = frappe.safe_eval(self.breadcrumbs, {"_": _}) if self.show_list and frappe.form_dict.is_new: context.title = _("New {0}").format(context.title) context.has_header = (frappe.form_dict.name or frappe.form_dict.is_new) and ( frappe.session.user != "Guest" or not self.login_required ) if context.success_message: context.success_message = frappe.db.escape(context.success_message.replace("\n", "<br>")).strip( "'" ) if not context.max_attachment_size: context.max_attachment_size = get_max_file_size() / 1024 / 1024 # For Table fields, server-side processing for meta for field in context.web_form_doc.web_form_fields: if field.fieldtype == "Table": field.fields = get_in_list_view_fields(field.options) if field.fieldtype == "Link": field.fieldtype = "Autocomplete" field.options = get_link_options( self.name, field.options, field.allow_read_on_all_link_options ) context.reference_doc = {} # load reference doc if frappe.form_dict.name: context.doc_name = frappe.form_dict.name context.reference_doc = frappe.get_doc(self.doc_type, context.doc_name) context.web_form_title = context.title context.title = ( strip_html(context.reference_doc.get(context.reference_doc.meta.get_title_field())) or context.doc_name ) context.reference_doc.add_seen() context.reference_doctype = context.reference_doc.doctype context.reference_name = context.reference_doc.name if self.show_attachments: context.attachments = frappe.get_all( "File", filters={ "attached_to_name": context.reference_name, "attached_to_doctype": context.reference_doctype, "is_private": 0, }, fields=["file_name", "file_url", "file_size"], ) if self.allow_comments: context.comment_list = get_comment_list( context.reference_doc.doctype, context.reference_doc.name ) context.reference_doc = context.reference_doc.as_dict(no_nulls=True) def add_custom_context_and_script(self, context): """Update context from module if standard and append script""" if self.is_standard: web_form_module = get_web_form_module(self) new_context = web_form_module.get_context(context) if new_context: context.update(new_context) js_path = os.path.join(os.path.dirname(web_form_module.__file__), scrub(self.name) + ".js") if os.path.exists(js_path): script = frappe.render_template(open(js_path).read(), context) for path in get_code_files_via_hooks("webform_include_js", context.doc_type): custom_js = frappe.render_template(open(path).read(), context) script = "\n\n".join([script, custom_js]) context.script = script css_path = os.path.join(os.path.dirname(web_form_module.__file__), scrub(self.name) + ".css") if os.path.exists(css_path): style = open(css_path).read() for path in get_code_files_via_hooks("webform_include_css", context.doc_type): custom_css = open(path).read() style = "\n\n".join([style, custom_css]) context.style = style def get_parents(self, context): parents = None if context.is_list and not context.parents: parents = [{"title": _("My Account"), "name": "me"}] elif context.parents: parents = context.parents return parents def validate_mandatory(self, doc): """Validate mandatory web form fields""" missing = [] for f in self.web_form_fields: if f.reqd and doc.get(f.fieldname) in (None, [], ""): missing.append(f) if missing: frappe.throw( _("Mandatory Information missing:") + "<br><br>" + "<br>".join(f"{d.label} ({d.fieldtype})" for d in missing) ) def allow_website_search_indexing(self): return False def has_web_form_permission(self, doctype, name, ptype="read"): if frappe.session.user == "Guest": return False if self.apply_document_permissions: return frappe.get_doc(doctype, name).has_permission() # owner matches elif frappe.db.get_value(doctype, name, "owner") == frappe.session.user: return True elif frappe.has_website_permission(name, ptype=ptype, doctype=doctype): return True elif check_webform_perm(doctype, name): return True else: return False def get_web_form_module(doc): if doc.is_standard: return get_doc_module(doc.module, doc.doctype, doc.name) @frappe.whitelist(allow_guest=True) @rate_limit(key="web_form", limit=5, seconds=60, methods=["POST"]) def accept(web_form, data, docname=None): """Save the web form""" data = frappe._dict(json.loads(data)) files = [] files_to_delete = [] web_form = frappe.get_doc("Web Form", web_form) if data.name and not web_form.allow_edit: frappe.throw(_("You are not allowed to update this Web Form Document")) frappe.flags.in_web_form = True meta = frappe.get_meta(data.doctype) if docname: # update doc = frappe.get_doc(data.doctype, docname) else: # insert doc = frappe.new_doc(data.doctype) # set values for field in web_form.web_form_fields: fieldname = field.fieldname df = meta.get_field(fieldname) value = data.get(fieldname, "") if df and df.fieldtype in ("Attach", "Attach Image"): if value and "data:" and "base64" in value: files.append((fieldname, value)) if not doc.name: doc.set(fieldname, "") continue elif not value and doc.get(fieldname): files_to_delete.append(doc.get(fieldname)) doc.set(fieldname, value) if doc.name: if web_form.has_web_form_permission(doc.doctype, doc.name, "write"): doc.save(ignore_permissions=True) else: # only if permissions are present doc.save() else: # insert if web_form.login_required and frappe.session.user == "Guest": frappe.throw(_("You must login to submit this form")) ignore_mandatory = True if files else False doc.insert(ignore_permissions=True, ignore_mandatory=ignore_mandatory) # add files if files: for f in files: fieldname, filedata = f # remove earlier attached file (if exists) if doc.get(fieldname): remove_file_by_url(doc.get(fieldname), doctype=doc.doctype, name=doc.name) # save new file filename, dataurl = filedata.split(",", 1) _file = frappe.get_doc( { "doctype": "File", "file_name": filename, "attached_to_doctype": doc.doctype, "attached_to_name": doc.name, "content": dataurl, "decode": True, } ) _file.save() # update values doc.set(fieldname, _file.file_url) doc.save(ignore_permissions=True) if files_to_delete: for f in files_to_delete: if f: remove_file_by_url(f, doctype=doc.doctype, name=doc.name) frappe.flags.web_form_doc = doc return doc @frappe.whitelist() def delete(web_form_name, docname): web_form = frappe.get_doc("Web Form", web_form_name) owner = frappe.db.get_value(web_form.doc_type, docname, "owner") if frappe.session.user == owner and web_form.allow_delete: frappe.delete_doc(web_form.doc_type, docname, ignore_permissions=True) else: raise frappe.PermissionError("Not Allowed") @frappe.whitelist() def delete_multiple(web_form_name, docnames): web_form = frappe.get_doc("Web Form", web_form_name) docnames = json.loads(docnames) allowed_docnames = [] restricted_docnames = [] for docname in docnames: owner = frappe.db.get_value(web_form.doc_type, docname, "owner") if frappe.session.user == owner and web_form.allow_delete: allowed_docnames.append(docname) else: restricted_docnames.append(docname) for docname in allowed_docnames: frappe.delete_doc(web_form.doc_type, docname, ignore_permissions=True) if restricted_docnames: raise frappe.PermissionError( "You do not have permisssion to delete " + ", ".join(restricted_docnames) ) def check_webform_perm(doctype, name): doc = frappe.get_doc(doctype, name) if hasattr(doc, "has_webform_permission"): if doc.has_webform_permission(): return True @frappe.whitelist(allow_guest=True) def get_web_form_filters(web_form_name): web_form = frappe.get_doc("Web Form", web_form_name) return [field for field in web_form.web_form_fields if field.show_in_filter] @frappe.whitelist(allow_guest=True) def get_form_data(doctype, docname=None, web_form_name=None): web_form = frappe.get_doc("Web Form", web_form_name) if web_form.login_required and frappe.session.user == "Guest": frappe.throw(_("Not Permitted"), frappe.PermissionError) out = frappe._dict() out.web_form = web_form if frappe.session.user != "Guest" and not docname and not web_form.allow_multiple: docname = frappe.db.get_value(doctype, {"owner": frappe.session.user}, "name") if docname: doc = frappe.get_doc(doctype, docname) if web_form.has_web_form_permission(doctype, docname, ptype="read"): out.doc = doc else: frappe.throw(_("Not permitted"), frappe.PermissionError) # For Table fields, server-side processing for meta for field in out.web_form.web_form_fields: if field.fieldtype == "Table": field.fields = get_in_list_view_fields(field.options) out.update({field.fieldname: field.fields}) if field.fieldtype == "Link": field.fieldtype = "Autocomplete" field.options = get_link_options( web_form_name, field.options, field.allow_read_on_all_link_options ) return out @frappe.whitelist() def get_in_list_view_fields(doctype): meta = frappe.get_meta(doctype) fields = [] if meta.title_field: fields.append(meta.title_field) else: fields.append("name") if meta.has_field("status"): fields.append("status") fields += [df.fieldname for df in meta.fields if df.in_list_view and df.fieldname not in fields] def get_field_df(fieldname): if fieldname == "name": return {"label": "Name", "fieldname": "name", "fieldtype": "Data"} return meta.get_field(fieldname).as_dict() return [get_field_df(f) for f in fields] @frappe.whitelist(allow_guest=True) def get_link_options(web_form_name, doctype, allow_read_on_all_link_options=False): web_form_doc = frappe.get_doc("Web Form", web_form_name) doctype_validated = False limited_to_user = False if web_form_doc.login_required: # check if frappe session user is not guest or admin if frappe.session.user != "Guest": doctype_validated = True if not allow_read_on_all_link_options: limited_to_user = True else: frappe.throw(_("You must be logged in to use this form."), frappe.PermissionError) else: for field in web_form_doc.web_form_fields: if field.options == doctype: doctype_validated = True break if doctype_validated: link_options, filters = [], {} if limited_to_user: filters = {"owner": frappe.session.user} fields = ["name as value"] title_field = frappe.db.get_value("DocType", doctype, "title_field", cache=1) show_title_field_in_link = ( frappe.db.get_value("DocType", doctype, "show_title_field_in_link", cache=1) == 1 ) if title_field and show_title_field_in_link: fields.append(f"{title_field} as label") link_options = frappe.get_all(doctype, filters, fields) if title_field and show_title_field_in_link: return json.dumps(link_options, default=str) else: return "\n".join([doc.value for doc in link_options]) else: raise frappe.PermissionError( _("You don't have permission to access the {0} DocType.").format(doctype) )
mit
b150c3e48989ae48f24790afdf72ffee
27.833876
99
0.689392
3.034625
false
false
false
false
simpeg/discretize
discretize/curvilinear_mesh.py
1
27594
import numpy as np from discretize.utils import ( mkvc, index_cube, face_info, volume_tetrahedron, make_boundary_bool, ) from discretize.base import BaseRectangularMesh from discretize.operators import DiffOperators, InnerProducts from discretize.mixins import InterfaceMixins # Some helper functions. def _length2D(x): return (x[:, 0] ** 2 + x[:, 1] ** 2) ** 0.5 def _length3D(x): return (x[:, 0] ** 2 + x[:, 1] ** 2 + x[:, 2] ** 2) ** 0.5 def _normalize2D(x): return x / np.kron(np.ones((1, 2)), mkvc(_length2D(x), 2)) def _normalize3D(x): return x / np.kron(np.ones((1, 3)), mkvc(_length3D(x), 2)) class CurvilinearMesh( DiffOperators, InnerProducts, BaseRectangularMesh, InterfaceMixins ): """Curvilinear mesh class. Curvilinear meshes are numerical grids whose cells are general quadrilaterals (2D) or cuboid (3D); unlike tensor meshes (see :class:`~discretize.TensorMesh`) whose cells are rectangles or rectangular prisms. That being said, the combinatorial structure (i.e. connectivity of mesh cells) of curvilinear meshes is the same as tensor meshes. Parameters ---------- node_list : list of array_like List :class:`array_like` containing the gridded x, y (and z) node locations. - For a 2D curvilinear mesh, *node_list* = [X, Y] where X and Y have shape (``n_nodes_x``, ``n_nodes_y``) - For a 3D curvilinear mesh, *node_list* = [X, Y, Z] where X, Y and Z have shape (``n_nodes_x``, ``n_nodes_y``, ``n_nodes_z``) Examples -------- Using the :py:func:`~discretize.utils.example_curvilinear_grid` utility, we provide an example of a curvilinear mesh. >>> from discretize import CurvilinearMesh >>> from discretize.utils import example_curvilinear_grid >>> import matplotlib.pyplot as plt The example grid slightly rotates the nodes in the center of the mesh, >>> x, y = example_curvilinear_grid([10, 10], "rotate") >>> x.shape (11, 11) >>> y.shape (11, 11) >>> curvilinear_mesh = CurvilinearMesh([x, y]) >>> curvilinear_mesh.shape_nodes (11, 11) >>> fig = plt.figure(figsize=(5,5)) >>> ax = fig.add_subplot(111) >>> curvilinear_mesh.plot_grid(ax=ax) >>> plt.show() """ _meshType = "Curv" _aliases = { **DiffOperators._aliases, **BaseRectangularMesh._aliases, **{ "gridFx": "faces_x", "gridFy": "faces_y", "gridFz": "faces_z", "gridEx": "edges_x", "gridEy": "edges_y", "gridEz": "edges_z", }, } _items = {"node_list"} def __init__(self, node_list, **kwargs): if "nodes" in kwargs: node_list = kwargs.pop("nodes") node_list = tuple(np.asarray(item, dtype=np.float64) for item in node_list) # check shapes of each node array match dim = len(node_list) if dim not in [2, 3]: raise ValueError( f"Only supports 2 and 3 dimensional meshes, saw a node_list of length {dim}" ) for i, nodes in enumerate(node_list): if len(nodes.shape) != dim: raise ValueError( f"Unexpected shape of item in node list, expect array with {dim} dimensions, got {len(nodes.shape)}" ) if node_list[0].shape != nodes.shape: raise ValueError( f"The shape of nodes are not consistent, saw {node_list[0].shape} and {nodes.shape}" ) self._node_list = tuple(node_list) # Save nodes to private variable _nodes as vectors self._nodes = np.ones((self.node_list[0].size, dim)) for i, nodes in enumerate(self.node_list): self._nodes[:, i] = mkvc(nodes) shape_cells = (n - 1 for n in self.node_list[0].shape) # absorb the rest of kwargs, and do not pass to super super().__init__(shape_cells, origin=self.nodes[0]) @property def node_list(self): """Returns the gridded x, y (and z) node locations used to create the mesh. Returns ------- (dim) list of numpy.ndarray Gridded x, y (and z) node locations used to create the mesh. - *2D:* return is a list [X, Y] where X and Y have shape (n_nodes_x, n_nodes_y) - *3D:* return is a list [X, Y, Z] where X, Y and Z have shape (n_nodes_x, n_nodes_y, n_nodes_z) """ return self._node_list @classmethod def deserialize(cls, value, **kwargs): if "nodes" in value: value["node_list"] = value.pop("nodes") return super().deserialize(value, **kwargs) @property def cell_centers(self): if getattr(self, "_cell_centers", None) is None: self._cell_centers = np.concatenate( [self.aveN2CC * self.gridN[:, i] for i in range(self.dim)] ).reshape((-1, self.dim), order="F") return self._cell_centers @property def nodes(self): if getattr(self, "_nodes", None) is None: raise Exception("Someone deleted this. I blame you.") return self._nodes @property def faces_x(self): """Gridded x-face locations (staggered grid) This property returns a numpy array of shape (n_faces_x, dim) containing gridded locations for all x-faces in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the x-faces are faces whose normal vectors are primarily along the x-direction. For highly irregular meshes however, this is not the case; see the examples below. Returns ------- (n_faces_x, dim) numpy.ndarray of float Gridded x-face locations (staggered grid) Examples -------- Here, we provide an example of a minimally staggered curvilinear mesh. In this case, the x-faces have normal vectors that are primarily along the x-direction. >>> from discretize import CurvilinearMesh >>> from discretize.utils import example_curvilinear_grid, mkvc >>> from matplotlib import pyplot as plt >>> x, y = example_curvilinear_grid([10, 10], "rotate") >>> mesh1 = CurvilinearMesh([x, y]) >>> x_faces = mesh1.faces_x >>> fig1 = plt.figure(figsize=(5, 5)) >>> ax1 = fig1.add_subplot(111) >>> mesh1.plot_grid(ax=ax1) >>> ax1.scatter(x_faces[:, 0], x_faces[:, 1], 30, 'r') >>> ax1.legend(['Mesh', 'X-faces'], fontsize=16) >>> plt.plot() Here, we provide an example of a highly irregular curvilinear mesh. In this case, the x-faces are not defined by normal vectors along a particular direction. >>> x, y = example_curvilinear_grid([10, 10], "sphere") >>> mesh2 = CurvilinearMesh([x, y]) >>> x_faces = mesh2.faces_x >>> fig2 = plt.figure(figsize=(5, 5)) >>> ax2 = fig2.add_subplot(111) >>> mesh2.plot_grid(ax=ax2) >>> ax2.scatter(x_faces[:, 0], x_faces[:, 1], 30, 'r') >>> ax2.legend(['Mesh', 'X-faces'], fontsize=16) >>> plt.plot() """ if getattr(self, "_faces_x", None) is None: N = self.reshape(self.gridN, "N", "N", "M") if self.dim == 2: XY = [mkvc(0.5 * (n[:, :-1] + n[:, 1:])) for n in N] self._faces_x = np.c_[XY[0], XY[1]] elif self.dim == 3: XYZ = [ mkvc( 0.25 * ( n[:, :-1, :-1] + n[:, :-1, 1:] + n[:, 1:, :-1] + n[:, 1:, 1:] ) ) for n in N ] self._faces_x = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._faces_x @property def faces_y(self): """Gridded y-face locations (staggered grid) This property returns a numpy array of shape (n_faces_y, dim) containing gridded locations for all y-faces in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the y-faces are faces whose normal vectors are primarily along the y-direction. For highly irregular meshes however, this is not the case; see the examples below. Returns ------- (n_faces_y, dim) numpy.ndarray of float Gridded y-face locations (staggered grid) Examples -------- Here, we provide an example of a minimally staggered curvilinear mesh. In this case, the y-faces have normal vectors that are primarily along the x-direction. >>> from discretize import CurvilinearMesh >>> from discretize.utils import example_curvilinear_grid, mkvc >>> from matplotlib import pyplot as plt >>> x, y = example_curvilinear_grid([10, 10], "rotate") >>> mesh1 = CurvilinearMesh([x, y]) >>> y_faces = mesh1.faces_y >>> fig1 = plt.figure(figsize=(5, 5)) >>> ax1 = fig1.add_subplot(111) >>> mesh1.plot_grid(ax=ax1) >>> ax1.scatter(y_faces[:, 0], y_faces[:, 1], 30, 'r') >>> ax1.legend(['Mesh', 'Y-faces'], fontsize=16) >>> plt.plot() Here, we provide an example of a highly irregular curvilinear mesh. In this case, the y-faces are not defined by normal vectors along a particular direction. >>> x, y = example_curvilinear_grid([10, 10], "sphere") >>> mesh2 = CurvilinearMesh([x, y]) >>> y_faces = mesh2.faces_y >>> fig2 = plt.figure(figsize=(5, 5)) >>> ax2 = fig2.add_subplot(111) >>> mesh2.plot_grid(ax=ax2) >>> ax2.scatter(y_faces[:, 0], y_faces[:, 1], 30, 'r') >>> ax2.legend(['Mesh', 'Y-faces'], fontsize=16) >>> plt.plot() """ if getattr(self, "_faces_y", None) is None: N = self.reshape(self.gridN, "N", "N", "M") if self.dim == 2: XY = [mkvc(0.5 * (n[:-1, :] + n[1:, :])) for n in N] self._faces_y = np.c_[XY[0], XY[1]] elif self.dim == 3: XYZ = [ mkvc( 0.25 * ( n[:-1, :, :-1] + n[:-1, :, 1:] + n[1:, :, :-1] + n[1:, :, 1:] ) ) for n in N ] self._faces_y = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._faces_y @property def faces_z(self): """Gridded z-face locations (staggered grid) This property returns a numpy array of shape (n_faces_z, dim) containing gridded locations for all z-faces in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the z-faces are faces whose normal vectors are primarily along the z-direction. For highly irregular meshes however, this is not the case. Returns ------- (n_faces_z, dim) numpy.ndarray of float Gridded z-face locations (staggered grid) """ if getattr(self, "_faces_z", None) is None: N = self.reshape(self.gridN, "N", "N", "M") XYZ = [ mkvc( 0.25 * (n[:-1, :-1, :] + n[:-1, 1:, :] + n[1:, :-1, :] + n[1:, 1:, :]) ) for n in N ] self._faces_z = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._faces_z @property def faces(self): faces = np.r_[self.faces_x, self.faces_y] if self.dim > 2: faces = np.r_[faces, self.faces_z] return faces @property def edges_x(self): """Gridded x-edge locations (staggered grid) This property returns a numpy array of shape (n_edges_x, dim) containing gridded locations for all x-edges in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the x-edges are edges oriented primarily along the x-direction. For highly irregular meshes however, this is not the case; see the examples below. Returns ------- (n_edges_x, dim) numpy.ndarray of float Gridded x-edge locations (staggered grid) Examples -------- Here, we provide an example of a minimally staggered curvilinear mesh. In this case, the x-edges are primarily oriented along the x-direction. >>> from discretize import CurvilinearMesh >>> from discretize.utils import example_curvilinear_grid, mkvc >>> from matplotlib import pyplot as plt >>> x, y = example_curvilinear_grid([10, 10], "rotate") >>> mesh1 = CurvilinearMesh([x, y]) >>> x_edges = mesh1.edges_x >>> fig1 = plt.figure(figsize=(5, 5)) >>> ax1 = fig1.add_subplot(111) >>> mesh1.plot_grid(ax=ax1) >>> ax1.scatter(x_edges[:, 0], x_edges[:, 1], 30, 'r') >>> ax1.legend(['Mesh', 'X-edges'], fontsize=16) >>> plt.plot() Here, we provide an example of a highly irregular curvilinear mesh. In this case, the x-edges are not aligned primarily along a particular direction. >>> x, y = example_curvilinear_grid([10, 10], "sphere") >>> mesh2 = CurvilinearMesh([x, y]) >>> x_edges = mesh2.edges_x >>> fig2 = plt.figure(figsize=(5, 5)) >>> ax2 = fig2.add_subplot(111) >>> mesh2.plot_grid(ax=ax2) >>> ax2.scatter(x_edges[:, 0], x_edges[:, 1], 30, 'r') >>> ax2.legend(['Mesh', 'X-edges'], fontsize=16) >>> plt.plot() """ if getattr(self, "_edges_x", None) is None: N = self.reshape(self.gridN, "N", "N", "M") if self.dim == 2: XY = [mkvc(0.5 * (n[:-1, :] + n[1:, :])) for n in N] self._edges_x = np.c_[XY[0], XY[1]] elif self.dim == 3: XYZ = [mkvc(0.5 * (n[:-1, :, :] + n[1:, :, :])) for n in N] self._edges_x = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._edges_x @property def edges_y(self): """Gridded y-edge locations (staggered grid) This property returns a numpy array of shape (n_edges_y, dim) containing gridded locations for all y-edges in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the y-edges are edges oriented primarily along the y-direction. For highly irregular meshes however, this is not the case; see the examples below. Returns ------- (n_edges_y, dim) numpy.ndarray of float Gridded y-edge locations (staggered grid) Examples -------- Here, we provide an example of a minimally staggered curvilinear mesh. In this case, the y-edges are primarily oriented along the y-direction. >>> from discretize import CurvilinearMesh >>> from discretize.utils import example_curvilinear_grid, mkvc >>> from matplotlib import pyplot as plt >>> x, y = example_curvilinear_grid([10, 10], "rotate") >>> mesh1 = CurvilinearMesh([x, y]) >>> y_edges = mesh1.edges_y >>> fig1 = plt.figure(figsize=(5, 5)) >>> ax1 = fig1.add_subplot(111) >>> mesh1.plot_grid(ax=ax1) >>> ax1.scatter(y_edges[:, 0], y_edges[:, 1], 30, 'r') >>> ax1.legend(['Mesh', 'Y-edges'], fontsize=16) >>> plt.plot() Here, we provide an example of a highly irregular curvilinear mesh. In this case, the y-edges are not aligned primarily along a particular direction. >>> x, y = example_curvilinear_grid([10, 10], "sphere") >>> mesh2 = CurvilinearMesh([x, y]) >>> y_edges = mesh2.edges_y >>> fig2 = plt.figure(figsize=(5, 5)) >>> ax2 = fig2.add_subplot(111) >>> mesh2.plot_grid(ax=ax2) >>> ax2.scatter(y_edges[:, 0], y_edges[:, 1], 30, 'r') >>> ax2.legend(['Mesh', 'X-edges'], fontsize=16) >>> plt.plot() """ if getattr(self, "_edges_y", None) is None: N = self.reshape(self.gridN, "N", "N", "M") if self.dim == 2: XY = [mkvc(0.5 * (n[:, :-1] + n[:, 1:])) for n in N] self._edges_y = np.c_[XY[0], XY[1]] elif self.dim == 3: XYZ = [mkvc(0.5 * (n[:, :-1, :] + n[:, 1:, :])) for n in N] self._edges_y = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._edges_y @property def edges_z(self): """Gridded z-edge locations (staggered grid) This property returns a numpy array of shape (n_edges_z, dim) containing gridded locations for all z-edges in the mesh (staggered grid). For curvilinear meshes whose structure is minimally staggered, the z-edges are faces whose normal vectors are primarily along the z-direction. For highly irregular meshes however, this is not the case. Returns ------- (n_edges_z, dim) numpy.ndarray of float Gridded z-edge locations (staggered grid) """ if getattr(self, "_edges_z", None) is None and self.dim == 3: N = self.reshape(self.gridN, "N", "N", "M") XYZ = [mkvc(0.5 * (n[:, :, :-1] + n[:, :, 1:])) for n in N] self._edges_z = np.c_[XYZ[0], XYZ[1], XYZ[2]] return self._edges_z @property def edges(self): edges = np.r_[self.edges_x, self.edges_y] if self.dim > 2: edges = np.r_[edges, self.edges_z] return edges @property def boundary_nodes(self): return self.nodes[make_boundary_bool(self.shape_nodes)] @property def boundary_edges(self): if self.dim == 2: ex = self.edges_x[make_boundary_bool(self.shape_edges_x, dir="y")] ey = self.edges_y[make_boundary_bool(self.shape_edges_y, dir="x")] return np.r_[ex, ey] elif self.dim == 3: ex = self.edges_x[make_boundary_bool(self.shape_edges_x, dir="yz")] ey = self.edges_y[make_boundary_bool(self.shape_edges_y, dir="xz")] ez = self.edges_z[make_boundary_bool(self.shape_edges_z, dir="xy")] return np.r_[ex, ey, ez] @property def boundary_faces(self): fx = self.faces_x[make_boundary_bool(self.shape_faces_x, dir="x")] fy = self.faces_y[make_boundary_bool(self.shape_faces_y, dir="y")] if self.dim == 2: return np.r_[fx, fy] elif self.dim == 3: fz = self.faces_z[make_boundary_bool(self.shape_faces_z, dir="z")] return np.r_[fx, fy, fz] @property def boundary_face_outward_normals(self): is_bxm = np.zeros(self.shape_faces_x, order="F", dtype=bool) is_bxm[0, :] = True is_bxm = is_bxm.reshape(-1, order="F") is_bym = np.zeros(self.shape_faces_y, order="F", dtype=bool) is_bym[:, 0] = True is_bym = is_bym.reshape(-1, order="F") is_b = np.r_[ make_boundary_bool(self.shape_faces_x, dir="x"), make_boundary_bool(self.shape_faces_y, dir="y"), ] switch = np.r_[is_bxm, is_bym] if self.dim == 3: is_bzm = np.zeros(self.shape_faces_z, order="F", dtype=bool) is_bzm[:, :, 0] = True is_bzm = is_bzm.reshape(-1, order="F") is_b = np.r_[is_b, make_boundary_bool(self.shape_faces_z, dir="z")] switch = np.r_[switch, is_bzm] face_normals = self.face_normals.copy() face_normals[switch] *= -1 return face_normals[is_b] # --------------- Geometries --------------------- # # # ------------------- 2D ------------------------- # # node(i,j) node(i,j+1) # A -------------- B # | | # | cell(i,j) | # | I | # | | # D -------------- C # node(i+1,j) node(i+1,j+1) # # ------------------- 3D ------------------------- # # # node(i,j,k+1) node(i,j+1,k+1) # E --------------- F # /| / | # / | / | # / | / | # node(i,j,k) node(i,j+1,k) # A -------------- B | # | H ----------|---- G # | /cell(i,j) | / # | / I | / # | / | / # D -------------- C # node(i+1,j,k) node(i+1,j+1,k) @property def cell_volumes(self): if getattr(self, "_cell_volumes", None) is None: if self.dim == 2: A, B, C, D = index_cube("ABCD", self.vnN) normal, area = face_info( np.c_[self.gridN, np.zeros((self.nN, 1))], A, B, C, D ) self._cell_volumes = area elif self.dim == 3: # Each polyhedron can be decomposed into 5 tetrahedrons # However, this presents a choice so we may as well divide in # two ways and average. A, B, C, D, E, F, G, H = index_cube("ABCDEFGH", self.vnN) vol1 = ( volume_tetrahedron(self.gridN, A, B, D, E) + volume_tetrahedron(self.gridN, B, E, F, G) # cutted edge top + volume_tetrahedron(self.gridN, B, D, E, G) # cutted edge top + volume_tetrahedron(self.gridN, B, C, D, G) # middle + volume_tetrahedron(self.gridN, D, E, G, H) # cutted edge bottom ) # cutted edge bottom vol2 = ( volume_tetrahedron(self.gridN, A, F, B, C) + volume_tetrahedron(self.gridN, A, E, F, H) # cutted edge top + volume_tetrahedron(self.gridN, A, H, F, C) # cutted edge top + volume_tetrahedron(self.gridN, C, H, D, A) # middle + volume_tetrahedron(self.gridN, C, G, H, F) # cutted edge bottom ) # cutted edge bottom self._cell_volumes = (vol1 + vol2) / 2 return self._cell_volumes @property def face_areas(self): if ( getattr(self, "_face_areas", None) is None or getattr(self, "_normals", None) is None ): # Compute areas of cell faces if self.dim == 2: xy = self.gridN A, B = index_cube("AB", self.vnN, self.vnFx) edge1 = xy[B, :] - xy[A, :] normal1 = np.c_[edge1[:, 1], -edge1[:, 0]] area1 = _length2D(edge1) A, D = index_cube("AD", self.vnN, self.vnFy) # Note that we are doing A-D to make sure the normal points the # right way. # Think about it. Look at the picture. Normal points towards C # iff you do this. edge2 = xy[A, :] - xy[D, :] normal2 = np.c_[edge2[:, 1], -edge2[:, 0]] area2 = _length2D(edge2) self._face_areas = np.r_[mkvc(area1), mkvc(area2)] self._normals = [_normalize2D(normal1), _normalize2D(normal2)] elif self.dim == 3: A, E, F, B = index_cube("AEFB", self.vnN, self.vnFx) normal1, area1 = face_info( self.gridN, A, E, F, B, average=False, normalizeNormals=False ) A, D, H, E = index_cube("ADHE", self.vnN, self.vnFy) normal2, area2 = face_info( self.gridN, A, D, H, E, average=False, normalizeNormals=False ) A, B, C, D = index_cube("ABCD", self.vnN, self.vnFz) normal3, area3 = face_info( self.gridN, A, B, C, D, average=False, normalizeNormals=False ) self._face_areas = np.r_[mkvc(area1), mkvc(area2), mkvc(area3)] self._normals = [normal1, normal2, normal3] return self._face_areas @property def face_normals(self): # For 3D meshes, there are 4 nodes in which # cross-products can be used to compute the normal vector. # In this case, the average normal vector is returned so there # is only 1 vector per face. if getattr(self, "_normals", None) is None: self.face_areas # calling .face_areas will create the face normals if self.dim == 2: return _normalize2D(np.r_[self._normals[0], self._normals[1]]) elif self.dim == 3: normal1 = ( self._normals[0][0] + self._normals[0][1] + self._normals[0][2] + self._normals[0][3] ) / 4 normal2 = ( self._normals[1][0] + self._normals[1][1] + self._normals[1][2] + self._normals[1][3] ) / 4 normal3 = ( self._normals[2][0] + self._normals[2][1] + self._normals[2][2] + self._normals[2][3] ) / 4 return _normalize3D(np.r_[normal1, normal2, normal3]) @property def edge_lengths(self): if getattr(self, "_edge_lengths", None) is None: if self.dim == 2: xy = self.gridN A, D = index_cube("AD", self.vnN, self.vnEx) edge1 = xy[D, :] - xy[A, :] A, B = index_cube("AB", self.vnN, self.vnEy) edge2 = xy[B, :] - xy[A, :] self._edge_lengths = np.r_[ mkvc(_length2D(edge1)), mkvc(_length2D(edge2)) ] self._edge_tangents = ( np.r_[edge1, edge2] / np.c_[self._edge_lengths, self._edge_lengths] ) elif self.dim == 3: xyz = self.gridN A, D = index_cube("AD", self.vnN, self.vnEx) edge1 = xyz[D, :] - xyz[A, :] A, B = index_cube("AB", self.vnN, self.vnEy) edge2 = xyz[B, :] - xyz[A, :] A, E = index_cube("AE", self.vnN, self.vnEz) edge3 = xyz[E, :] - xyz[A, :] self._edge_lengths = np.r_[ mkvc(_length3D(edge1)), mkvc(_length3D(edge2)), mkvc(_length3D(edge3)), ] self._edge_tangents = ( np.r_[edge1, edge2, edge3] / np.c_[self._edge_lengths, self._edge_lengths, self._edge_lengths] ) return self._edge_lengths @property def edge_tangents(self): if getattr(self, "_edge_tangents", None) is None: self.edge_lengths # calling .edge_lengths will create the tangents return self._edge_tangents
mit
d4dbb637295a4c3a506e5e16771c0cc2
36.903846
120
0.501776
3.484091
false
false
false
false
frappe/frappe
frappe/database/utils.py
2
1564
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import typing from functools import cached_property from types import NoneType import frappe from frappe.query_builder.builder import MariaDB, Postgres from frappe.query_builder.functions import Function if typing.TYPE_CHECKING: from frappe.query_builder import DocType Query = str | MariaDB | Postgres QueryValues = tuple | list | dict | NoneType EmptyQueryValues = object() FallBackDateTimeStr = "0001-01-01 00:00:00.000000" NestedSetHierarchy = ( "ancestors of", "descendants of", "not ancestors of", "not descendants of", ) def is_query_type(query: str, query_type: str | tuple[str]) -> bool: return query.lstrip().split(maxsplit=1)[0].lower().startswith(query_type) def is_pypika_function_object(field: str) -> bool: return getattr(field, "__module__", None) == "pypika.functions" or isinstance(field, Function) class LazyString: def _setup(self) -> None: raise NotImplementedError @cached_property def value(self) -> str: return self._setup() def __str__(self) -> str: return self.value def __repr__(self) -> str: return f"'{self.value}'" class LazyDecode(LazyString): __slots__ = () def __init__(self, value: str) -> None: self._value = value def _setup(self) -> None: return self._value.decode() class LazyMogrify(LazyString): __slots__ = () def __init__(self, query, values) -> None: self.query = query self.values = values def _setup(self) -> str: return frappe.db.mogrify(self.query, self.values)
mit
5aef9e4bb3b4deaa8ca6aababccc4d70
21.342857
95
0.703964
3.153226
false
false
false
false
frappe/frappe
frappe/desk/link_preview.py
3
1421
import frappe from frappe.model import no_value_fields, table_fields @frappe.whitelist() def get_preview_data(doctype, docname): preview_fields = [] meta = frappe.get_meta(doctype) if not meta.show_preview_popup: return preview_fields = [ field.fieldname for field in meta.fields if field.in_preview and field.fieldtype not in no_value_fields and field.fieldtype not in table_fields ] # no preview fields defined, build list from mandatory fields if not preview_fields: preview_fields = [ field.fieldname for field in meta.fields if field.reqd and field.fieldtype not in table_fields ] title_field = meta.get_title_field() image_field = meta.image_field preview_fields.append(title_field) preview_fields.append(image_field) preview_fields.append("name") preview_data = frappe.get_list(doctype, filters={"name": docname}, fields=preview_fields, limit=1) if not preview_data: return preview_data = preview_data[0] formatted_preview_data = { "preview_image": preview_data.get(image_field), "preview_title": preview_data.get(title_field), "name": preview_data.get("name"), } for key, val in preview_data.items(): if val and meta.has_field(key) and key not in [image_field, title_field, "name"]: formatted_preview_data[meta.get_field(key).label] = frappe.format( val, meta.get_field(key).fieldtype, translated=True, ) return formatted_preview_data
mit
207367f0ef10c915c79881384c0e2aad
25.314815
99
0.724842
3.123077
false
false
false
false
frappe/frappe
frappe/tests/test_query_builder.py
2
13097
import unittest from collections.abc import Callable from datetime import time import frappe from frappe.query_builder import Case from frappe.query_builder.builder import Function from frappe.query_builder.custom import ConstantColumn from frappe.query_builder.functions import Cast_, Coalesce, CombineDatetime, GroupConcat, Match from frappe.query_builder.utils import db_type_is from frappe.tests.utils import FrappeTestCase def run_only_if(dbtype: db_type_is) -> Callable: return unittest.skipIf(db_type_is(frappe.conf.db_type) != dbtype, f"Only runs for {dbtype.value}") @run_only_if(db_type_is.MARIADB) class TestCustomFunctionsMariaDB(FrappeTestCase): def test_concat(self): self.assertEqual("GROUP_CONCAT('Notes')", GroupConcat("Notes").get_sql()) def test_match(self): query = Match("Notes") with self.assertRaises(Exception): query.get_sql() query = query.Against("text") self.assertEqual(" MATCH('Notes') AGAINST ('+text*' IN BOOLEAN MODE)", query.get_sql()) def test_constant_column(self): query = frappe.qb.from_("DocType").select("name", ConstantColumn("John").as_("User")) self.assertEqual(query.get_sql(), "SELECT `name`,'John' `User` FROM `tabDocType`") def test_timestamp(self): note = frappe.qb.DocType("Note") self.assertEqual( "TIMESTAMP(posting_date,posting_time)", CombineDatetime(note.posting_date, note.posting_time).get_sql(), ) self.assertEqual( "TIMESTAMP('2021-01-01','00:00:21')", CombineDatetime("2021-01-01", "00:00:21").get_sql() ) todo = frappe.qb.DocType("ToDo") select_query = ( frappe.qb.from_(note) .join(todo) .on(todo.refernce_name == note.name) .select(CombineDatetime(note.posting_date, note.posting_time)) ) self.assertIn( "select timestamp(`tabnote`.`posting_date`,`tabnote`.`posting_time`)", str(select_query).lower() ) select_query = select_query.orderby(CombineDatetime(note.posting_date, note.posting_time)) self.assertIn( "order by timestamp(`tabnote`.`posting_date`,`tabnote`.`posting_time`)", str(select_query).lower(), ) select_query = select_query.where( CombineDatetime(note.posting_date, note.posting_time) >= CombineDatetime("2021-01-01", "00:00:01") ) self.assertIn( "timestamp(`tabnote`.`posting_date`,`tabnote`.`posting_time`)>=timestamp('2021-01-01','00:00:01')", str(select_query).lower(), ) select_query = select_query.select( CombineDatetime(note.posting_date, note.posting_time, alias="timestamp") ) self.assertIn( "timestamp(`tabnote`.`posting_date`,`tabnote`.`posting_time`) `timestamp`", str(select_query).lower(), ) def test_time(self): note = frappe.qb.DocType("Note") self.assertEqual( "TIMESTAMP('2021-01-01','00:00:21')", CombineDatetime("2021-01-01", time(0, 0, 21)).get_sql() ) select_query = frappe.qb.from_(note).select( CombineDatetime(note.posting_date, note.posting_time) ) self.assertIn("select timestamp(`posting_date`,`posting_time`)", str(select_query).lower()) select_query = select_query.where( CombineDatetime(note.posting_date, note.posting_time) >= CombineDatetime("2021-01-01", time(0, 0, 1)) ) self.assertIn( "timestamp(`posting_date`,`posting_time`)>=timestamp('2021-01-01','00:00:01')", str(select_query).lower(), ) def test_cast(self): note = frappe.qb.DocType("Note") self.assertEqual("CONCAT(name,'')", Cast_(note.name, "varchar").get_sql()) self.assertEqual("CAST(name AS INTEGER)", Cast_(note.name, "integer").get_sql()) self.assertEqual( frappe.qb.from_("red").from_(note).select("other", Cast_(note.name, "varchar")).get_sql(), "SELECT `tabred`.`other`,CONCAT(`tabNote`.`name`,'') FROM `tabred`,`tabNote`", ) @run_only_if(db_type_is.POSTGRES) class TestCustomFunctionsPostgres(FrappeTestCase): def test_concat(self): self.assertEqual("STRING_AGG('Notes',',')", GroupConcat("Notes").get_sql()) def test_match(self): query = Match("Notes") self.assertEqual("TO_TSVECTOR('Notes')", query.get_sql()) query = Match("Notes").Against("text") self.assertEqual("TO_TSVECTOR('Notes') @@ PLAINTO_TSQUERY('text')", query.get_sql()) def test_constant_column(self): query = frappe.qb.from_("DocType").select("name", ConstantColumn("John").as_("User")) self.assertEqual(query.get_sql(), 'SELECT "name",\'John\' "User" FROM "tabDocType"') def test_timestamp(self): note = frappe.qb.DocType("Note") self.assertEqual( "posting_date+posting_time", CombineDatetime(note.posting_date, note.posting_time).get_sql() ) self.assertEqual( "CAST('2021-01-01' AS DATE)+CAST('00:00:21' AS TIME)", CombineDatetime("2021-01-01", "00:00:21").get_sql(), ) todo = frappe.qb.DocType("ToDo") select_query = ( frappe.qb.from_(note) .join(todo) .on(todo.refernce_name == note.name) .select(CombineDatetime(note.posting_date, note.posting_time)) ) self.assertIn( 'select "tabnote"."posting_date"+"tabnote"."posting_time"', str(select_query).lower() ) select_query = select_query.orderby(CombineDatetime(note.posting_date, note.posting_time)) self.assertIn( 'order by "tabnote"."posting_date"+"tabnote"."posting_time"', str(select_query).lower() ) select_query = select_query.where( CombineDatetime(note.posting_date, note.posting_time) >= CombineDatetime("2021-01-01", "00:00:01") ) self.assertIn( """where "tabnote"."posting_date"+"tabnote"."posting_time">=cast('2021-01-01' as date)+cast('00:00:01' as time)""", str(select_query).lower(), ) select_query = select_query.select( CombineDatetime(note.posting_date, note.posting_time, alias="timestamp") ) self.assertIn( '"tabnote"."posting_date"+"tabnote"."posting_time" "timestamp"', str(select_query).lower() ) def test_time(self): note = frappe.qb.DocType("Note") self.assertEqual( "CAST('2021-01-01' AS DATE)+CAST('00:00:21' AS TIME)", CombineDatetime("2021-01-01", time(0, 0, 21)).get_sql(), ) select_query = frappe.qb.from_(note).select( CombineDatetime(note.posting_date, note.posting_time) ) self.assertIn('select "posting_date"+"posting_time"', str(select_query).lower()) select_query = select_query.where( CombineDatetime(note.posting_date, note.posting_time) >= CombineDatetime("2021-01-01", time(0, 0, 1)) ) self.assertIn( """where "posting_date"+"posting_time">=cast('2021-01-01' as date)+cast('00:00:01' as time)""", str(select_query).lower(), ) def test_cast(self): note = frappe.qb.DocType("Note") self.assertEqual("CAST(name AS VARCHAR)", Cast_(note.name, "varchar").get_sql()) self.assertEqual("CAST(name AS INTEGER)", Cast_(note.name, "integer").get_sql()) self.assertEqual( frappe.qb.from_("red").from_(note).select("other", Cast_(note.name, "varchar")).get_sql(), 'SELECT "tabred"."other",CAST("tabNote"."name" AS VARCHAR) FROM "tabred","tabNote"', ) class TestBuilderBase: def test_adding_tabs(self): self.assertEqual("tabNotes", frappe.qb.DocType("Notes").get_sql()) self.assertEqual("__Auth", frappe.qb.DocType("__Auth").get_sql()) self.assertEqual("Notes", frappe.qb.Table("Notes").get_sql()) def test_run_patcher(self): query = frappe.qb.from_("ToDo").select("*").limit(1) data = query.run(as_dict=True) self.assertTrue("run" in dir(query)) self.assertIsInstance(query.run, Callable) self.assertIsInstance(data, list) def test_agg_funcs(self): frappe.db.truncate("Communication") sample_data = { "doctype": "Communication", "communication_type": "Communication", "content": "testing", "rating": 1, } frappe.get_doc(sample_data).insert() sample_data["rating"] = 3 frappe.get_doc(sample_data).insert() sample_data["rating"] = 4 frappe.get_doc(sample_data).insert() self.assertEqual(frappe.qb.max("Communication", "rating"), 4) self.assertEqual(frappe.qb.min("Communication", "rating"), 1) self.assertAlmostEqual(frappe.qb.avg("Communication", "rating"), 2.666, places=2) self.assertEqual(frappe.qb.sum("Communication", "rating"), 8.0) frappe.db.rollback() class TestParameterization(FrappeTestCase): def test_where_conditions(self): DocType = frappe.qb.DocType("DocType") query = frappe.qb.from_(DocType).select(DocType.name).where(DocType.owner == "Administrator' --") self.assertTrue("walk" in dir(query)) query, params = query.walk() self.assertIn("%(param1)s", query) self.assertIn("param1", params) self.assertEqual(params["param1"], "Administrator' --") def test_set_conditions(self): DocType = frappe.qb.DocType("DocType") query = frappe.qb.update(DocType).set(DocType.value, "some_value") self.assertTrue("walk" in dir(query)) query, params = query.walk() self.assertIn("%(param1)s", query) self.assertIn("param1", params) self.assertEqual(params["param1"], "some_value") def test_where_conditions_functions(self): DocType = frappe.qb.DocType("DocType") query = ( frappe.qb.from_(DocType) .select(DocType.name) .where(Coalesce(DocType.search_fields == "subject")) ) self.assertTrue("walk" in dir(query)) query, params = query.walk() self.assertIn("%(param1)s", query) self.assertIn("param1", params) self.assertEqual(params["param1"], "subject") def test_case(self): DocType = frappe.qb.DocType("DocType") query = frappe.qb.from_(DocType).select( Case() .when(DocType.search_fields == "value", "other_value") .when(Coalesce(DocType.search_fields == "subject_in_function"), "true_value") .else_("Overdue") ) self.assertTrue("walk" in dir(query)) query, params = query.walk() self.assertIn("%(param1)s", query) self.assertIn("param1", params) self.assertEqual(params["param1"], "value") self.assertEqual(params["param2"], "other_value") self.assertEqual(params["param3"], "subject_in_function") self.assertEqual(params["param4"], "true_value") self.assertEqual(params["param5"], "Overdue") def test_case_in_update(self): DocType = frappe.qb.DocType("DocType") query = frappe.qb.update(DocType).set( "parent", Case() .when(DocType.search_fields == "value", "other_value") .when(Coalesce(DocType.search_fields == "subject_in_function"), "true_value") .else_("Overdue"), ) self.assertTrue("walk" in dir(query)) query, params = query.walk() self.assertIn("%(param1)s", query) self.assertIn("param1", params) self.assertEqual(params["param1"], "value") self.assertEqual(params["param2"], "other_value") self.assertEqual(params["param3"], "subject_in_function") self.assertEqual(params["param4"], "true_value") self.assertEqual(params["param5"], "Overdue") def test_named_parameter_wrapper(self): from frappe.query_builder.terms import NamedParameterWrapper test_npw = NamedParameterWrapper() self.assertTrue(hasattr(test_npw, "parameters")) self.assertEqual(test_npw.get_sql("test_string_one"), "%(param1)s") self.assertEqual(test_npw.get_sql("test_string_two"), "%(param2)s") params = test_npw.get_parameters() for key in params.keys(): # checks for param# format self.assertRegex(key, r"param\d") self.assertEqual(params["param1"], "test_string_one") @run_only_if(db_type_is.MARIADB) class TestBuilderMaria(FrappeTestCase, TestBuilderBase): def test_adding_tabs_in_from(self): self.assertEqual("SELECT * FROM `tabNotes`", frappe.qb.from_("Notes").select("*").get_sql()) self.assertEqual("SELECT * FROM `__Auth`", frappe.qb.from_("__Auth").select("*").get_sql()) def test_get_qb_type(self): from frappe.query_builder import get_query_builder qb = get_query_builder(frappe.db.db_type) self.assertEqual("SELECT * FROM `tabDocType`", qb().from_("DocType").select("*").get_sql()) @run_only_if(db_type_is.POSTGRES) class TestBuilderPostgres(FrappeTestCase, TestBuilderBase): def test_adding_tabs_in_from(self): self.assertEqual('SELECT * FROM "tabNotes"', frappe.qb.from_("Notes").select("*").get_sql()) self.assertEqual('SELECT * FROM "__Auth"', frappe.qb.from_("__Auth").select("*").get_sql()) def test_replace_tables(self): info_schema = frappe.qb.Schema("information_schema") self.assertEqual( 'SELECT * FROM "pg_stat_all_tables"', frappe.qb.from_(info_schema.tables).select("*").get_sql(), ) def test_replace_fields_post(self): self.assertEqual("relname", frappe.qb.Field("table_name").get_sql()) def test_get_qb_type(self): from frappe.query_builder import get_query_builder qb = get_query_builder(frappe.db.db_type) self.assertEqual('SELECT * FROM "tabDocType"', qb().from_("DocType").select("*").get_sql()) class TestMisc(FrappeTestCase): def test_custom_func(self): rand_func = frappe.qb.functions("rand", "45") self.assertIsInstance(rand_func, Function) self.assertEqual(rand_func.get_sql(), "rand('45')") def test_function_with_schema(self): from frappe.query_builder import ParameterizedFunction x = ParameterizedFunction("rand", "45") x.schema = frappe.qb.DocType("DocType") self.assertEqual("tabDocType.rand('45')", x.get_sql()) def test_util_table(self): from frappe.query_builder.utils import Table DocType = Table("DocType") self.assertEqual(DocType.get_sql(), "DocType")
mit
33e8284c1ad88c357086e9e505f43fb9
33.925333
118
0.690234
2.976591
false
true
false
false
frappe/frappe
frappe/core/doctype/submission_queue/submission_queue.py
1
5727
# Copyright (c) 2022, Frappe Technologies and contributors # For license information, please see license.txt from urllib.parse import quote from rq import get_current_job from rq.exceptions import NoSuchJobError from rq.job import Job import frappe from frappe import _ from frappe.desk.doctype.notification_log.notification_log import enqueue_create_notification from frappe.model.document import Document from frappe.monitor import add_data_to_monitor from frappe.utils import now, time_diff_in_seconds from frappe.utils.background_jobs import get_redis_conn from frappe.utils.data import cint class SubmissionQueue(Document): @property def created_at(self): return self.creation @property def enqueued_by(self): return self.owner @property def queued_doc(self): return getattr(self, "to_be_queued_doc", frappe.get_doc(self.ref_doctype, self.ref_docname)) @staticmethod def clear_old_logs(days=30): from frappe.query_builder import Interval from frappe.query_builder.functions import Now table = frappe.qb.DocType("Submission Queue") frappe.db.delete(table, filters=(table.modified < (Now() - Interval(days=days)))) def insert(self, to_be_queued_doc: Document, action: str): self.to_be_queued_doc = to_be_queued_doc self.action_for_queuing = action super().insert(ignore_permissions=True) def lock(self): self.queued_doc.lock() def unlock(self): self.queued_doc.unlock() def update_job_id(self, job_id): frappe.db.set_value( self.doctype, self.name, {"job_id": job_id}, update_modified=False, ) frappe.db.commit() def after_insert(self): self.queue_action( "background_submission", to_be_queued_doc=self.queued_doc, action_for_queuing=self.action_for_queuing, timeout=600, enqueue_after_commit=True, ) def background_submission(self, to_be_queued_doc: Document, action_for_queuing: str): # Set the job id for that submission doctype self.update_job_id(get_current_job().id) _action = action_for_queuing.lower() if _action == "update": _action = "submit" try: getattr(to_be_queued_doc, _action)() add_data_to_monitor( doctype=to_be_queued_doc.doctype, docname=to_be_queued_doc.name, action=_action, execution_time=time_diff_in_seconds(now(), self.created_at), enqueued_by=self.enqueued_by, ) values = {"status": "Finished"} except Exception: values = {"status": "Failed", "exception": frappe.get_traceback()} frappe.db.rollback() values["ended_at"] = now() frappe.db.set_value(self.doctype, self.name, values, update_modified=False) self.notify(values["status"], action_for_queuing) def notify(self, submission_status: str, action: str): if submission_status == "Failed": doctype = self.doctype docname = self.name message = _("Submission of {0} {1} with action {2} failed") else: doctype = self.ref_doctype docname = self.ref_docname message = _("Submission of {0} {1} with action {2} completed successfully") message = message.format( frappe.bold(str(self.ref_doctype)), frappe.bold(self.ref_docname), frappe.bold(action) ) time_diff = time_diff_in_seconds(now(), self.created_at) if cint(time_diff) <= 60: frappe.publish_realtime( "msgprint", { "message": message + f". View it <a href='/app/{quote(doctype.lower().replace(' ', '-'))}/{quote(docname)}'><b>here</b></a>", "alert": True, "indicator": "red" if submission_status == "Failed" else "green", }, user=self.enqueued_by, ) else: notification_doc = { "type": "Alert", "document_type": doctype, "document_name": docname, "subject": message, } notify_to = frappe.db.get_value("User", self.enqueued_by, fieldname="email") enqueue_create_notification([notify_to], notification_doc) def _unlock_reference_doc(self): """ Only execute if self.job_id is defined. """ try: job = Job.fetch(self.job_id, connection=get_redis_conn()) status = job.get_status(refresh=True) exc = job.exc_info except NoSuchJobError: exc = None status = "failed" if status in ("queued", "started"): frappe.msgprint(_("Document in queue for execution!")) return self.queued_doc.unlock() values = ( {"status": "Finished"} if status == "finished" else {"status": "Failed", "exception": exc} ) frappe.db.set_value(self.doctype, self.name, values, update_modified=False) frappe.msgprint(_("Document Unlocked")) @frappe.whitelist() def unlock_doc(self): # NOTE: this can lead to some weird unlocking/locking behaviours. # for example: hitting unlock on a submission could lead to unlocking of another submission # of the same reference document. if self.status != "Queued" and not self.job_id: return self._unlock_reference_doc() def queue_submission(doc: Document, action: str, alert: bool = True): queue = frappe.new_doc("Submission Queue") queue.state = "Queued" queue.ref_doctype = doc.doctype queue.ref_docname = doc.name queue.insert(doc, action) if alert: frappe.msgprint( _("Queued for Submission. You can track the progress over {0}.").format( f"<a href='/app/submission-queue/{queue.name}'><b>here</b></a>" ), indicator="green", alert=True, ) @frappe.whitelist() def get_latest_submissions(doctype, docname): # NOTE: not used creation as orderby intentianlly as we have used update_modified=False everywhere # hence assuming modified will be equal to creation for submission queue documents dt = "Submission Queue" filters = {"ref_doctype": doctype, "ref_docname": docname} return { "latest_submission": frappe.db.get_value(dt, filters), "latest_failed_submission": frappe.db.get_value(dt, filters | {"status": "Failed"}), }
mit
728e0fdfa35ecc0462b135393584b367
28.673575
111
0.696176
3.126092
false
false
false
false
frappe/frappe
frappe/build.py
1
11637
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import os import re import shutil import subprocess from subprocess import getoutput from tempfile import mkdtemp, mktemp from urllib.parse import urlparse import click import psutil from requests import head from requests.exceptions import HTTPError from semantic_version import Version import frappe timestamps = {} app_paths = None sites_path = os.path.abspath(os.getcwd()) WHITESPACE_PATTERN = re.compile(r"\s+") HTML_COMMENT_PATTERN = re.compile(r"(<!--.*?-->)") class AssetsNotDownloadedError(Exception): pass class AssetsDontExistError(HTTPError): pass def download_file(url, prefix): from requests import get filename = urlparse(url).path.split("/")[-1] local_filename = os.path.join(prefix, filename) with get(url, stream=True, allow_redirects=True) as r: r.raise_for_status() with open(local_filename, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return local_filename def build_missing_files(): """Check which files dont exist yet from the assets.json and run build for those files""" missing_assets = [] current_asset_files = [] for type in ["css", "js"]: folder = os.path.join(sites_path, "assets", "frappe", "dist", type) current_asset_files.extend(os.listdir(folder)) development = frappe.local.conf.developer_mode or frappe.local.dev_server build_mode = "development" if development else "production" assets_json = frappe.read_file("assets/assets.json") if assets_json: assets_json = frappe.parse_json(assets_json) for bundle_file, output_file in assets_json.items(): if not output_file.startswith("/assets/frappe"): continue if os.path.basename(output_file) not in current_asset_files: missing_assets.append(bundle_file) if missing_assets: click.secho("\nBuilding missing assets...\n", fg="yellow") files_to_build = ["frappe/" + name for name in missing_assets] bundle(build_mode, files=files_to_build) else: # no assets.json, run full build bundle(build_mode, apps="frappe") def get_assets_link(frappe_head) -> str: tag = getoutput( r"cd ../apps/frappe && git show-ref --tags -d | grep %s | sed -e 's,.*" r" refs/tags/,,' -e 's/\^{}//'" % frappe_head ) if tag: # if tag exists, download assets from github release url = f"https://github.com/frappe/frappe/releases/download/{tag}/assets.tar.gz" else: url = f"http://assets.frappeframework.com/{frappe_head}.tar.gz" if not head(url): reference = f"Release {tag}" if tag else f"Commit {frappe_head}" raise AssetsDontExistError(f"Assets for {reference} don't exist") return url def fetch_assets(url, frappe_head): click.secho("Retrieving assets...", fg="yellow") prefix = mkdtemp(prefix="frappe-assets-", suffix=frappe_head) assets_archive = download_file(url, prefix) if not assets_archive: raise AssetsNotDownloadedError(f"Assets could not be retrived from {url}") click.echo(click.style("✔", fg="green") + f" Downloaded Frappe assets from {url}") return assets_archive def setup_assets(assets_archive): import tarfile directories_created = set() click.secho("\nExtracting assets...\n", fg="yellow") with tarfile.open(assets_archive) as tar: for file in tar: if not file.isdir(): dest = "." + file.name.replace("./frappe-bench/sites", "") asset_directory = os.path.dirname(dest) show = dest.replace("./assets/", "") if asset_directory not in directories_created: if not os.path.exists(asset_directory): os.makedirs(asset_directory, exist_ok=True) directories_created.add(asset_directory) tar.makefile(file, dest) click.echo(click.style("✔", fg="green") + f" Restored {show}") return directories_created def download_frappe_assets(verbose=True): """Downloads and sets up Frappe assets if they exist based on the current commit HEAD. Returns True if correctly setup else returns False. """ frappe_head = getoutput("cd ../apps/frappe && git rev-parse HEAD") if not frappe_head: return False try: url = get_assets_link(frappe_head) assets_archive = fetch_assets(url, frappe_head) setup_assets(assets_archive) build_missing_files() return True except AssetsDontExistError as e: click.secho(str(e), fg="yellow") except Exception as e: # TODO: log traceback in bench.log click.secho(str(e), fg="red") finally: try: shutil.rmtree(os.path.dirname(assets_archive)) except Exception: pass return False def symlink(target, link_name, overwrite=False): """ Create a symbolic link named link_name pointing to target. If link_name exists then FileExistsError is raised, unless overwrite=True. When trying to overwrite a directory, IsADirectoryError is raised. Source: https://stackoverflow.com/a/55742015/10309266 """ if not overwrite: return os.symlink(target, link_name) # os.replace() may fail if files are on different filesystems link_dir = os.path.dirname(link_name) # Create link to target with temporary filename while True: temp_link_name = mktemp(dir=link_dir) # os.* functions mimic as closely as possible system functions # The POSIX symlink() returns EEXIST if link_name already exists # https://pubs.opengroup.org/onlinepubs/9699919799/functions/symlink.html try: os.symlink(target, temp_link_name) break except FileExistsError: pass # Replace link_name with temp_link_name try: # Pre-empt os.replace on a directory with a nicer message if os.path.isdir(link_name): raise IsADirectoryError(f"Cannot symlink over existing directory: '{link_name}'") try: os.replace(temp_link_name, link_name) except AttributeError: os.renames(temp_link_name, link_name) except Exception: if os.path.islink(temp_link_name): os.remove(temp_link_name) raise def setup(): global app_paths, assets_path pymodules = [] for app in frappe.get_all_apps(True): try: pymodules.append(frappe.get_module(app)) except ImportError: pass app_paths = [os.path.dirname(pymodule.__file__) for pymodule in pymodules] assets_path = os.path.join(frappe.local.sites_path, "assets") def bundle( mode, apps=None, hard_link=False, make_copy=False, restore=False, verbose=False, skip_frappe=False, files=None, ): """concat / minify js files""" setup() make_asset_dirs(hard_link=hard_link) mode = "production" if mode == "production" else "build" command = f"yarn run {mode}" if apps: command += f" --apps {apps}" if skip_frappe: command += " --skip_frappe" if files: command += " --files {files}".format(files=",".join(files)) command += " --run-build-command" check_node_executable() frappe_app_path = frappe.get_app_path("frappe", "..") frappe.commands.popen(command, cwd=frappe_app_path, env=get_node_env(), raise_err=True) def watch(apps=None): """watch and rebuild if necessary""" setup() command = "yarn run watch" if apps: command += f" --apps {apps}" live_reload = frappe.utils.cint(os.environ.get("LIVE_RELOAD", frappe.conf.live_reload)) if live_reload: command += " --live-reload" check_node_executable() frappe_app_path = frappe.get_app_path("frappe", "..") frappe.commands.popen(command, cwd=frappe_app_path, env=get_node_env()) def check_node_executable(): node_version = Version(subprocess.getoutput("node -v")[1:]) warn = "⚠️ " if node_version.major < 14: click.echo(f"{warn} Please update your node version to 14") if not shutil.which("yarn"): click.echo(f"{warn} Please install yarn using below command and try again.\nnpm install -g yarn") click.echo() def get_node_env(): node_env = {"NODE_OPTIONS": f"--max_old_space_size={get_safe_max_old_space_size()}"} return node_env def get_safe_max_old_space_size(): safe_max_old_space_size = 0 try: total_memory = psutil.virtual_memory().total / (1024 * 1024) # reference for the safe limit assumption # https://nodejs.org/api/cli.html#cli_max_old_space_size_size_in_megabytes # set minimum value 1GB safe_max_old_space_size = max(1024, int(total_memory * 0.75)) except Exception: pass return safe_max_old_space_size def generate_assets_map(): symlinks = {} for app_name in frappe.get_all_apps(): app_doc_path = None pymodule = frappe.get_module(app_name) app_base_path = os.path.abspath(os.path.dirname(pymodule.__file__)) app_public_path = os.path.join(app_base_path, "public") app_node_modules_path = os.path.join(app_base_path, "..", "node_modules") app_docs_path = os.path.join(app_base_path, "docs") app_www_docs_path = os.path.join(app_base_path, "www", "docs") app_assets = os.path.abspath(app_public_path) app_node_modules = os.path.abspath(app_node_modules_path) # {app}/public > assets/{app} if os.path.isdir(app_assets): symlinks[app_assets] = os.path.join(assets_path, app_name) # {app}/node_modules > assets/{app}/node_modules if os.path.isdir(app_node_modules): symlinks[app_node_modules] = os.path.join(assets_path, app_name, "node_modules") # {app}/docs > assets/{app}_docs if os.path.isdir(app_docs_path): app_doc_path = os.path.join(app_base_path, "docs") elif os.path.isdir(app_www_docs_path): app_doc_path = os.path.join(app_base_path, "www", "docs") if app_doc_path: app_docs = os.path.abspath(app_doc_path) symlinks[app_docs] = os.path.join(assets_path, app_name + "_docs") return symlinks def setup_assets_dirs(): for dir_path in (os.path.join(assets_path, x) for x in ("js", "css")): os.makedirs(dir_path, exist_ok=True) def clear_broken_symlinks(): for path in os.listdir(assets_path): path = os.path.join(assets_path, path) if os.path.islink(path) and not os.path.exists(path): os.remove(path) def unstrip(message: str) -> str: """Pads input string on the right side until the last available column in the terminal""" _len = len(message) try: max_str = os.get_terminal_size().columns except Exception: max_str = 80 if _len < max_str: _rem = max_str - _len else: _rem = max_str % _len return f"{message}{' ' * _rem}" def make_asset_dirs(hard_link=False): setup_assets_dirs() clear_broken_symlinks() symlinks = generate_assets_map() for source, target in symlinks.items(): start_message = unstrip( f"{'Copying assets from' if hard_link else 'Linking'} {source} to {target}" ) fail_message = unstrip(f"Cannot {'copy' if hard_link else 'link'} {source} to {target}") # Used '\r' instead of '\x1b[1K\r' to print entire lines in smaller terminal sizes try: print(start_message, end="\r") link_assets_dir(source, target, hard_link=hard_link) except Exception: print(fail_message, end="\r") click.echo(unstrip(click.style("✔", fg="green") + " Application Assets Linked") + "\n") def link_assets_dir(source, target, hard_link=False): if not os.path.exists(source): return if os.path.exists(target): if os.path.islink(target): os.unlink(target) else: shutil.rmtree(target) if hard_link: shutil.copytree(source, target, dirs_exist_ok=True) else: symlink(source, target, overwrite=True) def scrub_html_template(content): """Returns HTML content with removed whitespace and comments""" # remove whitespace to a single space content = WHITESPACE_PATTERN.sub(" ", content) # strip comments content = HTML_COMMENT_PATTERN.sub("", content) return content.replace("'", "'") def html_to_js_template(path, content): """returns HTML template content as Javascript code, adding it to `frappe.templates`""" return """frappe.templates["{key}"] = '{content}';\n""".format( key=path.rsplit("/", 1)[-1][:-5], content=scrub_html_template(content) )
mit
8c71c7d3542e8de75cc5e51f60be3fe0
26.552133
99
0.698977
3.007501
false
false
false
false
frappe/frappe
frappe/patches/v12_0/move_timeline_links_to_dynamic_links.py
3
1949
import frappe def execute(): communications = frappe.db.sql( """ SELECT `tabCommunication`.name, `tabCommunication`.creation, `tabCommunication`.modified, `tabCommunication`.modified_by,`tabCommunication`.timeline_doctype, `tabCommunication`.timeline_name, `tabCommunication`.link_doctype, `tabCommunication`.link_name FROM `tabCommunication` WHERE `tabCommunication`.communication_medium='Email' """, as_dict=True, ) name = 1000000000 values = [] for count, communication in enumerate(communications): counter = 1 if communication.timeline_doctype and communication.timeline_name: name += 1 values.append( """({}, "{}", "timeline_links", "Communication", "{}", "{}", "{}", "{}", "{}", "{}")""".format( counter, str(name), frappe.db.escape(communication.name), frappe.db.escape(communication.timeline_doctype), frappe.db.escape(communication.timeline_name), communication.creation, communication.modified, communication.modified_by, ) ) counter += 1 if communication.link_doctype and communication.link_name: name += 1 values.append( """({}, "{}", "timeline_links", "Communication", "{}", "{}", "{}", "{}", "{}", "{}")""".format( counter, str(name), frappe.db.escape(communication.name), frappe.db.escape(communication.link_doctype), frappe.db.escape(communication.link_name), communication.creation, communication.modified, communication.modified_by, ) ) if values and (count % 10000 == 0 or count == len(communications) - 1): frappe.db.sql( """ INSERT INTO `tabCommunication Link` (`idx`, `name`, `parentfield`, `parenttype`, `parent`, `link_doctype`, `link_name`, `creation`, `modified`, `modified_by`) VALUES {} """.format( ", ".join([d for d in values]) ) ) values = [] frappe.db.add_index("Communication Link", ["link_doctype", "link_name"])
mit
07cd21b454de37ed0ba335cbbf40fca4
28.530303
104
0.640328
3.41331
false
false
false
false
frappe/frappe
frappe/utils/dashboard.py
2
3585
# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import os from functools import wraps from os.path import join import frappe from frappe import _ from frappe.modules.import_file import import_file_by_path from frappe.utils import cint, get_link_to_form def cache_source(function): @wraps(function) def wrapper(*args, **kwargs): if kwargs.get("chart_name"): chart = frappe.get_doc("Dashboard Chart", kwargs.get("chart_name")) else: chart = kwargs.get("chart") no_cache = kwargs.get("no_cache") if no_cache: return function(chart=chart, no_cache=no_cache) chart_name = frappe.parse_json(chart).name cache_key = f"chart-data:{chart_name}" if int(kwargs.get("refresh") or 0): results = generate_and_cache_results(kwargs, function, cache_key, chart) else: cached_results = frappe.cache().get_value(cache_key) if cached_results: results = frappe.parse_json(frappe.safe_decode(cached_results)) else: results = generate_and_cache_results(kwargs, function, cache_key, chart) return results return wrapper def generate_and_cache_results(args, function, cache_key, chart): try: args = frappe._dict(args) results = function( chart_name=args.chart_name, filters=args.filters or None, from_date=args.from_date or None, to_date=args.to_date or None, time_interval=args.time_interval or None, timespan=args.timespan or None, heatmap_year=args.heatmap_year or None, ) except TypeError as e: if str(e) == "'NoneType' object is not iterable": # Probably because of invalid link filter # # Note: Do not try to find the right way of doing this because # it results in an inelegant & inefficient solution # ref: https://github.com/frappe/frappe/pull/9403 frappe.throw( _("Please check the filter values set for Dashboard Chart: {}").format( get_link_to_form(chart.doctype, chart.name) ), title=_("Invalid Filter Value"), ) return else: raise if not frappe.flags.read_only: frappe.db.set_value( "Dashboard Chart", args.chart_name, "last_synced_on", frappe.utils.now(), update_modified=False ) return results def get_dashboards_with_link(docname, doctype): dashboards = [] links = [] if doctype == "Dashboard Chart": links = frappe.get_all("Dashboard Chart Link", fields=["parent"], filters={"chart": docname}) elif doctype == "Number Card": links = frappe.get_all("Number Card Link", fields=["parent"], filters={"card": docname}) dashboards = [link.parent for link in links] return dashboards def sync_dashboards(app=None): """Import, overwrite dashboards from `[app]/[app]_dashboard`""" apps = [app] if app else frappe.get_installed_apps() for app_name in apps: print(f"Updating Dashboard for {app_name}") for module_name in frappe.local.app_modules.get(app_name) or []: frappe.flags.in_import = True make_records_in_module(app_name, module_name) frappe.flags.in_import = False def make_records_in_module(app, module): dashboards_path = frappe.get_module_path(module, f"{module}_dashboard") charts_path = frappe.get_module_path(module, "dashboard chart") cards_path = frappe.get_module_path(module, "number card") paths = [dashboards_path, charts_path, cards_path] for path in paths: make_records(path) def make_records(path, filters=None): if os.path.isdir(path): for fname in os.listdir(path): if os.path.isdir(join(path, fname)): if fname == "__pycache__": continue import_file_by_path("{path}/{fname}/{fname}.json".format(path=path, fname=fname))
mit
f86822a5d580e12ef1d86fe9508a8ba0
30.173913
98
0.70265
3.150264
false
false
false
false
simpeg/discretize
tests/base/test_tensor_omf.py
1
3923
import numpy as np import unittest import discretize try: import omf except ImportError: has_omf = False else: has_omf = True if has_omf: from discretize.mixins.omf_mod import unravel_data_array, ravel_data_array class TestTensorMeshOMF(unittest.TestCase): def setUp(self): h = np.ones(16) mesh = discretize.TensorMesh([h, 2 * h, 3 * h]) self.mesh = mesh def test_to_omf(self): mesh = self.mesh vec = np.arange(mesh.nC) models = {"arange": vec} omf_element = mesh.to_omf(models) geom = omf_element.geometry # Check geometry self.assertEqual(mesh.nC, geom.num_cells) self.assertEqual(mesh.nN, geom.num_nodes) self.assertTrue(np.allclose(mesh.hx, geom.tensor_u)) self.assertTrue(np.allclose(mesh.hy, geom.tensor_v)) self.assertTrue(np.allclose(mesh.hz, geom.tensor_w)) self.assertTrue(np.allclose(mesh.axis_u, geom.axis_u)) self.assertTrue(np.allclose(mesh.axis_v, geom.axis_v)) self.assertTrue(np.allclose(mesh.axis_w, geom.axis_w)) self.assertTrue(np.allclose(mesh.x0, geom.origin)) # Check data arrays self.assertEqual(len(models.keys()), len(omf_element.data)) for i in range(len(omf_element.data)): name = list(models.keys())[i] scalar_data = omf_element.data[i] self.assertEqual(name, scalar_data.name) arr = unravel_data_array( np.array(scalar_data.array), mesh.nCx, mesh.nCy, mesh.nCz ) self.assertTrue(np.allclose(models[name], arr)) def test_from_omf(self): omf_element = omf.VolumeElement( name="vol_ir", geometry=omf.VolumeGridGeometry( axis_u=[1, 1, 0], axis_v=[0, 0, 1], axis_w=[1, -1, 0], tensor_u=np.ones(10).astype(float), tensor_v=np.ones(15).astype(float), tensor_w=np.ones(20).astype(float), origin=[10.0, 10.0, -10], ), data=[ omf.ScalarData( name="Random Data", location="cells", array=np.random.rand(10, 15, 20).flatten(), ) ], ) # Make a discretize mesh mesh, models = discretize.TensorMesh.from_omf(omf_element) geom = omf_element.geometry # Check geometry self.assertEqual(mesh.nC, geom.num_cells) self.assertEqual(mesh.nN, geom.num_nodes) self.assertTrue(np.allclose(mesh.hx, geom.tensor_u)) self.assertTrue(np.allclose(mesh.hy, geom.tensor_v)) self.assertTrue(np.allclose(mesh.hz, geom.tensor_w)) self.assertTrue(np.allclose(mesh.axis_u, geom.axis_u)) self.assertTrue(np.allclose(mesh.axis_v, geom.axis_v)) self.assertTrue(np.allclose(mesh.axis_w, geom.axis_w)) self.assertTrue(np.allclose(mesh.x0, geom.origin)) # Check data arrays self.assertEqual(len(models.keys()), len(omf_element.data)) for i in range(len(omf_element.data)): name = list(models.keys())[i] scalar_data = omf_element.data[i] self.assertEqual(name, scalar_data.name) arr = ravel_data_array( models[name], len(geom.tensor_u), len(geom.tensor_v), len(geom.tensor_w), ) self.assertTrue(np.allclose(np.array(scalar_data.array), arr)) if __name__ == "__main__": unittest.main()
mit
a764968bb81433f0abe8f1ced87c3d76
36.721154
78
0.520265
3.750478
false
true
false
false
frappe/frappe
frappe/core/report/database_storage_usage_by_tables/database_storage_usage_by_tables.py
2
1323
# Copyright (c) 2022, Frappe Technologies and contributors # For license information, please see license.txt import frappe COLUMNS = [ {"label": "Table", "fieldname": "table", "fieldtype": "Data", "width": 200}, {"label": "Size (MB)", "fieldname": "size", "fieldtype": "Float"}, {"label": "Data (MB)", "fieldname": "data_size", "fieldtype": "Float"}, {"label": "Index (MB)", "fieldname": "index_size", "fieldtype": "Float"}, ] def execute(filters=None): frappe.only_for("System Manager") data = frappe.db.multisql( { "mariadb": """ SELECT table_name AS `table`, round(((data_length + index_length) / 1024 / 1024), 2) `size`, round((data_length / 1024 / 1024), 2) as data_size, round((index_length / 1024 / 1024), 2) as index_size FROM information_schema.TABLES ORDER BY (data_length + index_length) DESC; """, "postgres": """ SELECT table_name as "table", round(pg_total_relation_size(quote_ident(table_name)) / 1024 / 1024, 2) as "size", round(pg_relation_size(quote_ident(table_name)) / 1024 / 1024, 2) as "data_size", round(pg_indexes_size(quote_ident(table_name)) / 1024 / 1024, 2) as "index_size" FROM information_schema.tables WHERE table_schema = 'public' ORDER BY 2 DESC; """, }, as_dict=1, ) return COLUMNS, data
mit
0204ee8c4cc8530af6ec742fc243cf85
32.075
88
0.624339
3.055427
false
false
false
false
richardkiss/pycoin
pycoin/services/chain_so.py
1
1577
import io import json from .agent import urlopen from pycoin.coins.bitcoin.Tx import Tx from pycoin.encoding.hexbytes import b2h_rev, h2b, h2b_rev from pycoin.networks.default import get_current_netcode class ChainSoProvider(object): def __init__(self, netcode=None): NETWORK_PATHS = { "BTC": "BTC", "XTN": "BTCTEST", "DOGE": "DOGE", "XDT": "DOGETEST", } if netcode is None: netcode = get_current_netcode() self.network_path = NETWORK_PATHS.get(netcode) def base_url(self, method, args): return "https://chain.so/api/v2/%s/%s/%s" % (method, self.network_path, args) def spendables_for_address(self, address): """ Return a list of Spendable objects for the given bitcoin address. """ spendables = [] r = json.loads(urlopen(self.base_url('get_tx_unspent', address)).read().decode("utf8")) for u in r['data']['txs']: coin_value = int(float(u['value']) * 100000000) script = h2b(u["script_hex"]) previous_hash = h2b_rev(u["txid"]) previous_index = u["output_no"] spendables.append(Tx.Spendable(coin_value, script, previous_hash, previous_index)) return spendables def tx_for_tx_hash(self, tx_hash): "Get a Tx by its hash." url = self.base_url("get_tx", b2h_rev(tx_hash)) r = json.loads(urlopen(url).read().decode("utf8")) tx = Tx.parse(io.BytesIO(h2b(r.get("data").get("tx_hex")))) return tx
mit
0d1b001f07a590438c2f022e17c99f37
31.854167
95
0.579581
3.292276
false
false
false
false
richardkiss/pycoin
pycoin/solve/constraints.py
1
4845
import functools import pdb @functools.total_ordering class Atom(object): def __init__(self, name): self.name = name def dependencies(self): return frozenset([self]) def __len__(self): # HACK to allow MAX_BLOB_LENGTH comparison to succeed return 0 def __eq__(self, other): if isinstance(other, Atom): return self.name == other.name return False def __lt__(self, other): if isinstance(other, Atom): return self.name < other.name return False def __hash__(self): return self.name.__hash__() def __repr__(self): return "<%s>" % self.name class Operator(Atom): def __init__(self, op_name, *args): self._op_name = op_name self._args = tuple(args) s = set() for a in self._args: if hasattr(a, "dependencies"): s.update(a.dependencies()) self._dependencies = frozenset(s) def __hash__(self): return self._args.__hash__() def __eq__(self, other): if isinstance(other, Operator): return self._op_name, self._args == other._op_name, other._args return False def dependencies(self): return self._dependencies def __repr__(self): return "(%s %s)" % (self._op_name, ' '.join(repr(a) for a in self._args)) def make_op_if(constraints): def my_op_if(vm): pdb.set_trace() t = vm.stack.pop() t = Operator('IF', t) vm.stack.append(t) return my_op_if def make_op_hash160(constraints): def my_op_hash160(vm): t = vm.stack.pop() t = Operator('HASH160', t) vm.stack.append(t) my_op_hash160.stack_size = 1 return my_op_hash160 def make_op_equal(constraints): def my_op_equal(vm): t1 = vm.stack.pop() t2 = vm.stack.pop() c = Operator('EQUAL', t1, t2) vm.append(c) my_op_equal.stack_size = 2 return my_op_equal def make_op_equalverify(constraints): def my_op_equalverify(vm): t1 = vm.stack.pop() t2 = vm.stack.pop() c = Operator('EQUAL', t1, t2) constraints.append(c) my_op_equalverify.stack_size = 2 return my_op_equalverify def make_op_checksig(constraints): def my_op_checksig(vm): def sighash_f(signature_type): return vm.signature_for_hash_type_f(signature_type, [], vm) t1 = vm.stack.pop() t2 = vm.stack.pop() t = Operator('SIGNATURES_CORRECT', [t1], [t2], sighash_f) constraints.append(Operator('IS_PUBKEY', t1)) constraints.append(Operator('IS_SIGNATURE', t2)) vm.stack.append(t) return my_op_checksig def make_op_checkmultisig(constraints): def my_op_checkmultisig(vm): def sighash_f(signature_type): return vm.signature_for_hash_type_f(signature_type, [], vm) key_count = vm.IntStreamer.int_from_script_bytes(vm.stack.pop(), require_minimal=False) public_pair_blobs = [] for i in range(key_count): constraints.append(Operator('IS_PUBKEY', vm.stack[-1])) public_pair_blobs.append(vm.stack.pop()) signature_count = vm.IntStreamer.int_from_script_bytes(vm.stack.pop(), require_minimal=False) sig_blobs = [] for i in range(signature_count): constraints.append(Operator('IS_SIGNATURE', vm.stack[-1])) sig_blobs.append(vm.stack.pop()) t1 = vm.stack.pop() constraints.append(Operator('EQUAL', t1, b'')) t = Operator('SIGNATURES_CORRECT', public_pair_blobs, sig_blobs, sighash_f) vm.stack.append(t) return my_op_checkmultisig def make_traceback_f(constraints, int_for_opcode_f, reset_stack_f): TWEAKED_OPCODES = ( ("OP_HASH160", make_op_hash160), ("OP_EQUALVERIFY", make_op_equalverify), ("OP_EQUAL", make_op_equal), ("OP_CHECKSIG", make_op_checksig), ("OP_CHECKMULTISIG", make_op_checkmultisig), ) MY_OPCODES = {int_for_opcode_f(k): v(constraints) for k, v in TWEAKED_OPCODES} def prelaunch(vmc): if not vmc.is_solution_script: # reset stack vmc.stack = reset_stack_f(vmc.stack) def traceback_f(opcode, data, pc, vm): f = MY_OPCODES.get(opcode) if f is None: return stack_size = getattr(f, "stack_size", 0) if stack_size and all(not isinstance(v, Atom) for v in vm.stack[-stack_size:]): return return f def postscript(vmc): if not vmc.is_solution_script: if isinstance(vmc.stack[-1], Atom): constraints.append(vmc.stack[-1]) vmc.stack = [vmc.VM_TRUE] traceback_f.prelaunch = prelaunch traceback_f.postscript = postscript return traceback_f
mit
12905749f5da05984070d5be6ab681b1
27.333333
101
0.579154
3.409571
false
false
false
false
frappe/frappe
frappe/desk/doctype/note/test_note.py
2
2314
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors # License: MIT. See LICENSE import frappe from frappe.tests.utils import FrappeTestCase test_records = frappe.get_test_records("Note") class TestNote(FrappeTestCase): def insert_note(self): frappe.db.delete("Version") frappe.db.delete("Note") frappe.db.delete("Note Seen By") return frappe.get_doc( dict(doctype="Note", title="test note", content="test note content") ).insert() def test_version(self): note = self.insert_note() note.title = "test note 1" note.content = "1" note.save(ignore_version=False) version = frappe.get_doc("Version", dict(docname=note.name)) data = version.get_data() self.assertTrue(("title", "test note", "test note 1"), data["changed"]) self.assertTrue(("content", "test note content", "1"), data["changed"]) def test_rows(self): note = self.insert_note() # test add note.append("seen_by", {"user": "Administrator"}) note.save(ignore_version=False) version = frappe.get_doc("Version", dict(docname=note.name)) data = version.get_data() self.assertEqual(len(data.get("added")), 1) self.assertEqual(len(data.get("removed")), 0) self.assertEqual(len(data.get("changed")), 0) for row in data.get("added"): self.assertEqual(row[0], "seen_by") self.assertEqual(row[1]["user"], "Administrator") # test row change note.seen_by[0].user = "Guest" note.save(ignore_version=False) version = frappe.get_doc("Version", dict(docname=note.name)) data = version.get_data() self.assertEqual(len(data.get("row_changed")), 1) for row in data.get("row_changed"): self.assertEqual(row[0], "seen_by") self.assertEqual(row[1], 0) self.assertEqual(row[2], note.seen_by[0].name) self.assertEqual(row[3], [["user", "Administrator", "Guest"]]) # test remove note.seen_by = [] note.save(ignore_version=False) version = frappe.get_doc("Version", dict(docname=note.name)) data = version.get_data() self.assertEqual(len(data.get("removed")), 1) for row in data.get("removed"): self.assertEqual(row[0], "seen_by") self.assertEqual(row[1]["user"], "Guest") # self.assertTrue(('title', 'test note', 'test note 1'), data['changed']) # self.assertTrue(('content', 'test note content', '1'), data['changed'])
mit
1d95f00c6345b77c57e303bcca912cab
29.051948
85
0.674589
3.073041
false
true
false
false
frappe/frappe
frappe/printing/doctype/letter_head/letter_head.py
2
3081
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import flt, is_image class LetterHead(Document): def before_insert(self): # for better UX, let user set from attachment self.source = "Image" def validate(self): self.set_image() self.validate_disabled_and_default() def validate_disabled_and_default(self): if self.disabled and self.is_default: frappe.throw(_("Letter Head cannot be both disabled and default")) if not self.is_default and not self.disabled: if not frappe.db.exists("Letter Head", dict(is_default=1)): self.is_default = 1 def set_image(self): if self.source == "Image": self.set_image_as_html( field="image", width="image_width", height="image_height", align="align", html_field="content", dimension_prefix="image_", success_msg=_("Header HTML set from attachment {0}").format(self.image), failure_msg=_("Please attach an image file to set HTML for Letter Head."), ) if self.footer_source == "Image": self.set_image_as_html( field="footer_image", width="footer_image_width", height="footer_image_height", align="footer_align", html_field="footer", dimension_prefix="footer_image_", success_msg=_("Footer HTML set from attachment {0}").format(self.footer_image), failure_msg=_("Please attach an image file to set HTML for Footer."), ) def set_image_as_html( self, field, width, height, dimension_prefix, align, html_field, success_msg, failure_msg ): if not self.get(field) or not is_image(self.get(field)): frappe.msgprint(failure_msg, alert=True, indicator="orange") return self.set(width, flt(self.get(width))) self.set(height, flt(self.get(height))) # To preserve the aspect ratio of the image, apply constraints only on # the greater dimension and allow the other to scale accordingly dimension = "width" if self.get(width) > self.get(height) else "height" dimension_value = self.get(f"{dimension_prefix}{dimension}") if not dimension_value: dimension_value = "" self.set( html_field, f"""<div style="text-align: {self.get(align, "").lower()};"> <img src="{self.get(field)}" alt="{self.get("name")}" {dimension}="{dimension_value}" style="{dimension}: {dimension_value}px;"> </div>""", ) frappe.msgprint(success_msg, alert=True) def on_update(self): self.set_as_default() # clear the cache so that the new letter head is uploaded frappe.clear_cache() def set_as_default(self): from frappe.utils import set_default if self.is_default: frappe.db.sql("update `tabLetter Head` set is_default=0 where name != %s", self.name) set_default("letter_head", self.name) # update control panel - so it loads new letter directly frappe.db.set_default("default_letter_head_content", self.content) else: frappe.defaults.clear_default("letter_head", self.name) frappe.defaults.clear_default("default_letter_head_content", self.content)
mit
99ec1eb3cba982ab491732944cd3a903
30.438776
91
0.694255
3.25
false
false
false
false