Best JavaScript code snippet using wpt
users_api.py
Source:users_api.py
1# coding: utf-82"""3 MarketPay API4 API for Smart Contracts and Payments5 OpenAPI spec version: v2.016 7 Generated by: https://github.com/swagger-api/swagger-codegen.git8"""9from __future__ import absolute_import10import sys11import os12import re13# python 2 and python 3 compatibility library14from six import iteritems15from ..configuration import Configuration16from ..api_client import ApiClient17class UsersApi(object):18 """19 NOTE: This class is auto generated by the swagger code generator program.20 Do not edit the class manually.21 Ref: https://github.com/swagger-api/swagger-codegen22 """23 def __init__(self, api_client=None):24 config = Configuration()25 if api_client:26 self.api_client = api_client27 else:28 if not config.api_client:29 config.api_client = ApiClient()30 self.api_client = config.api_client31 def users_get(self, user_id, **kwargs):32 """33 View a User34 A User can be \"Natural\" or \"Legal\". With a UserId, you are able to: Fetch a user and get their details List all the wallets of a user Get all your users in a list35 This method makes a synchronous HTTP request by default. To make an36 asynchronous HTTP request, please define a `callback` function37 to be invoked when receiving the response.38 >>> def callback_function(response):39 >>> pprint(response)40 >>>41 >>> thread = api.users_get(user_id, callback=callback_function)42 :param callback function: The callback function43 for asynchronous request. (optional)44 :param int user_id: The Id of a user (required)45 :return: UserResponse46 If the method is called asynchronously,47 returns the request thread.48 """49 kwargs['_return_http_data_only'] = True50 if kwargs.get('callback'):51 return self.users_get_with_http_info(user_id, **kwargs)52 else:53 (data) = self.users_get_with_http_info(user_id, **kwargs)54 return data55 def users_get_with_http_info(self, user_id, **kwargs):56 """57 View a User58 A User can be \"Natural\" or \"Legal\". With a UserId, you are able to: Fetch a user and get their details List all the wallets of a user Get all your users in a list59 This method makes a synchronous HTTP request by default. To make an60 asynchronous HTTP request, please define a `callback` function61 to be invoked when receiving the response.62 >>> def callback_function(response):63 >>> pprint(response)64 >>>65 >>> thread = api.users_get_with_http_info(user_id, callback=callback_function)66 :param callback function: The callback function67 for asynchronous request. (optional)68 :param int user_id: The Id of a user (required)69 :return: UserResponse70 If the method is called asynchronously,71 returns the request thread.72 """73 all_params = ['user_id']74 all_params.append('callback')75 all_params.append('_return_http_data_only')76 all_params.append('_preload_content')77 all_params.append('_request_timeout')78 params = locals()79 for key, val in iteritems(params['kwargs']):80 if key not in all_params:81 raise TypeError(82 "Got an unexpected keyword argument '%s'"83 " to method users_get" % key84 )85 params[key] = val86 del params['kwargs']87 # verify the required parameter 'user_id' is set88 if ('user_id' not in params) or (params['user_id'] is None):89 raise ValueError("Missing the required parameter `user_id` when calling `users_get`")90 collection_formats = {}91 path_params = {}92 if 'user_id' in params:93 path_params['UserId'] = params['user_id']94 query_params = []95 header_params = {}96 form_params = []97 local_var_files = {}98 body_params = None99 # HTTP header `Accept`100 header_params['Accept'] = self.api_client.\101 select_header_accept(['text/plain', 'application/json', 'text/json'])102 # Authentication setting103 auth_settings = ['oauth2']104 return self.api_client.call_api('/v2.01/Users/{UserId}', 'GET',105 path_params,106 query_params,107 header_params,108 body=body_params,109 post_params=form_params,110 files=local_var_files,111 response_type='UserResponse',112 auth_settings=auth_settings,113 callback=params.get('callback'),114 _return_http_data_only=params.get('_return_http_data_only'),115 _preload_content=params.get('_preload_content', True),116 _request_timeout=params.get('_request_timeout'),117 collection_formats=collection_formats)118 def users_get_bank_account(self, user_id, bank_account_id, **kwargs):119 """120 View a Bank Account121 122 This method makes a synchronous HTTP request by default. To make an123 asynchronous HTTP request, please define a `callback` function124 to be invoked when receiving the response.125 >>> def callback_function(response):126 >>> pprint(response)127 >>>128 >>> thread = api.users_get_bank_account(user_id, bank_account_id, callback=callback_function)129 :param callback function: The callback function130 for asynchronous request. (optional)131 :param int user_id: The Id of a user (required)132 :param int bank_account_id: The Id of a bank account (required)133 :return: BankAccountResponse134 If the method is called asynchronously,135 returns the request thread.136 """137 kwargs['_return_http_data_only'] = True138 if kwargs.get('callback'):139 return self.users_get_bank_account_with_http_info(user_id, bank_account_id, **kwargs)140 else:141 (data) = self.users_get_bank_account_with_http_info(user_id, bank_account_id, **kwargs)142 return data143 def users_get_bank_account_with_http_info(self, user_id, bank_account_id, **kwargs):144 """145 View a Bank Account146 147 This method makes a synchronous HTTP request by default. To make an148 asynchronous HTTP request, please define a `callback` function149 to be invoked when receiving the response.150 >>> def callback_function(response):151 >>> pprint(response)152 >>>153 >>> thread = api.users_get_bank_account_with_http_info(user_id, bank_account_id, callback=callback_function)154 :param callback function: The callback function155 for asynchronous request. (optional)156 :param int user_id: The Id of a user (required)157 :param int bank_account_id: The Id of a bank account (required)158 :return: BankAccountResponse159 If the method is called asynchronously,160 returns the request thread.161 """162 all_params = ['user_id', 'bank_account_id']163 all_params.append('callback')164 all_params.append('_return_http_data_only')165 all_params.append('_preload_content')166 all_params.append('_request_timeout')167 params = locals()168 for key, val in iteritems(params['kwargs']):169 if key not in all_params:170 raise TypeError(171 "Got an unexpected keyword argument '%s'"172 " to method users_get_bank_account" % key173 )174 params[key] = val175 del params['kwargs']176 # verify the required parameter 'user_id' is set177 if ('user_id' not in params) or (params['user_id'] is None):178 raise ValueError("Missing the required parameter `user_id` when calling `users_get_bank_account`")179 # verify the required parameter 'bank_account_id' is set180 if ('bank_account_id' not in params) or (params['bank_account_id'] is None):181 raise ValueError("Missing the required parameter `bank_account_id` when calling `users_get_bank_account`")182 collection_formats = {}183 path_params = {}184 if 'user_id' in params:185 path_params['UserId'] = params['user_id']186 if 'bank_account_id' in params:187 path_params['BankAccountId'] = params['bank_account_id']188 query_params = []189 header_params = {}190 form_params = []191 local_var_files = {}192 body_params = None193 # HTTP header `Accept`194 header_params['Accept'] = self.api_client.\195 select_header_accept(['text/plain', 'application/json', 'text/json'])196 # Authentication setting197 auth_settings = ['oauth2']198 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/{BankAccountId}', 'GET',199 path_params,200 query_params,201 header_params,202 body=body_params,203 post_params=form_params,204 files=local_var_files,205 response_type='BankAccountResponse',206 auth_settings=auth_settings,207 callback=params.get('callback'),208 _return_http_data_only=params.get('_return_http_data_only'),209 _preload_content=params.get('_preload_content', True),210 _request_timeout=params.get('_request_timeout'),211 collection_formats=collection_formats)212 def users_get_bank_account_list(self, user_id, **kwargs):213 """214 List Bank Accounts for a User215 216 This method makes a synchronous HTTP request by default. To make an217 asynchronous HTTP request, please define a `callback` function218 to be invoked when receiving the response.219 >>> def callback_function(response):220 >>> pprint(response)221 >>>222 >>> thread = api.users_get_bank_account_list(user_id, callback=callback_function)223 :param callback function: The callback function224 for asynchronous request. (optional)225 :param int user_id: The Id of a user (required)226 :param int page: The page number of results you wish to return227 :param int per_page: The number of results to return per page228 :return: list[BankAccountResponse]229 If the method is called asynchronously,230 returns the request thread.231 """232 kwargs['_return_http_data_only'] = True233 if kwargs.get('callback'):234 return self.users_get_bank_account_list_with_http_info(user_id, **kwargs)235 else:236 (data) = self.users_get_bank_account_list_with_http_info(user_id, **kwargs)237 return data238 def users_get_bank_account_list_with_http_info(self, user_id, **kwargs):239 """240 List Bank Accounts for a User241 242 This method makes a synchronous HTTP request by default. To make an243 asynchronous HTTP request, please define a `callback` function244 to be invoked when receiving the response.245 >>> def callback_function(response):246 >>> pprint(response)247 >>>248 >>> thread = api.users_get_bank_account_list_with_http_info(user_id, callback=callback_function)249 :param callback function: The callback function250 for asynchronous request. (optional)251 :param int user_id: The Id of a user (required)252 :param int page: The page number of results you wish to return253 :param int per_page: The number of results to return per page254 :return: list[BankAccountResponse]255 If the method is called asynchronously,256 returns the request thread.257 """258 all_params = ['user_id', 'page', 'per_page']259 all_params.append('callback')260 all_params.append('_return_http_data_only')261 all_params.append('_preload_content')262 all_params.append('_request_timeout')263 params = locals()264 for key, val in iteritems(params['kwargs']):265 if key not in all_params:266 raise TypeError(267 "Got an unexpected keyword argument '%s'"268 " to method users_get_bank_account_list" % key269 )270 params[key] = val271 del params['kwargs']272 # verify the required parameter 'user_id' is set273 if ('user_id' not in params) or (params['user_id'] is None):274 raise ValueError("Missing the required parameter `user_id` when calling `users_get_bank_account_list`")275 collection_formats = {}276 path_params = {}277 if 'user_id' in params:278 path_params['UserId'] = params['user_id']279 query_params = []280 if 'page' in params:281 query_params.append(('Page', params['page']))282 if 'per_page' in params:283 query_params.append(('Per_Page', params['per_page']))284 header_params = {}285 form_params = []286 local_var_files = {}287 body_params = None288 # HTTP header `Accept`289 header_params['Accept'] = self.api_client.\290 select_header_accept(['text/plain', 'application/json', 'text/json'])291 # Authentication setting292 auth_settings = ['oauth2']293 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts', 'GET',294 path_params,295 query_params,296 header_params,297 body=body_params,298 post_params=form_params,299 files=local_var_files,300 response_type='list[BankAccountResponse]',301 auth_settings=auth_settings,302 callback=params.get('callback'),303 _return_http_data_only=params.get('_return_http_data_only'),304 _preload_content=params.get('_preload_content', True),305 _request_timeout=params.get('_request_timeout'),306 collection_formats=collection_formats)307 def users_get_card_list(self, user_id, **kwargs):308 """309 List Cards for a User310 311 This method makes a synchronous HTTP request by default. To make an312 asynchronous HTTP request, please define a `callback` function313 to be invoked when receiving the response.314 >>> def callback_function(response):315 >>> pprint(response)316 >>>317 >>> thread = api.users_get_card_list(user_id, callback=callback_function)318 :param callback function: The callback function319 for asynchronous request. (optional)320 :param int user_id: The Id of a user (required)321 :param int page: The page number of results you wish to return322 :param int per_page: The number of results to return per page323 :return: list[CardResponse]324 If the method is called asynchronously,325 returns the request thread.326 """327 kwargs['_return_http_data_only'] = True328 if kwargs.get('callback'):329 return self.users_get_card_list_with_http_info(user_id, **kwargs)330 else:331 (data) = self.users_get_card_list_with_http_info(user_id, **kwargs)332 return data333 def users_get_card_list_with_http_info(self, user_id, **kwargs):334 """335 List Cards for a User336 337 This method makes a synchronous HTTP request by default. To make an338 asynchronous HTTP request, please define a `callback` function339 to be invoked when receiving the response.340 >>> def callback_function(response):341 >>> pprint(response)342 >>>343 >>> thread = api.users_get_card_list_with_http_info(user_id, callback=callback_function)344 :param callback function: The callback function345 for asynchronous request. (optional)346 :param int user_id: The Id of a user (required)347 :param int page: The page number of results you wish to return348 :param int per_page: The number of results to return per page349 :return: list[CardResponse]350 If the method is called asynchronously,351 returns the request thread.352 """353 all_params = ['user_id', 'page', 'per_page']354 all_params.append('callback')355 all_params.append('_return_http_data_only')356 all_params.append('_preload_content')357 all_params.append('_request_timeout')358 params = locals()359 for key, val in iteritems(params['kwargs']):360 if key not in all_params:361 raise TypeError(362 "Got an unexpected keyword argument '%s'"363 " to method users_get_card_list" % key364 )365 params[key] = val366 del params['kwargs']367 # verify the required parameter 'user_id' is set368 if ('user_id' not in params) or (params['user_id'] is None):369 raise ValueError("Missing the required parameter `user_id` when calling `users_get_card_list`")370 collection_formats = {}371 path_params = {}372 if 'user_id' in params:373 path_params['UserId'] = params['user_id']374 query_params = []375 if 'page' in params:376 query_params.append(('Page', params['page']))377 if 'per_page' in params:378 query_params.append(('Per_Page', params['per_page']))379 header_params = {}380 form_params = []381 local_var_files = {}382 body_params = None383 # HTTP header `Accept`384 header_params['Accept'] = self.api_client.\385 select_header_accept(['text/plain', 'application/json', 'text/json'])386 # Authentication setting387 auth_settings = ['oauth2']388 return self.api_client.call_api('/v2.01/Users/{UserId}/cards', 'GET',389 path_params,390 query_params,391 header_params,392 body=body_params,393 post_params=form_params,394 files=local_var_files,395 response_type='list[CardResponse]',396 auth_settings=auth_settings,397 callback=params.get('callback'),398 _return_http_data_only=params.get('_return_http_data_only'),399 _preload_content=params.get('_preload_content', True),400 _request_timeout=params.get('_request_timeout'),401 collection_formats=collection_formats)402 def users_get_legal(self, user_id, **kwargs):403 """404 View a Legal User405 406 This method makes a synchronous HTTP request by default. To make an407 asynchronous HTTP request, please define a `callback` function408 to be invoked when receiving the response.409 >>> def callback_function(response):410 >>> pprint(response)411 >>>412 >>> thread = api.users_get_legal(user_id, callback=callback_function)413 :param callback function: The callback function414 for asynchronous request. (optional)415 :param int user_id: The Id of a legal user (required)416 :return: UserLegalResponse417 If the method is called asynchronously,418 returns the request thread.419 """420 kwargs['_return_http_data_only'] = True421 if kwargs.get('callback'):422 return self.users_get_legal_with_http_info(user_id, **kwargs)423 else:424 (data) = self.users_get_legal_with_http_info(user_id, **kwargs)425 return data426 def users_get_legal_with_http_info(self, user_id, **kwargs):427 """428 View a Legal User429 430 This method makes a synchronous HTTP request by default. To make an431 asynchronous HTTP request, please define a `callback` function432 to be invoked when receiving the response.433 >>> def callback_function(response):434 >>> pprint(response)435 >>>436 >>> thread = api.users_get_legal_with_http_info(user_id, callback=callback_function)437 :param callback function: The callback function438 for asynchronous request. (optional)439 :param int user_id: The Id of a legal user (required)440 :return: UserLegalResponse441 If the method is called asynchronously,442 returns the request thread.443 """444 all_params = ['user_id']445 all_params.append('callback')446 all_params.append('_return_http_data_only')447 all_params.append('_preload_content')448 all_params.append('_request_timeout')449 params = locals()450 for key, val in iteritems(params['kwargs']):451 if key not in all_params:452 raise TypeError(453 "Got an unexpected keyword argument '%s'"454 " to method users_get_legal" % key455 )456 params[key] = val457 del params['kwargs']458 # verify the required parameter 'user_id' is set459 if ('user_id' not in params) or (params['user_id'] is None):460 raise ValueError("Missing the required parameter `user_id` when calling `users_get_legal`")461 collection_formats = {}462 path_params = {}463 if 'user_id' in params:464 path_params['UserId'] = params['user_id']465 query_params = []466 header_params = {}467 form_params = []468 local_var_files = {}469 body_params = None470 # HTTP header `Accept`471 header_params['Accept'] = self.api_client.\472 select_header_accept(['text/plain', 'application/json', 'text/json'])473 # Authentication setting474 auth_settings = ['oauth2']475 return self.api_client.call_api('/v2.01/Users/legal/{UserId}', 'GET',476 path_params,477 query_params,478 header_params,479 body=body_params,480 post_params=form_params,481 files=local_var_files,482 response_type='UserLegalResponse',483 auth_settings=auth_settings,484 callback=params.get('callback'),485 _return_http_data_only=params.get('_return_http_data_only'),486 _preload_content=params.get('_preload_content', True),487 _request_timeout=params.get('_request_timeout'),488 collection_formats=collection_formats)489 def users_get_list(self, **kwargs):490 """491 List all Users492 493 This method makes a synchronous HTTP request by default. To make an494 asynchronous HTTP request, please define a `callback` function495 to be invoked when receiving the response.496 >>> def callback_function(response):497 >>> pprint(response)498 >>>499 >>> thread = api.users_get_list(callback=callback_function)500 :param callback function: The callback function501 for asynchronous request. (optional)502 :param int page: The page number of results you wish to return503 :param int per_page: The number of results to return per page504 :return: list[UserResponse]505 If the method is called asynchronously,506 returns the request thread.507 """508 kwargs['_return_http_data_only'] = True509 if kwargs.get('callback'):510 return self.users_get_list_with_http_info(**kwargs)511 else:512 (data) = self.users_get_list_with_http_info(**kwargs)513 return data514 def users_get_list_with_http_info(self, **kwargs):515 """516 List all Users517 518 This method makes a synchronous HTTP request by default. To make an519 asynchronous HTTP request, please define a `callback` function520 to be invoked when receiving the response.521 >>> def callback_function(response):522 >>> pprint(response)523 >>>524 >>> thread = api.users_get_list_with_http_info(callback=callback_function)525 :param callback function: The callback function526 for asynchronous request. (optional)527 :param int page: The page number of results you wish to return528 :param int per_page: The number of results to return per page529 :return: list[UserResponse]530 If the method is called asynchronously,531 returns the request thread.532 """533 all_params = ['page', 'per_page']534 all_params.append('callback')535 all_params.append('_return_http_data_only')536 all_params.append('_preload_content')537 all_params.append('_request_timeout')538 params = locals()539 for key, val in iteritems(params['kwargs']):540 if key not in all_params:541 raise TypeError(542 "Got an unexpected keyword argument '%s'"543 " to method users_get_list" % key544 )545 params[key] = val546 del params['kwargs']547 collection_formats = {}548 path_params = {}549 query_params = []550 if 'page' in params:551 query_params.append(('Page', params['page']))552 if 'per_page' in params:553 query_params.append(('Per_Page', params['per_page']))554 header_params = {}555 form_params = []556 local_var_files = {}557 body_params = None558 # HTTP header `Accept`559 header_params['Accept'] = self.api_client.\560 select_header_accept(['text/plain', 'application/json', 'text/json'])561 # Authentication setting562 auth_settings = ['oauth2']563 return self.api_client.call_api('/v2.01/Users', 'GET',564 path_params,565 query_params,566 header_params,567 body=body_params,568 post_params=form_params,569 files=local_var_files,570 response_type='list[UserResponse]',571 auth_settings=auth_settings,572 callback=params.get('callback'),573 _return_http_data_only=params.get('_return_http_data_only'),574 _preload_content=params.get('_preload_content', True),575 _request_timeout=params.get('_request_timeout'),576 collection_formats=collection_formats)577 def users_get_natural(self, user_id, **kwargs):578 """579 View a Natural User580 581 This method makes a synchronous HTTP request by default. To make an582 asynchronous HTTP request, please define a `callback` function583 to be invoked when receiving the response.584 >>> def callback_function(response):585 >>> pprint(response)586 >>>587 >>> thread = api.users_get_natural(user_id, callback=callback_function)588 :param callback function: The callback function589 for asynchronous request. (optional)590 :param int user_id: The Id of a natural user (required)591 :return: UserNaturalResponse592 If the method is called asynchronously,593 returns the request thread.594 """595 kwargs['_return_http_data_only'] = True596 if kwargs.get('callback'):597 return self.users_get_natural_with_http_info(user_id, **kwargs)598 else:599 (data) = self.users_get_natural_with_http_info(user_id, **kwargs)600 return data601 def users_get_natural_with_http_info(self, user_id, **kwargs):602 """603 View a Natural User604 605 This method makes a synchronous HTTP request by default. To make an606 asynchronous HTTP request, please define a `callback` function607 to be invoked when receiving the response.608 >>> def callback_function(response):609 >>> pprint(response)610 >>>611 >>> thread = api.users_get_natural_with_http_info(user_id, callback=callback_function)612 :param callback function: The callback function613 for asynchronous request. (optional)614 :param int user_id: The Id of a natural user (required)615 :return: UserNaturalResponse616 If the method is called asynchronously,617 returns the request thread.618 """619 all_params = ['user_id']620 all_params.append('callback')621 all_params.append('_return_http_data_only')622 all_params.append('_preload_content')623 all_params.append('_request_timeout')624 params = locals()625 for key, val in iteritems(params['kwargs']):626 if key not in all_params:627 raise TypeError(628 "Got an unexpected keyword argument '%s'"629 " to method users_get_natural" % key630 )631 params[key] = val632 del params['kwargs']633 # verify the required parameter 'user_id' is set634 if ('user_id' not in params) or (params['user_id'] is None):635 raise ValueError("Missing the required parameter `user_id` when calling `users_get_natural`")636 collection_formats = {}637 path_params = {}638 if 'user_id' in params:639 path_params['UserId'] = params['user_id']640 query_params = []641 header_params = {}642 form_params = []643 local_var_files = {}644 body_params = None645 # HTTP header `Accept`646 header_params['Accept'] = self.api_client.\647 select_header_accept(['text/plain', 'application/json', 'text/json'])648 # Authentication setting649 auth_settings = ['oauth2']650 return self.api_client.call_api('/v2.01/Users/natural/{UserId}', 'GET',651 path_params,652 query_params,653 header_params,654 body=body_params,655 post_params=form_params,656 files=local_var_files,657 response_type='UserNaturalResponse',658 auth_settings=auth_settings,659 callback=params.get('callback'),660 _return_http_data_only=params.get('_return_http_data_only'),661 _preload_content=params.get('_preload_content', True),662 _request_timeout=params.get('_request_timeout'),663 collection_formats=collection_formats)664 def users_get_transaction_list(self, user_id, **kwargs):665 """666 List Transactions for a User667 668 This method makes a synchronous HTTP request by default. To make an669 asynchronous HTTP request, please define a `callback` function670 to be invoked when receiving the response.671 >>> def callback_function(response):672 >>> pprint(response)673 >>>674 >>> thread = api.users_get_transaction_list(user_id, callback=callback_function)675 :param callback function: The callback function676 for asynchronous request. (optional)677 :param int user_id: The Id of a user (required)678 :param int page: The page number of results you wish to return679 :param int per_page: The number of results to return per page680 :return: list[TransactionResponse]681 If the method is called asynchronously,682 returns the request thread.683 """684 kwargs['_return_http_data_only'] = True685 if kwargs.get('callback'):686 return self.users_get_transaction_list_with_http_info(user_id, **kwargs)687 else:688 (data) = self.users_get_transaction_list_with_http_info(user_id, **kwargs)689 return data690 def users_get_transaction_list_with_http_info(self, user_id, **kwargs):691 """692 List Transactions for a User693 694 This method makes a synchronous HTTP request by default. To make an695 asynchronous HTTP request, please define a `callback` function696 to be invoked when receiving the response.697 >>> def callback_function(response):698 >>> pprint(response)699 >>>700 >>> thread = api.users_get_transaction_list_with_http_info(user_id, callback=callback_function)701 :param callback function: The callback function702 for asynchronous request. (optional)703 :param int user_id: The Id of a user (required)704 :param int page: The page number of results you wish to return705 :param int per_page: The number of results to return per page706 :return: list[TransactionResponse]707 If the method is called asynchronously,708 returns the request thread.709 """710 all_params = ['user_id', 'page', 'per_page']711 all_params.append('callback')712 all_params.append('_return_http_data_only')713 all_params.append('_preload_content')714 all_params.append('_request_timeout')715 params = locals()716 for key, val in iteritems(params['kwargs']):717 if key not in all_params:718 raise TypeError(719 "Got an unexpected keyword argument '%s'"720 " to method users_get_transaction_list" % key721 )722 params[key] = val723 del params['kwargs']724 # verify the required parameter 'user_id' is set725 if ('user_id' not in params) or (params['user_id'] is None):726 raise ValueError("Missing the required parameter `user_id` when calling `users_get_transaction_list`")727 collection_formats = {}728 path_params = {}729 if 'user_id' in params:730 path_params['UserId'] = params['user_id']731 query_params = []732 if 'page' in params:733 query_params.append(('Page', params['page']))734 if 'per_page' in params:735 query_params.append(('Per_Page', params['per_page']))736 header_params = {}737 form_params = []738 local_var_files = {}739 body_params = None740 # HTTP header `Accept`741 header_params['Accept'] = self.api_client.\742 select_header_accept(['text/plain', 'application/json', 'text/json'])743 # Authentication setting744 auth_settings = ['oauth2']745 return self.api_client.call_api('/v2.01/Users/{UserId}/transactions', 'GET',746 path_params,747 query_params,748 header_params,749 body=body_params,750 post_params=form_params,751 files=local_var_files,752 response_type='list[TransactionResponse]',753 auth_settings=auth_settings,754 callback=params.get('callback'),755 _return_http_data_only=params.get('_return_http_data_only'),756 _preload_content=params.get('_preload_content', True),757 _request_timeout=params.get('_request_timeout'),758 collection_formats=collection_formats)759 def users_get_wallet_list(self, user_id, **kwargs):760 """761 List Wallets for a User762 763 This method makes a synchronous HTTP request by default. To make an764 asynchronous HTTP request, please define a `callback` function765 to be invoked when receiving the response.766 >>> def callback_function(response):767 >>> pprint(response)768 >>>769 >>> thread = api.users_get_wallet_list(user_id, callback=callback_function)770 :param callback function: The callback function771 for asynchronous request. (optional)772 :param int user_id: The Id of a user (required)773 :param int page: The page number of results you wish to return774 :param int per_page: The number of results to return per page775 :return: list[WalletResponse]776 If the method is called asynchronously,777 returns the request thread.778 """779 kwargs['_return_http_data_only'] = True780 if kwargs.get('callback'):781 return self.users_get_wallet_list_with_http_info(user_id, **kwargs)782 else:783 (data) = self.users_get_wallet_list_with_http_info(user_id, **kwargs)784 return data785 def users_get_wallet_list_with_http_info(self, user_id, **kwargs):786 """787 List Wallets for a User788 789 This method makes a synchronous HTTP request by default. To make an790 asynchronous HTTP request, please define a `callback` function791 to be invoked when receiving the response.792 >>> def callback_function(response):793 >>> pprint(response)794 >>>795 >>> thread = api.users_get_wallet_list_with_http_info(user_id, callback=callback_function)796 :param callback function: The callback function797 for asynchronous request. (optional)798 :param int user_id: The Id of a user (required)799 :param int page: The page number of results you wish to return800 :param int per_page: The number of results to return per page801 :return: list[WalletResponse]802 If the method is called asynchronously,803 returns the request thread.804 """805 all_params = ['user_id', 'page', 'per_page']806 all_params.append('callback')807 all_params.append('_return_http_data_only')808 all_params.append('_preload_content')809 all_params.append('_request_timeout')810 params = locals()811 for key, val in iteritems(params['kwargs']):812 if key not in all_params:813 raise TypeError(814 "Got an unexpected keyword argument '%s'"815 " to method users_get_wallet_list" % key816 )817 params[key] = val818 del params['kwargs']819 # verify the required parameter 'user_id' is set820 if ('user_id' not in params) or (params['user_id'] is None):821 raise ValueError("Missing the required parameter `user_id` when calling `users_get_wallet_list`")822 collection_formats = {}823 path_params = {}824 if 'user_id' in params:825 path_params['UserId'] = params['user_id']826 query_params = []827 if 'page' in params:828 query_params.append(('Page', params['page']))829 if 'per_page' in params:830 query_params.append(('Per_Page', params['per_page']))831 header_params = {}832 form_params = []833 local_var_files = {}834 body_params = None835 # HTTP header `Accept`836 header_params['Accept'] = self.api_client.\837 select_header_accept(['text/plain', 'application/json', 'text/json'])838 # Authentication setting839 auth_settings = ['oauth2']840 return self.api_client.call_api('/v2.01/Users/{UserId}/wallets', 'GET',841 path_params,842 query_params,843 header_params,844 body=body_params,845 post_params=form_params,846 files=local_var_files,847 response_type='list[WalletResponse]',848 auth_settings=auth_settings,849 callback=params.get('callback'),850 _return_http_data_only=params.get('_return_http_data_only'),851 _preload_content=params.get('_preload_content', True),852 _request_timeout=params.get('_request_timeout'),853 collection_formats=collection_formats)854 def users_post_bank_account_ca(self, user_id, **kwargs):855 """856 Create a CA BankAccount857 In the case of CAD PayOut, the author (AuthorId) of the PayOut should have their address (Address for Natural Users or HeaquartersAddress for Legal Users) completed in their User object858 This method makes a synchronous HTTP request by default. To make an859 asynchronous HTTP request, please define a `callback` function860 to be invoked when receiving the response.861 >>> def callback_function(response):862 >>> pprint(response)863 >>>864 >>> thread = api.users_post_bank_account_ca(user_id, callback=callback_function)865 :param callback function: The callback function866 for asynchronous request. (optional)867 :param int user_id: The Id of a user (required)868 :param BankAccountCaPost bank_account_ca: BankAccountCA Object params869 :return: BankAccountResponseCa870 If the method is called asynchronously,871 returns the request thread.872 """873 kwargs['_return_http_data_only'] = True874 if kwargs.get('callback'):875 return self.users_post_bank_account_ca_with_http_info(user_id, **kwargs)876 else:877 (data) = self.users_post_bank_account_ca_with_http_info(user_id, **kwargs)878 return data879 def users_post_bank_account_ca_with_http_info(self, user_id, **kwargs):880 """881 Create a CA BankAccount882 In the case of CAD PayOut, the author (AuthorId) of the PayOut should have their address (Address for Natural Users or HeaquartersAddress for Legal Users) completed in their User object883 This method makes a synchronous HTTP request by default. To make an884 asynchronous HTTP request, please define a `callback` function885 to be invoked when receiving the response.886 >>> def callback_function(response):887 >>> pprint(response)888 >>>889 >>> thread = api.users_post_bank_account_ca_with_http_info(user_id, callback=callback_function)890 :param callback function: The callback function891 for asynchronous request. (optional)892 :param int user_id: The Id of a user (required)893 :param BankAccountCaPost bank_account_ca: BankAccountCA Object params894 :return: BankAccountResponseCa895 If the method is called asynchronously,896 returns the request thread.897 """898 all_params = ['user_id', 'bank_account_ca']899 all_params.append('callback')900 all_params.append('_return_http_data_only')901 all_params.append('_preload_content')902 all_params.append('_request_timeout')903 params = locals()904 for key, val in iteritems(params['kwargs']):905 if key not in all_params:906 raise TypeError(907 "Got an unexpected keyword argument '%s'"908 " to method users_post_bank_account_ca" % key909 )910 params[key] = val911 del params['kwargs']912 # verify the required parameter 'user_id' is set913 if ('user_id' not in params) or (params['user_id'] is None):914 raise ValueError("Missing the required parameter `user_id` when calling `users_post_bank_account_ca`")915 collection_formats = {}916 path_params = {}917 if 'user_id' in params:918 path_params['UserId'] = params['user_id']919 query_params = []920 header_params = {}921 form_params = []922 local_var_files = {}923 body_params = None924 if 'bank_account_ca' in params:925 body_params = params['bank_account_ca']926 # HTTP header `Accept`927 header_params['Accept'] = self.api_client.\928 select_header_accept(['text/plain', 'application/json', 'text/json'])929 # HTTP header `Content-Type`930 header_params['Content-Type'] = self.api_client.\931 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])932 # Authentication setting933 auth_settings = ['oauth2']934 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/CA', 'POST',935 path_params,936 query_params,937 header_params,938 body=body_params,939 post_params=form_params,940 files=local_var_files,941 response_type='BankAccountResponseCa',942 auth_settings=auth_settings,943 callback=params.get('callback'),944 _return_http_data_only=params.get('_return_http_data_only'),945 _preload_content=params.get('_preload_content', True),946 _request_timeout=params.get('_request_timeout'),947 collection_formats=collection_formats)948 def users_post_bank_account_gb(self, user_id, **kwargs):949 """950 Create a GB BankAccount951 952 This method makes a synchronous HTTP request by default. To make an953 asynchronous HTTP request, please define a `callback` function954 to be invoked when receiving the response.955 >>> def callback_function(response):956 >>> pprint(response)957 >>>958 >>> thread = api.users_post_bank_account_gb(user_id, callback=callback_function)959 :param callback function: The callback function960 for asynchronous request. (optional)961 :param int user_id: The Id of a user (required)962 :param BankAccountGbPost bank_account_gb: 963 :return: BankAccountResponseGb964 If the method is called asynchronously,965 returns the request thread.966 """967 kwargs['_return_http_data_only'] = True968 if kwargs.get('callback'):969 return self.users_post_bank_account_gb_with_http_info(user_id, **kwargs)970 else:971 (data) = self.users_post_bank_account_gb_with_http_info(user_id, **kwargs)972 return data973 def users_post_bank_account_gb_with_http_info(self, user_id, **kwargs):974 """975 Create a GB BankAccount976 977 This method makes a synchronous HTTP request by default. To make an978 asynchronous HTTP request, please define a `callback` function979 to be invoked when receiving the response.980 >>> def callback_function(response):981 >>> pprint(response)982 >>>983 >>> thread = api.users_post_bank_account_gb_with_http_info(user_id, callback=callback_function)984 :param callback function: The callback function985 for asynchronous request. (optional)986 :param int user_id: The Id of a user (required)987 :param BankAccountGbPost bank_account_gb: 988 :return: BankAccountResponseGb989 If the method is called asynchronously,990 returns the request thread.991 """992 all_params = ['user_id', 'bank_account_gb']993 all_params.append('callback')994 all_params.append('_return_http_data_only')995 all_params.append('_preload_content')996 all_params.append('_request_timeout')997 params = locals()998 for key, val in iteritems(params['kwargs']):999 if key not in all_params:1000 raise TypeError(1001 "Got an unexpected keyword argument '%s'"1002 " to method users_post_bank_account_gb" % key1003 )1004 params[key] = val1005 del params['kwargs']1006 # verify the required parameter 'user_id' is set1007 if ('user_id' not in params) or (params['user_id'] is None):1008 raise ValueError("Missing the required parameter `user_id` when calling `users_post_bank_account_gb`")1009 collection_formats = {}1010 path_params = {}1011 if 'user_id' in params:1012 path_params['UserId'] = params['user_id']1013 query_params = []1014 header_params = {}1015 form_params = []1016 local_var_files = {}1017 body_params = None1018 if 'bank_account_gb' in params:1019 body_params = params['bank_account_gb']1020 # HTTP header `Accept`1021 header_params['Accept'] = self.api_client.\1022 select_header_accept(['text/plain', 'application/json', 'text/json'])1023 # HTTP header `Content-Type`1024 header_params['Content-Type'] = self.api_client.\1025 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1026 # Authentication setting1027 auth_settings = ['oauth2']1028 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/GB', 'POST',1029 path_params,1030 query_params,1031 header_params,1032 body=body_params,1033 post_params=form_params,1034 files=local_var_files,1035 response_type='BankAccountResponseGb',1036 auth_settings=auth_settings,1037 callback=params.get('callback'),1038 _return_http_data_only=params.get('_return_http_data_only'),1039 _preload_content=params.get('_preload_content', True),1040 _request_timeout=params.get('_request_timeout'),1041 collection_formats=collection_formats)1042 def users_post_bank_account_iban(self, user_id, **kwargs):1043 """1044 Create an IBAN BankAccount1045 1046 This method makes a synchronous HTTP request by default. To make an1047 asynchronous HTTP request, please define a `callback` function1048 to be invoked when receiving the response.1049 >>> def callback_function(response):1050 >>> pprint(response)1051 >>>1052 >>> thread = api.users_post_bank_account_iban(user_id, callback=callback_function)1053 :param callback function: The callback function1054 for asynchronous request. (optional)1055 :param int user_id: The Id of a user (required)1056 :param BankAccountIbanPost bank_account_iban: BankAccountIBAN Object params1057 :return: BankAccountResponseIban1058 If the method is called asynchronously,1059 returns the request thread.1060 """1061 kwargs['_return_http_data_only'] = True1062 if kwargs.get('callback'):1063 return self.users_post_bank_account_iban_with_http_info(user_id, **kwargs)1064 else:1065 (data) = self.users_post_bank_account_iban_with_http_info(user_id, **kwargs)1066 return data1067 def users_post_bank_account_iban_with_http_info(self, user_id, **kwargs):1068 """1069 Create an IBAN BankAccount1070 1071 This method makes a synchronous HTTP request by default. To make an1072 asynchronous HTTP request, please define a `callback` function1073 to be invoked when receiving the response.1074 >>> def callback_function(response):1075 >>> pprint(response)1076 >>>1077 >>> thread = api.users_post_bank_account_iban_with_http_info(user_id, callback=callback_function)1078 :param callback function: The callback function1079 for asynchronous request. (optional)1080 :param int user_id: The Id of a user (required)1081 :param BankAccountIbanPost bank_account_iban: BankAccountIBAN Object params1082 :return: BankAccountResponseIban1083 If the method is called asynchronously,1084 returns the request thread.1085 """1086 all_params = ['user_id', 'bank_account_iban']1087 all_params.append('callback')1088 all_params.append('_return_http_data_only')1089 all_params.append('_preload_content')1090 all_params.append('_request_timeout')1091 params = locals()1092 for key, val in iteritems(params['kwargs']):1093 if key not in all_params:1094 raise TypeError(1095 "Got an unexpected keyword argument '%s'"1096 " to method users_post_bank_account_iban" % key1097 )1098 params[key] = val1099 del params['kwargs']1100 # verify the required parameter 'user_id' is set1101 if ('user_id' not in params) or (params['user_id'] is None):1102 raise ValueError("Missing the required parameter `user_id` when calling `users_post_bank_account_iban`")1103 collection_formats = {}1104 path_params = {}1105 if 'user_id' in params:1106 path_params['UserId'] = params['user_id']1107 query_params = []1108 header_params = {}1109 form_params = []1110 local_var_files = {}1111 body_params = None1112 if 'bank_account_iban' in params:1113 body_params = params['bank_account_iban']1114 # HTTP header `Accept`1115 header_params['Accept'] = self.api_client.\1116 select_header_accept(['text/plain', 'application/json', 'text/json'])1117 # HTTP header `Content-Type`1118 header_params['Content-Type'] = self.api_client.\1119 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1120 # Authentication setting1121 auth_settings = ['oauth2']1122 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/IBAN', 'POST',1123 path_params,1124 query_params,1125 header_params,1126 body=body_params,1127 post_params=form_params,1128 files=local_var_files,1129 response_type='BankAccountResponseIban',1130 auth_settings=auth_settings,1131 callback=params.get('callback'),1132 _return_http_data_only=params.get('_return_http_data_only'),1133 _preload_content=params.get('_preload_content', True),1134 _request_timeout=params.get('_request_timeout'),1135 collection_formats=collection_formats)1136 def users_post_bank_account_other(self, user_id, **kwargs):1137 """1138 Create an OTHER BankAccount1139 1140 This method makes a synchronous HTTP request by default. To make an1141 asynchronous HTTP request, please define a `callback` function1142 to be invoked when receiving the response.1143 >>> def callback_function(response):1144 >>> pprint(response)1145 >>>1146 >>> thread = api.users_post_bank_account_other(user_id, callback=callback_function)1147 :param callback function: The callback function1148 for asynchronous request. (optional)1149 :param int user_id: The Id of a user (required)1150 :param BankAccountOtherPost bank_account_other: 1151 :return: BankAccountResponseOther1152 If the method is called asynchronously,1153 returns the request thread.1154 """1155 kwargs['_return_http_data_only'] = True1156 if kwargs.get('callback'):1157 return self.users_post_bank_account_other_with_http_info(user_id, **kwargs)1158 else:1159 (data) = self.users_post_bank_account_other_with_http_info(user_id, **kwargs)1160 return data1161 def users_post_bank_account_other_with_http_info(self, user_id, **kwargs):1162 """1163 Create an OTHER BankAccount1164 1165 This method makes a synchronous HTTP request by default. To make an1166 asynchronous HTTP request, please define a `callback` function1167 to be invoked when receiving the response.1168 >>> def callback_function(response):1169 >>> pprint(response)1170 >>>1171 >>> thread = api.users_post_bank_account_other_with_http_info(user_id, callback=callback_function)1172 :param callback function: The callback function1173 for asynchronous request. (optional)1174 :param int user_id: The Id of a user (required)1175 :param BankAccountOtherPost bank_account_other: 1176 :return: BankAccountResponseOther1177 If the method is called asynchronously,1178 returns the request thread.1179 """1180 all_params = ['user_id', 'bank_account_other']1181 all_params.append('callback')1182 all_params.append('_return_http_data_only')1183 all_params.append('_preload_content')1184 all_params.append('_request_timeout')1185 params = locals()1186 for key, val in iteritems(params['kwargs']):1187 if key not in all_params:1188 raise TypeError(1189 "Got an unexpected keyword argument '%s'"1190 " to method users_post_bank_account_other" % key1191 )1192 params[key] = val1193 del params['kwargs']1194 # verify the required parameter 'user_id' is set1195 if ('user_id' not in params) or (params['user_id'] is None):1196 raise ValueError("Missing the required parameter `user_id` when calling `users_post_bank_account_other`")1197 collection_formats = {}1198 path_params = {}1199 if 'user_id' in params:1200 path_params['UserId'] = params['user_id']1201 query_params = []1202 header_params = {}1203 form_params = []1204 local_var_files = {}1205 body_params = None1206 if 'bank_account_other' in params:1207 body_params = params['bank_account_other']1208 # HTTP header `Accept`1209 header_params['Accept'] = self.api_client.\1210 select_header_accept(['text/plain', 'application/json', 'text/json'])1211 # HTTP header `Content-Type`1212 header_params['Content-Type'] = self.api_client.\1213 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1214 # Authentication setting1215 auth_settings = ['oauth2']1216 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/OTHER', 'POST',1217 path_params,1218 query_params,1219 header_params,1220 body=body_params,1221 post_params=form_params,1222 files=local_var_files,1223 response_type='BankAccountResponseOther',1224 auth_settings=auth_settings,1225 callback=params.get('callback'),1226 _return_http_data_only=params.get('_return_http_data_only'),1227 _preload_content=params.get('_preload_content', True),1228 _request_timeout=params.get('_request_timeout'),1229 collection_formats=collection_formats)1230 def users_post_bank_account_us(self, user_id, **kwargs):1231 """1232 Create an US BankAccount1233 In the case of USD PayOut, the author (AuthorId) of the PayOut should have their address (Address for Natural Users or HeaquartersAddress for Legal Users) completed in their User object.1234 This method makes a synchronous HTTP request by default. To make an1235 asynchronous HTTP request, please define a `callback` function1236 to be invoked when receiving the response.1237 >>> def callback_function(response):1238 >>> pprint(response)1239 >>>1240 >>> thread = api.users_post_bank_account_us(user_id, callback=callback_function)1241 :param callback function: The callback function1242 for asynchronous request. (optional)1243 :param int user_id: The Id of a user (required)1244 :param BankAccountUsPost bank_account_us: BankAccountUS Object params1245 :return: BankAccountResponseUs1246 If the method is called asynchronously,1247 returns the request thread.1248 """1249 kwargs['_return_http_data_only'] = True1250 if kwargs.get('callback'):1251 return self.users_post_bank_account_us_with_http_info(user_id, **kwargs)1252 else:1253 (data) = self.users_post_bank_account_us_with_http_info(user_id, **kwargs)1254 return data1255 def users_post_bank_account_us_with_http_info(self, user_id, **kwargs):1256 """1257 Create an US BankAccount1258 In the case of USD PayOut, the author (AuthorId) of the PayOut should have their address (Address for Natural Users or HeaquartersAddress for Legal Users) completed in their User object.1259 This method makes a synchronous HTTP request by default. To make an1260 asynchronous HTTP request, please define a `callback` function1261 to be invoked when receiving the response.1262 >>> def callback_function(response):1263 >>> pprint(response)1264 >>>1265 >>> thread = api.users_post_bank_account_us_with_http_info(user_id, callback=callback_function)1266 :param callback function: The callback function1267 for asynchronous request. (optional)1268 :param int user_id: The Id of a user (required)1269 :param BankAccountUsPost bank_account_us: BankAccountUS Object params1270 :return: BankAccountResponseUs1271 If the method is called asynchronously,1272 returns the request thread.1273 """1274 all_params = ['user_id', 'bank_account_us']1275 all_params.append('callback')1276 all_params.append('_return_http_data_only')1277 all_params.append('_preload_content')1278 all_params.append('_request_timeout')1279 params = locals()1280 for key, val in iteritems(params['kwargs']):1281 if key not in all_params:1282 raise TypeError(1283 "Got an unexpected keyword argument '%s'"1284 " to method users_post_bank_account_us" % key1285 )1286 params[key] = val1287 del params['kwargs']1288 # verify the required parameter 'user_id' is set1289 if ('user_id' not in params) or (params['user_id'] is None):1290 raise ValueError("Missing the required parameter `user_id` when calling `users_post_bank_account_us`")1291 collection_formats = {}1292 path_params = {}1293 if 'user_id' in params:1294 path_params['UserId'] = params['user_id']1295 query_params = []1296 header_params = {}1297 form_params = []1298 local_var_files = {}1299 body_params = None1300 if 'bank_account_us' in params:1301 body_params = params['bank_account_us']1302 # HTTP header `Accept`1303 header_params['Accept'] = self.api_client.\1304 select_header_accept(['text/plain', 'application/json', 'text/json'])1305 # HTTP header `Content-Type`1306 header_params['Content-Type'] = self.api_client.\1307 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1308 # Authentication setting1309 auth_settings = ['oauth2']1310 return self.api_client.call_api('/v2.01/Users/{UserId}/bankaccounts/US', 'POST',1311 path_params,1312 query_params,1313 header_params,1314 body=body_params,1315 post_params=form_params,1316 files=local_var_files,1317 response_type='BankAccountResponseUs',1318 auth_settings=auth_settings,1319 callback=params.get('callback'),1320 _return_http_data_only=params.get('_return_http_data_only'),1321 _preload_content=params.get('_preload_content', True),1322 _request_timeout=params.get('_request_timeout'),1323 collection_formats=collection_formats)1324 def users_post_legal(self, **kwargs):1325 """1326 Create a Legal User1327 Note that the LegalRepresentativeBirthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1328 This method makes a synchronous HTTP request by default. To make an1329 asynchronous HTTP request, please define a `callback` function1330 to be invoked when receiving the response.1331 >>> def callback_function(response):1332 >>> pprint(response)1333 >>>1334 >>> thread = api.users_post_legal(callback=callback_function)1335 :param callback function: The callback function1336 for asynchronous request. (optional)1337 :param UserLegalPost user_legal: UserLegal Object params1338 :return: UserLegalResponse1339 If the method is called asynchronously,1340 returns the request thread.1341 """1342 kwargs['_return_http_data_only'] = True1343 if kwargs.get('callback'):1344 return self.users_post_legal_with_http_info(**kwargs)1345 else:1346 (data) = self.users_post_legal_with_http_info(**kwargs)1347 return data1348 def users_post_legal_with_http_info(self, **kwargs):1349 """1350 Create a Legal User1351 Note that the LegalRepresentativeBirthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1352 This method makes a synchronous HTTP request by default. To make an1353 asynchronous HTTP request, please define a `callback` function1354 to be invoked when receiving the response.1355 >>> def callback_function(response):1356 >>> pprint(response)1357 >>>1358 >>> thread = api.users_post_legal_with_http_info(callback=callback_function)1359 :param callback function: The callback function1360 for asynchronous request. (optional)1361 :param UserLegalPost user_legal: UserLegal Object params1362 :return: UserLegalResponse1363 If the method is called asynchronously,1364 returns the request thread.1365 """1366 all_params = ['user_legal']1367 all_params.append('callback')1368 all_params.append('_return_http_data_only')1369 all_params.append('_preload_content')1370 all_params.append('_request_timeout')1371 params = locals()1372 for key, val in iteritems(params['kwargs']):1373 if key not in all_params:1374 raise TypeError(1375 "Got an unexpected keyword argument '%s'"1376 " to method users_post_legal" % key1377 )1378 params[key] = val1379 del params['kwargs']1380 collection_formats = {}1381 path_params = {}1382 query_params = []1383 header_params = {}1384 form_params = []1385 local_var_files = {}1386 body_params = None1387 if 'user_legal' in params:1388 body_params = params['user_legal']1389 # HTTP header `Accept`1390 header_params['Accept'] = self.api_client.\1391 select_header_accept(['text/plain', 'application/json', 'text/json'])1392 # HTTP header `Content-Type`1393 header_params['Content-Type'] = self.api_client.\1394 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1395 # Authentication setting1396 auth_settings = ['oauth2']1397 return self.api_client.call_api('/v2.01/Users/legal', 'POST',1398 path_params,1399 query_params,1400 header_params,1401 body=body_params,1402 post_params=form_params,1403 files=local_var_files,1404 response_type='UserLegalResponse',1405 auth_settings=auth_settings,1406 callback=params.get('callback'),1407 _return_http_data_only=params.get('_return_http_data_only'),1408 _preload_content=params.get('_preload_content', True),1409 _request_timeout=params.get('_request_timeout'),1410 collection_formats=collection_formats)1411 def users_post_natural(self, **kwargs):1412 """1413 Create a Natural User1414 Note that the Birthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1415 This method makes a synchronous HTTP request by default. To make an1416 asynchronous HTTP request, please define a `callback` function1417 to be invoked when receiving the response.1418 >>> def callback_function(response):1419 >>> pprint(response)1420 >>>1421 >>> thread = api.users_post_natural(callback=callback_function)1422 :param callback function: The callback function1423 for asynchronous request. (optional)1424 :param UserNaturalPost user_natural: UserNatural Object params1425 :return: UserNaturalResponse1426 If the method is called asynchronously,1427 returns the request thread.1428 """1429 kwargs['_return_http_data_only'] = True1430 if kwargs.get('callback'):1431 return self.users_post_natural_with_http_info(**kwargs)1432 else:1433 (data) = self.users_post_natural_with_http_info(**kwargs)1434 return data1435 def users_post_natural_with_http_info(self, **kwargs):1436 """1437 Create a Natural User1438 Note that the Birthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1439 This method makes a synchronous HTTP request by default. To make an1440 asynchronous HTTP request, please define a `callback` function1441 to be invoked when receiving the response.1442 >>> def callback_function(response):1443 >>> pprint(response)1444 >>>1445 >>> thread = api.users_post_natural_with_http_info(callback=callback_function)1446 :param callback function: The callback function1447 for asynchronous request. (optional)1448 :param UserNaturalPost user_natural: UserNatural Object params1449 :return: UserNaturalResponse1450 If the method is called asynchronously,1451 returns the request thread.1452 """1453 all_params = ['user_natural']1454 all_params.append('callback')1455 all_params.append('_return_http_data_only')1456 all_params.append('_preload_content')1457 all_params.append('_request_timeout')1458 params = locals()1459 for key, val in iteritems(params['kwargs']):1460 if key not in all_params:1461 raise TypeError(1462 "Got an unexpected keyword argument '%s'"1463 " to method users_post_natural" % key1464 )1465 params[key] = val1466 del params['kwargs']1467 collection_formats = {}1468 path_params = {}1469 query_params = []1470 header_params = {}1471 form_params = []1472 local_var_files = {}1473 body_params = None1474 if 'user_natural' in params:1475 body_params = params['user_natural']1476 # HTTP header `Accept`1477 header_params['Accept'] = self.api_client.\1478 select_header_accept(['text/plain', 'application/json', 'text/json'])1479 # HTTP header `Content-Type`1480 header_params['Content-Type'] = self.api_client.\1481 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1482 # Authentication setting1483 auth_settings = ['oauth2']1484 return self.api_client.call_api('/v2.01/Users/natural', 'POST',1485 path_params,1486 query_params,1487 header_params,1488 body=body_params,1489 post_params=form_params,1490 files=local_var_files,1491 response_type='UserNaturalResponse',1492 auth_settings=auth_settings,1493 callback=params.get('callback'),1494 _return_http_data_only=params.get('_return_http_data_only'),1495 _preload_content=params.get('_preload_content', True),1496 _request_timeout=params.get('_request_timeout'),1497 collection_formats=collection_formats)1498 def users_put_legal(self, user_id, **kwargs):1499 """1500 Update a Legal User1501 Note that the LegalRepresentativeBirthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1502 This method makes a synchronous HTTP request by default. To make an1503 asynchronous HTTP request, please define a `callback` function1504 to be invoked when receiving the response.1505 >>> def callback_function(response):1506 >>> pprint(response)1507 >>>1508 >>> thread = api.users_put_legal(user_id, callback=callback_function)1509 :param callback function: The callback function1510 for asynchronous request. (optional)1511 :param int user_id: The Id of a user (required)1512 :param UserLegalPut user_legal: UserLegal Object params1513 :return: UserLegalResponse1514 If the method is called asynchronously,1515 returns the request thread.1516 """1517 kwargs['_return_http_data_only'] = True1518 if kwargs.get('callback'):1519 return self.users_put_legal_with_http_info(user_id, **kwargs)1520 else:1521 (data) = self.users_put_legal_with_http_info(user_id, **kwargs)1522 return data1523 def users_put_legal_with_http_info(self, user_id, **kwargs):1524 """1525 Update a Legal User1526 Note that the LegalRepresentativeBirthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1527 This method makes a synchronous HTTP request by default. To make an1528 asynchronous HTTP request, please define a `callback` function1529 to be invoked when receiving the response.1530 >>> def callback_function(response):1531 >>> pprint(response)1532 >>>1533 >>> thread = api.users_put_legal_with_http_info(user_id, callback=callback_function)1534 :param callback function: The callback function1535 for asynchronous request. (optional)1536 :param int user_id: The Id of a user (required)1537 :param UserLegalPut user_legal: UserLegal Object params1538 :return: UserLegalResponse1539 If the method is called asynchronously,1540 returns the request thread.1541 """1542 all_params = ['user_id', 'user_legal']1543 all_params.append('callback')1544 all_params.append('_return_http_data_only')1545 all_params.append('_preload_content')1546 all_params.append('_request_timeout')1547 params = locals()1548 for key, val in iteritems(params['kwargs']):1549 if key not in all_params:1550 raise TypeError(1551 "Got an unexpected keyword argument '%s'"1552 " to method users_put_legal" % key1553 )1554 params[key] = val1555 del params['kwargs']1556 # verify the required parameter 'user_id' is set1557 if ('user_id' not in params) or (params['user_id'] is None):1558 raise ValueError("Missing the required parameter `user_id` when calling `users_put_legal`")1559 collection_formats = {}1560 path_params = {}1561 if 'user_id' in params:1562 path_params['UserId'] = params['user_id']1563 query_params = []1564 header_params = {}1565 form_params = []1566 local_var_files = {}1567 body_params = None1568 if 'user_legal' in params:1569 body_params = params['user_legal']1570 # HTTP header `Accept`1571 header_params['Accept'] = self.api_client.\1572 select_header_accept(['text/plain', 'application/json', 'text/json'])1573 # HTTP header `Content-Type`1574 header_params['Content-Type'] = self.api_client.\1575 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1576 # Authentication setting1577 auth_settings = ['oauth2']1578 return self.api_client.call_api('/v2.01/Users/legal/{UserId}', 'PUT',1579 path_params,1580 query_params,1581 header_params,1582 body=body_params,1583 post_params=form_params,1584 files=local_var_files,1585 response_type='UserLegalResponse',1586 auth_settings=auth_settings,1587 callback=params.get('callback'),1588 _return_http_data_only=params.get('_return_http_data_only'),1589 _preload_content=params.get('_preload_content', True),1590 _request_timeout=params.get('_request_timeout'),1591 collection_formats=collection_formats)1592 def users_put_natural(self, user_id, **kwargs):1593 """1594 Update a Natural User1595 Note that the Birthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1596 This method makes a synchronous HTTP request by default. To make an1597 asynchronous HTTP request, please define a `callback` function1598 to be invoked when receiving the response.1599 >>> def callback_function(response):1600 >>> pprint(response)1601 >>>1602 >>> thread = api.users_put_natural(user_id, callback=callback_function)1603 :param callback function: The callback function1604 for asynchronous request. (optional)1605 :param int user_id: The Id of a user (required)1606 :param UserNaturalPut user_natural: UserNatural Object params1607 :return: UserNaturalResponse1608 If the method is called asynchronously,1609 returns the request thread.1610 """1611 kwargs['_return_http_data_only'] = True1612 if kwargs.get('callback'):1613 return self.users_put_natural_with_http_info(user_id, **kwargs)1614 else:1615 (data) = self.users_put_natural_with_http_info(user_id, **kwargs)1616 return data1617 def users_put_natural_with_http_info(self, user_id, **kwargs):1618 """1619 Update a Natural User1620 Note that the Birthday field is a timestamp, but be careful to ensure that the time is midnight UTC (otherwise a local time can be understood as 23h UTC, and therefore rendering the wrong date which will present problems when needing to validate the KYC identity)1621 This method makes a synchronous HTTP request by default. To make an1622 asynchronous HTTP request, please define a `callback` function1623 to be invoked when receiving the response.1624 >>> def callback_function(response):1625 >>> pprint(response)1626 >>>1627 >>> thread = api.users_put_natural_with_http_info(user_id, callback=callback_function)1628 :param callback function: The callback function1629 for asynchronous request. (optional)1630 :param int user_id: The Id of a user (required)1631 :param UserNaturalPut user_natural: UserNatural Object params1632 :return: UserNaturalResponse1633 If the method is called asynchronously,1634 returns the request thread.1635 """1636 all_params = ['user_id', 'user_natural']1637 all_params.append('callback')1638 all_params.append('_return_http_data_only')1639 all_params.append('_preload_content')1640 all_params.append('_request_timeout')1641 params = locals()1642 for key, val in iteritems(params['kwargs']):1643 if key not in all_params:1644 raise TypeError(1645 "Got an unexpected keyword argument '%s'"1646 " to method users_put_natural" % key1647 )1648 params[key] = val1649 del params['kwargs']1650 # verify the required parameter 'user_id' is set1651 if ('user_id' not in params) or (params['user_id'] is None):1652 raise ValueError("Missing the required parameter `user_id` when calling `users_put_natural`")1653 collection_formats = {}1654 path_params = {}1655 if 'user_id' in params:1656 path_params['UserId'] = params['user_id']1657 query_params = []1658 header_params = {}1659 form_params = []1660 local_var_files = {}1661 body_params = None1662 if 'user_natural' in params:1663 body_params = params['user_natural']1664 # HTTP header `Accept`1665 header_params['Accept'] = self.api_client.\1666 select_header_accept(['text/plain', 'application/json', 'text/json'])1667 # HTTP header `Content-Type`1668 header_params['Content-Type'] = self.api_client.\1669 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])1670 # Authentication setting1671 auth_settings = ['oauth2']1672 return self.api_client.call_api('/v2.01/Users/natural/{UserId}', 'PUT',1673 path_params,1674 query_params,1675 header_params,1676 body=body_params,1677 post_params=form_params,1678 files=local_var_files,1679 response_type='UserNaturalResponse',1680 auth_settings=auth_settings,1681 callback=params.get('callback'),1682 _return_http_data_only=params.get('_return_http_data_only'),1683 _preload_content=params.get('_preload_content', True),1684 _request_timeout=params.get('_request_timeout'),...
wallets_api.py
Source:wallets_api.py
1# coding: utf-82"""3 MarketPay API4 API for Smart Contracts and Payments5 OpenAPI spec version: v2.016 7 Generated by: https://github.com/swagger-api/swagger-codegen.git8"""9from __future__ import absolute_import10import sys11import os12import re13# python 2 and python 3 compatibility library14from six import iteritems15from ..configuration import Configuration16from ..api_client import ApiClient17class WalletsApi(object):18 """19 NOTE: This class is auto generated by the swagger code generator program.20 Do not edit the class manually.21 Ref: https://github.com/swagger-api/swagger-codegen22 """23 def __init__(self, api_client=None):24 config = Configuration()25 if api_client:26 self.api_client = api_client27 else:28 if not config.api_client:29 config.api_client = ApiClient()30 self.api_client = config.api_client31 def wallets_get(self, wallet_id, **kwargs):32 """33 View a Wallet34 A Wallet is an object in which PayIns and Transfers from users are stored in order to collect money. You can pay into a Wallet, withdraw funds from a wallet or transfer funds from a Wallet to another Wallet. Once a wallet is created, its Currency can not be changed35 This method makes a synchronous HTTP request by default. To make an36 asynchronous HTTP request, please define a `callback` function37 to be invoked when receiving the response.38 >>> def callback_function(response):39 >>> pprint(response)40 >>>41 >>> thread = api.wallets_get(wallet_id, callback=callback_function)42 :param callback function: The callback function43 for asynchronous request. (optional)44 :param int wallet_id: The Id of a wallet (required)45 :return: WalletResponse46 If the method is called asynchronously,47 returns the request thread.48 """49 kwargs['_return_http_data_only'] = True50 if kwargs.get('callback'):51 return self.wallets_get_with_http_info(wallet_id, **kwargs)52 else:53 (data) = self.wallets_get_with_http_info(wallet_id, **kwargs)54 return data55 def wallets_get_with_http_info(self, wallet_id, **kwargs):56 """57 View a Wallet58 A Wallet is an object in which PayIns and Transfers from users are stored in order to collect money. You can pay into a Wallet, withdraw funds from a wallet or transfer funds from a Wallet to another Wallet. Once a wallet is created, its Currency can not be changed59 This method makes a synchronous HTTP request by default. To make an60 asynchronous HTTP request, please define a `callback` function61 to be invoked when receiving the response.62 >>> def callback_function(response):63 >>> pprint(response)64 >>>65 >>> thread = api.wallets_get_with_http_info(wallet_id, callback=callback_function)66 :param callback function: The callback function67 for asynchronous request. (optional)68 :param int wallet_id: The Id of a wallet (required)69 :return: WalletResponse70 If the method is called asynchronously,71 returns the request thread.72 """73 all_params = ['wallet_id']74 all_params.append('callback')75 all_params.append('_return_http_data_only')76 all_params.append('_preload_content')77 all_params.append('_request_timeout')78 params = locals()79 for key, val in iteritems(params['kwargs']):80 if key not in all_params:81 raise TypeError(82 "Got an unexpected keyword argument '%s'"83 " to method wallets_get" % key84 )85 params[key] = val86 del params['kwargs']87 # verify the required parameter 'wallet_id' is set88 if ('wallet_id' not in params) or (params['wallet_id'] is None):89 raise ValueError("Missing the required parameter `wallet_id` when calling `wallets_get`")90 collection_formats = {}91 path_params = {}92 if 'wallet_id' in params:93 path_params['WalletId'] = params['wallet_id']94 query_params = []95 header_params = {}96 form_params = []97 local_var_files = {}98 body_params = None99 # HTTP header `Accept`100 header_params['Accept'] = self.api_client.\101 select_header_accept(['text/plain', 'application/json', 'text/json'])102 # Authentication setting103 auth_settings = ['oauth2']104 return self.api_client.call_api('/v2.01/Wallets/{WalletId}', 'GET',105 path_params,106 query_params,107 header_params,108 body=body_params,109 post_params=form_params,110 files=local_var_files,111 response_type='WalletResponse',112 auth_settings=auth_settings,113 callback=params.get('callback'),114 _return_http_data_only=params.get('_return_http_data_only'),115 _preload_content=params.get('_preload_content', True),116 _request_timeout=params.get('_request_timeout'),117 collection_formats=collection_formats)118 def wallets_get_list(self, **kwargs):119 """120 This method makes a synchronous HTTP request by default. To make an121 asynchronous HTTP request, please define a `callback` function122 to be invoked when receiving the response.123 >>> def callback_function(response):124 >>> pprint(response)125 >>>126 >>> thread = api.wallets_get_list(callback=callback_function)127 :param callback function: The callback function128 for asynchronous request. (optional)129 :param int page:130 :param int per_page:131 :return: ResponseListWalletResponse132 If the method is called asynchronously,133 returns the request thread.134 """135 kwargs['_return_http_data_only'] = True136 if kwargs.get('callback'):137 return self.wallets_get_list_with_http_info(**kwargs)138 else:139 (data) = self.wallets_get_list_with_http_info(**kwargs)140 return data141 def wallets_get_list_with_http_info(self, **kwargs):142 """143 This method makes a synchronous HTTP request by default. To make an144 asynchronous HTTP request, please define a `callback` function145 to be invoked when receiving the response.146 >>> def callback_function(response):147 >>> pprint(response)148 >>>149 >>> thread = api.wallets_get_list_with_http_info(callback=callback_function)150 :param callback function: The callback function151 for asynchronous request. (optional)152 :param int page:153 :param int per_page:154 :return: ResponseListWalletResponse155 If the method is called asynchronously,156 returns the request thread.157 """158 all_params = ['page', 'per_page']159 all_params.append('callback')160 all_params.append('_return_http_data_only')161 all_params.append('_preload_content')162 all_params.append('_request_timeout')163 params = locals()164 for key, val in iteritems(params['kwargs']):165 if key not in all_params:166 raise TypeError(167 "Got an unexpected keyword argument '%s'"168 " to method wallets_get_list" % key169 )170 params[key] = val171 del params['kwargs']172 collection_formats = {}173 path_params = {}174 query_params = []175 if 'page' in params:176 query_params.append(('Page', params['page']))177 if 'per_page' in params:178 query_params.append(('Per_Page', params['per_page']))179 header_params = {}180 form_params = []181 local_var_files = {}182 body_params = None183 # HTTP header `Accept`184 header_params['Accept'] = self.api_client.\185 select_header_accept(['text/plain', 'application/json', 'text/json'])186 # Authentication setting187 auth_settings = ['oauth2']188 return self.api_client.call_api('/v2.01/Wallets', 'GET',189 path_params,190 query_params,191 header_params,192 body=body_params,193 post_params=form_params,194 files=local_var_files,195 response_type='ResponseListWalletResponse',196 auth_settings=auth_settings,197 callback=params.get('callback'),198 _return_http_data_only=params.get('_return_http_data_only'),199 _preload_content=params.get('_preload_content', True),200 _request_timeout=params.get('_request_timeout'),201 collection_formats=collection_formats)202 def wallets_get_transaction_list(self, wallet_id, **kwargs):203 """204 List a Wallet's Transactions205 206 This method makes a synchronous HTTP request by default. To make an207 asynchronous HTTP request, please define a `callback` function208 to be invoked when receiving the response.209 >>> def callback_function(response):210 >>> pprint(response)211 >>>212 >>> thread = api.wallets_get_transaction_list(wallet_id, callback=callback_function)213 :param callback function: The callback function214 for asynchronous request. (optional)215 :param int wallet_id: The Id of a wallet (required)216 :param int page: The page number of results you wish to return217 :param int per_page: The number of results to return per page218 :return: list[TransactionResponse]219 If the method is called asynchronously,220 returns the request thread.221 """222 kwargs['_return_http_data_only'] = True223 if kwargs.get('callback'):224 return self.wallets_get_transaction_list_with_http_info(wallet_id, **kwargs)225 else:226 (data) = self.wallets_get_transaction_list_with_http_info(wallet_id, **kwargs)227 return data228 def wallets_get_transaction_list_with_http_info(self, wallet_id, **kwargs):229 """230 List a Wallet's Transactions231 232 This method makes a synchronous HTTP request by default. To make an233 asynchronous HTTP request, please define a `callback` function234 to be invoked when receiving the response.235 >>> def callback_function(response):236 >>> pprint(response)237 >>>238 >>> thread = api.wallets_get_transaction_list_with_http_info(wallet_id, callback=callback_function)239 :param callback function: The callback function240 for asynchronous request. (optional)241 :param int wallet_id: The Id of a wallet (required)242 :param int page: The page number of results you wish to return243 :param int per_page: The number of results to return per page244 :return: list[TransactionResponse]245 If the method is called asynchronously,246 returns the request thread.247 """248 all_params = ['wallet_id', 'page', 'per_page']249 all_params.append('callback')250 all_params.append('_return_http_data_only')251 all_params.append('_preload_content')252 all_params.append('_request_timeout')253 params = locals()254 for key, val in iteritems(params['kwargs']):255 if key not in all_params:256 raise TypeError(257 "Got an unexpected keyword argument '%s'"258 " to method wallets_get_transaction_list" % key259 )260 params[key] = val261 del params['kwargs']262 # verify the required parameter 'wallet_id' is set263 if ('wallet_id' not in params) or (params['wallet_id'] is None):264 raise ValueError("Missing the required parameter `wallet_id` when calling `wallets_get_transaction_list`")265 collection_formats = {}266 path_params = {}267 if 'wallet_id' in params:268 path_params['WalletId'] = params['wallet_id']269 query_params = []270 if 'page' in params:271 query_params.append(('Page', params['page']))272 if 'per_page' in params:273 query_params.append(('per_page', params['per_page']))274 header_params = {}275 form_params = []276 local_var_files = {}277 body_params = None278 # HTTP header `Accept`279 header_params['Accept'] = self.api_client.\280 select_header_accept(['text/plain', 'application/json', 'text/json'])281 # Authentication setting282 auth_settings = ['oauth2']283 return self.api_client.call_api('/v2.01/Wallets/{WalletId}/transactions', 'GET',284 path_params,285 query_params,286 header_params,287 body=body_params,288 post_params=form_params,289 files=local_var_files,290 response_type='list[TransactionResponse]',291 auth_settings=auth_settings,292 callback=params.get('callback'),293 _return_http_data_only=params.get('_return_http_data_only'),294 _preload_content=params.get('_preload_content', True),295 _request_timeout=params.get('_request_timeout'),296 collection_formats=collection_formats)297 def wallets_post(self, **kwargs):298 """299 Create a Wallet300 301 This method makes a synchronous HTTP request by default. To make an302 asynchronous HTTP request, please define a `callback` function303 to be invoked when receiving the response.304 >>> def callback_function(response):305 >>> pprint(response)306 >>>307 >>> thread = api.wallets_post(callback=callback_function)308 :param callback function: The callback function309 for asynchronous request. (optional)310 :param WalletPost wallet: Wallet Object params311 :return: WalletResponse312 If the method is called asynchronously,313 returns the request thread.314 """315 kwargs['_return_http_data_only'] = True316 if kwargs.get('callback'):317 return self.wallets_post_with_http_info(**kwargs)318 else:319 (data) = self.wallets_post_with_http_info(**kwargs)320 return data321 def wallets_post_with_http_info(self, **kwargs):322 """323 Create a Wallet324 325 This method makes a synchronous HTTP request by default. To make an326 asynchronous HTTP request, please define a `callback` function327 to be invoked when receiving the response.328 >>> def callback_function(response):329 >>> pprint(response)330 >>>331 >>> thread = api.wallets_post_with_http_info(callback=callback_function)332 :param callback function: The callback function333 for asynchronous request. (optional)334 :param WalletPost wallet: Wallet Object params335 :return: WalletResponse336 If the method is called asynchronously,337 returns the request thread.338 """339 all_params = ['wallet']340 all_params.append('callback')341 all_params.append('_return_http_data_only')342 all_params.append('_preload_content')343 all_params.append('_request_timeout')344 params = locals()345 for key, val in iteritems(params['kwargs']):346 if key not in all_params:347 raise TypeError(348 "Got an unexpected keyword argument '%s'"349 " to method wallets_post" % key350 )351 params[key] = val352 del params['kwargs']353 collection_formats = {}354 path_params = {}355 query_params = []356 header_params = {}357 form_params = []358 local_var_files = {}359 body_params = None360 if 'wallet' in params:361 body_params = params['wallet']362 # HTTP header `Accept`363 header_params['Accept'] = self.api_client.\364 select_header_accept(['text/plain', 'application/json', 'text/json'])365 # HTTP header `Content-Type`366 header_params['Content-Type'] = self.api_client.\367 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])368 # Authentication setting369 auth_settings = ['oauth2']370 return self.api_client.call_api('/v2.01/Wallets', 'POST',371 path_params,372 query_params,373 header_params,374 body=body_params,375 post_params=form_params,376 files=local_var_files,377 response_type='WalletResponse',378 auth_settings=auth_settings,379 callback=params.get('callback'),380 _return_http_data_only=params.get('_return_http_data_only'),381 _preload_content=params.get('_preload_content', True),382 _request_timeout=params.get('_request_timeout'),383 collection_formats=collection_formats)384 def wallets_put(self, wallet_id, **kwargs):385 """386 Update a Wallet387 388 This method makes a synchronous HTTP request by default. To make an389 asynchronous HTTP request, please define a `callback` function390 to be invoked when receiving the response.391 >>> def callback_function(response):392 >>> pprint(response)393 >>>394 >>> thread = api.wallets_put(wallet_id, callback=callback_function)395 :param callback function: The callback function396 for asynchronous request. (optional)397 :param int wallet_id: The Id of a wallet (required)398 :param WalletPut wallet: Wallet Object params399 :return: WalletResponse400 If the method is called asynchronously,401 returns the request thread.402 """403 kwargs['_return_http_data_only'] = True404 if kwargs.get('callback'):405 return self.wallets_put_with_http_info(wallet_id, **kwargs)406 else:407 (data) = self.wallets_put_with_http_info(wallet_id, **kwargs)408 return data409 def wallets_put_with_http_info(self, wallet_id, **kwargs):410 """411 Update a Wallet412 413 This method makes a synchronous HTTP request by default. To make an414 asynchronous HTTP request, please define a `callback` function415 to be invoked when receiving the response.416 >>> def callback_function(response):417 >>> pprint(response)418 >>>419 >>> thread = api.wallets_put_with_http_info(wallet_id, callback=callback_function)420 :param callback function: The callback function421 for asynchronous request. (optional)422 :param int wallet_id: The Id of a wallet (required)423 :param WalletPut wallet: Wallet Object params424 :return: WalletResponse425 If the method is called asynchronously,426 returns the request thread.427 """428 all_params = ['wallet_id', 'wallet']429 all_params.append('callback')430 all_params.append('_return_http_data_only')431 all_params.append('_preload_content')432 all_params.append('_request_timeout')433 params = locals()434 for key, val in iteritems(params['kwargs']):435 if key not in all_params:436 raise TypeError(437 "Got an unexpected keyword argument '%s'"438 " to method wallets_put" % key439 )440 params[key] = val441 del params['kwargs']442 # verify the required parameter 'wallet_id' is set443 if ('wallet_id' not in params) or (params['wallet_id'] is None):444 raise ValueError("Missing the required parameter `wallet_id` when calling `wallets_put`")445 collection_formats = {}446 path_params = {}447 if 'wallet_id' in params:448 path_params['WalletId'] = params['wallet_id']449 query_params = []450 header_params = {}451 form_params = []452 local_var_files = {}453 body_params = None454 if 'wallet' in params:455 body_params = params['wallet']456 # HTTP header `Accept`457 header_params['Accept'] = self.api_client.\458 select_header_accept(['text/plain', 'application/json', 'text/json'])459 # HTTP header `Content-Type`460 header_params['Content-Type'] = self.api_client.\461 select_header_content_type(['application/json', 'text/json', 'application/json-patch+json'])462 # Authentication setting463 auth_settings = ['oauth2']464 return self.api_client.call_api('/v2.01/Wallets/{WalletId}', 'PUT',465 path_params,466 query_params,467 header_params,468 body=body_params,469 post_params=form_params,470 files=local_var_files,471 response_type='WalletResponse',472 auth_settings=auth_settings,473 callback=params.get('callback'),474 _return_http_data_only=params.get('_return_http_data_only'),475 _preload_content=params.get('_preload_content', True),476 _request_timeout=params.get('_request_timeout'),...
SES_setup.py
Source:SES_setup.py
1import os2import time3import numpy as np4from numpy import pi, sqrt5import matplotlib.pyplot as plt6import copy 7import phonons as RC8import optical as opt9from phonons import RC_mapping10from optical import L_non_rwa, L_phenom_SES11from qutip import basis, qeye, enr_identity, enr_destroy, tensor, enr_thermal_dm, steadystate12from utils import *13import imp14OO = basis(3,0)15XO = basis(3,1)16OX = basis(3,2)17site_coherence = OX*XO.dag()18OO_proj = OO*OO.dag()19XO_proj = XO*XO.dag()20OX_proj = OX*OX.dag()21sigma_m1 = OO*XO.dag()22sigma_m2 = OO*OX.dag()23sigma_x1 = sigma_m1+sigma_m1.dag()24sigma_x2 = sigma_m2+sigma_m2.dag()25sigma_x = 0.5*(site_coherence+site_coherence.dag())26sigma_y = 0.5*(1j*(site_coherence-site_coherence.dag()))27I_sys = qeye(3)28imp.reload(RC)29imp.reload(opt)30labels = [ 'OO', 'XO', 'OX', 'site_coherence', 31 'bright', 'dark', 'eig_x', 'eig_y', 'eig_z', 'eig_x_equiv', 'sigma_x', 'sigma_y', 'sigma_z',32 'RC1_position1', 'RC2_position', 33 'RC1_number', 'RC2_number']34tex_labels = [ '$\\rho_0$', '$\\rho_1$', '$\\rho_2$', '$\\rho_12$', 35 '$|+ \\rangle$', '$|- \\rangle$', '$\\tilde{\\sigma}_x$', '$\\tilde{\\sigma}_y^{\prime}$','$\\tilde{\\sigma}_z^{\prime}$', 'eig_x_equiv',36 '$\\sigma_x$', '$\\sigma_y$','$\\sigma_z$',37 r'$\hat{x_1}$', r'$\hat{x_2}$', 38 r'$\hat{N_1}$', r'$\hat{N_2}$']39def make_expectation_labels():40 # makes a dict: keys are names of observables, values are latex friendly labels41 assert(len(tex_labels) == len(labels))42 return dict((key_val[0], key_val[1]) for key_val in zip(labels, tex_labels))43def make_expectation_operators(PARAMS, H=None, weak_coupling=False, shift=True):44 # makes a dict: keys are names of observables values are operators45 I_sys=qeye(PARAMS['sys_dim'])46 I = enr_identity([PARAMS['N_1'], PARAMS['N_2']], PARAMS['exc'])47 N_1, N_2, exc = PARAMS['N_1'], PARAMS['N_2'], PARAMS['exc']48 energies, states = exciton_states(PARAMS, shift=shift)49 bright_vec = states[1]50 dark_vec = states[0]51 sigma_z = XO_proj - OX_proj52 eta = np.sqrt(PARAMS['bias']**2 + 4*PARAMS['V']**2)53 eig_x_equiv = (2*PARAMS['V']/eta)*sigma_z - (PARAMS['bias']/eta)*sigma_x54 # electronic operators55 # site populations site coherences, eig pops, eig cohs56 subspace_ops = [OO_proj, XO_proj, OX_proj, site_coherence,57 bright_vec*bright_vec.dag(), dark_vec*dark_vec.dag(),58 dark_vec*bright_vec.dag()+dark_vec.dag()*bright_vec,59 1j*(dark_vec*bright_vec.dag()-dark_vec.dag()*bright_vec),60 bright_vec*bright_vec.dag()-dark_vec.dag()*dark_vec, eig_x_equiv,61 sigma_x, sigma_y, sigma_z]62 # put operators into full RC tensor product basis63 fullspace_ops = [tensor(op, I) for op in subspace_ops]64 # RC operators65 # RC positions, RC number state1, RC number state1, RC upper N fock, RC ground fock66 if weak_coupling:67 return dict((key_val[0], key_val[1]) for key_val in zip(labels[0:len(subspace_ops)], subspace_ops))68 else:69 a_enr_ops = enr_destroy([N_1, N_2], exc)70 position1 = a_enr_ops[0].dag() + a_enr_ops[0]71 position2 = a_enr_ops[1].dag() + a_enr_ops[1]72 number1 = a_enr_ops[0].dag()*a_enr_ops[0]73 number2 = a_enr_ops[1].dag()*a_enr_ops[1]74 subspace_ops = [position1, position2, number1, number2]75 fullspace_ops += [tensor(I_sys, op) for op in subspace_ops]76 return dict((key_val[0], key_val[1]) for key_val in zip(labels, fullspace_ops))77def separate_states(H, PARAMS, trunc=0.8):78 # truncation removes the really dodgy states for which the parity is unclear 79 # (this might not be numerical error, but it probs is)80 ops = make_expectation_operators(PARAMS)81 energies, states = H.eigenstates()82 energies, states = sort_eigs(energies, states)83 energies, states = energies[0:int(len(states)*trunc)], states[0:int(len(states)*trunc)]84 parities = [(state*state.dag()*ops['sigma_x']).tr() for state in states]85 phonon_occ_dict = {'dark': [], 'bright': [], 'ground': []}86 states_dict = {'dark': [], 'bright': [], 'ground': []}87 energies_dict = {'dark': [], 'bright': [], 'ground': []} # for checking88 for i, parity in enumerate(parities):89 occ_1 = (states[i].dag()*ops['RC1_number']*states[i]).tr().real90 occ_2 = (states[i].dag()*ops['RC2_number']*states[i]).tr().real91 if abs(parity)<1e-10:92 states_dict['ground'].append(states[i])93 energies_dict['ground'].append(energies[i])94 phonon_occ_dict['ground'].append((occ_1, occ_2))95 elif parity>1e-10:96 states_dict['bright'].append(states[i])97 energies_dict['bright'].append(energies[i])98 phonon_occ_dict['bright'].append((occ_1, occ_2))99 elif parity<-1e-10:100 states_dict['dark'].append(states[i])101 energies_dict['dark'].append(energies[i])102 phonon_occ_dict['dark'].append((occ_1, occ_2))103 else:104 raise ValueError("Parity is {} ".format(parity))105 if len(states_dict['ground']) == len(states):106 print("This will not work for V=0. Ground contains all states.")107 #print(len(states_dict['dark']), len(states_dict['bright']), len(states_dict['ground']))108 #assert (len(states_dict['dark']) == len(states_dict['bright']))109 dark_bright_check(states_dict, ops)110 return energies_dict, states_dict, phonon_occ_dict111def get_H_and_L_local(PARAMS, silent=False, threshold=0.):112 V = PARAMS['V']113 PARAMS['H_sub'] = PARAMS['w_1']*XO_proj + PARAMS['w_2']*OX_proj 114 PARAMS.update({'V': 0.})115 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True, parity_flip=PARAMS['parity_flip'])116 L_add = copy.deepcopy(L)117 N_1 = PARAMS['N_1']118 N_2 = PARAMS['N_2']119 exc = PARAMS['exc']120 mu = PARAMS['mu']121 I = enr_identity([N_1,N_2], exc)122 sigma = sigma_m1 + mu*sigma_m2123 PARAMS['H_sub'] += V*(site_coherence + site_coherence.dag())124 PARAMS.update({'V': V})125 H, A_1, A_2 = RC.H_mapping_RC(PARAMS['H_sub'], PARAMS['coupling_ops'], PARAMS['w_1'], PARAMS['w_2'],126 PARAMS['kappa_1'], PARAMS['kappa_2'], PARAMS['N_1'], PARAMS['N_2'], PARAMS['exc'], shift=True)127 128 if abs(PARAMS['alpha_EM'])>0:129 L += opt.L_BMME(H[1], tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)130 L_add += opt.L_BMME(tensor(PARAMS['H_sub'],I), tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)131 #L_add += opt.L_phenom_SES(PARAMS)132 else:133 print("Not including optical dissipator")134 spar0 = sparse_percentage(L)135 if threshold:136 L_add.tidyup(threshold)137 L.tidyup(threshold)138 if not silent:139 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))140 PARAMS.update({'V': V})141 142 return H, L, L_add143def get_H_and_L_add_and_sec(PARAMS,silent=False, threshold=0., shift_in_additive=False):144 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True, parity_flip=PARAMS['parity_flip'])145 L_add = copy.deepcopy(L)146 L_sec = copy.deepcopy(L)147 N_1 = PARAMS['N_1']148 N_2 = PARAMS['N_2']149 exc = PARAMS['exc']150 mu = PARAMS['mu']151 I = enr_identity([N_1,N_2], exc)152 sigma = sigma_m1 + mu*sigma_m2153 if shift_in_additive:154 H_add = tensor(H[0],I)155 else:156 H_add = tensor(PARAMS['H_sub'], I)157 if abs(PARAMS['alpha_EM'])>0:158 L += opt.L_non_rwa(H[1], tensor(sigma,I), PARAMS, silent=silent) #opt.L_BMME(H[1], tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)159 L_add += opt.L_non_rwa(H_add, tensor(sigma,I), PARAMS, silent=silent) #opt.L_BMME(tensor(H_unshifted,I), tensor(sigma,I), PARAMS, 160 L_sec += opt.L_secular(H[1], tensor(sigma,I), PARAMS) #opt.L_BMME(tensor(H_unshifted,I), tensor(sigma,I), PARAMS, 161 #ME_type='nonsecular', site_basis=True, silent=silent)162 #L_secular(H_vib, A, args, silent=False)163 #L_add += opt.L_phenom_SES(PARAMS)164 else:165 print("Not including optical dissipator")166 spar0 = sparse_percentage(L)167 if threshold:168 L_add.tidyup(threshold)169 L.tidyup(threshold)170 if not silent:171 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))172 return H, {'nonadd':L , 'add': L_add, 'sec': L_sec}, PARAMS173def get_H_and_L_full(PARAMS,silent=False, threshold=0.):174 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True)175 N_1 = PARAMS['N_1']176 N_2 = PARAMS['N_2']177 exc = PARAMS['exc']178 mu = PARAMS['mu']179 I = enr_identity([N_1,N_2], exc)180 sigma = sigma_m1 + mu*sigma_m2181 if abs(PARAMS['alpha_EM'])>0:182 L += opt.L_non_rwa(H[1], tensor(sigma,I), PARAMS, silent=silent) #opt.L_BMME(H[1], tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)183 else:184 print("Not including optical dissipator")185 spar0 = sparse_percentage(L)186 if threshold:187 L.tidyup(threshold)188 if not silent:189 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))190 return H, {'nonadd':L }, PARAMS191def get_H_and_L(PARAMS,silent=False, threshold=0., shift_in_additive=False):192 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True, parity_flip=PARAMS['parity_flip'])193 L_add = copy.deepcopy(L)194 N_1 = PARAMS['N_1']195 N_2 = PARAMS['N_2']196 exc = PARAMS['exc']197 mu = PARAMS['mu']198 I = enr_identity([N_1,N_2], exc)199 sigma = sigma_m1 + mu*sigma_m2200 if shift_in_additive:201 H_add = tensor(H[0],I)202 else:203 H_add = tensor(PARAMS['H_sub'], I)204 if abs(PARAMS['alpha_EM'])>0:205 L += opt.L_non_rwa(H[1], tensor(sigma,I), PARAMS, silent=silent) #opt.L_BMME(H[1], tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)206 L_add += opt.L_non_rwa(H_add, tensor(sigma,I), PARAMS, silent=silent) #opt.L_BMME(tensor(H_unshifted,I), tensor(sigma,I), PARAMS, 207 #ME_type='nonsecular', site_basis=True, silent=silent)208 #L_add += opt.L_phenom_SES(PARAMS)209 else:210 print("Not including optical dissipator")211 spar0 = sparse_percentage(L)212 if threshold:213 L_add.tidyup(threshold)214 L.tidyup(threshold)215 if not silent:216 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))217 return H, {'nonadd':L , 'add': L_add}, PARAMS218def get_H_and_L_RWA(PARAMS, silent=False, threshold=0.):219 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True, parity_flip=PARAMS['parity_flip'])220 L_RWA = copy.deepcopy(L)221 N_1 = PARAMS['N_1']222 N_2 = PARAMS['N_2']223 exc = PARAMS['exc']224 mu = PARAMS['mu']225 I = enr_identity([N_1,N_2], exc)226 sigma = sigma_m1 + mu*sigma_m2227 H_unshifted = PARAMS['w_1']*XO_proj + PARAMS['w_2']*OX_proj + PARAMS['V']*(site_coherence+site_coherence.dag())228 if abs(PARAMS['alpha_EM'])>0:229 L_RWA += opt.L_BMME(H[1], tensor(sigma,I), PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)230 L+= opt.L_non_rwa(H[1], tensor(sigma,I), PARAMS, silent=silent)231 else:232 print("Not including optical dissipator")233 spar0 = sparse_percentage(L)234 if threshold:235 L_RWA.tidyup(threshold)236 L.tidyup(threshold)237 if not silent:238 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))239 return H, L, L_RWA, PARAMS240def get_H_and_L_wc(H, PARAMS, silent=True, secular_phonon=False, 241 shift=True, tol=1e-6):242 import optical as opt243 import weak_phonons as wp244 imp.reload(wp)245 imp.reload(opt)246 ti = time.time()247 L_s = wp.weak_phonon(H, PARAMS, secular=secular_phonon, tol=tol)248 L_ns = copy.deepcopy(L_s)249 mu = PARAMS['mu']250 sigma = sigma_m1 + mu*sigma_m2251 if abs(PARAMS['alpha_EM'])>0:252 L_ns += opt.L_non_rwa(H, sigma, PARAMS, silent=silent)253 #opt.L_BMME(H, sigma, PARAMS, ME_type='nonsecular', site_basis=True, silent=silent)254 L_s += wp.L_sec_wc_SES(PARAMS, silent=silent)255 #L += opt.L_BMME(H, sigma, PARAMS, ME_type='secular', site_basis=True, silent=silent)256 H += 0.5*pi*(PARAMS['alpha_1']*sigma_m1.dag()*sigma_m1 + PARAMS['alpha_2']*sigma_m2.dag()*sigma_m2)257 if not silent:258 print("WC non-secular and secular dissipators calculated in {} seconds".format(time.time() - ti))259 return H, L_ns, L_s260def get_H_and_L_additive(PARAMS,silent=False, threshold=0.):261 L, H, A_1, A_2, PARAMS = RC.RC_mapping(PARAMS, silent=silent, shift=True, site_basis=True)262 H_unshifted = PARAMS['w_1']*XO_proj + PARAMS['w_2']*OX_proj + PARAMS['V']*(site_coherence+site_coherence.dag())263 L_add = copy.deepcopy(L)264 L_add_shift = copy.deepcopy(L)265 N_1 = PARAMS['N_1']266 N_2 = PARAMS['N_2']267 exc = PARAMS['exc']268 mu = PARAMS['mu']269 I = enr_identity([N_1,N_2], exc)270 sigma = sigma_m1 + mu*sigma_m2271 272 if abs(PARAMS['alpha_EM'])>0:273 L += opt.L_non_rwa(H[1], tensor(sigma,I), PARAMS, silent=silent)274 L_add += opt.L_non_rwa(tensor(H_unshifted,I), tensor(sigma,I), PARAMS, silent=silent)275 L_add_shift += opt.L_non_rwa(tensor(H[0],I), tensor(sigma,I), PARAMS, silent=silent)276 else:277 print("Not including optical dissipator")278 spar0 = sparse_percentage(L)279 if threshold:280 L.tidyup(threshold)281 if not silent:282 print(("Chopping reduced the sparsity from {:0.3f}% to {:0.3f}%".format(spar0, sparse_percentage(L))))283 return H, {'nonadd':L, 'add-shift':L_add_shift , 'add': L_add}, PARAMS284def get_H(PARAMS):285 H, phonon_operators, PARAMS = RC.mapped_H(PARAMS)286 sigma = sigma_m1 + PARAMS['mu']*sigma_m2 287 I = enr_identity([PARAMS['N_1'], PARAMS['N_2']], PARAMS['exc'])288 return H, phonon_operators, tensor(sigma+sigma.dag(), I), PARAMS289def PARAMS_setup(bias=100., w_2=2000., V = 100., alpha=100.,290 T_EM=0., T_ph =300.,291 alpha_EM=1., shift=True,292 num_cpus=1, w_0=200, Gamma=50., N=3,293 silent=False, exc_diff=0, sys_dim=3, alpha_bias=0., parity_flip=False):294 # alpha_1 = alpha+alpha_bias295 # Sets up the parameter dict296 N_1 = N_2 = N297 exc = N+exc_diff298 gap = sqrt(bias**2 +4*(V**2))299 phonon_energy = T_ph*0.695300 w_1 = w_2 + bias301 dipole_1, dipole_2 = 1., 1.302 mu = (w_2*dipole_2)/(w_1*dipole_1)303 T_1, T_2 = T_ph, T_ph # Phonon bath temperature304 Gamma_1 = Gamma_2 = Gamma305 w0_2, w0_1 = w_0, w_0 # underdamped SD parameter omega_0306 if not silent:307 plot_UD_SD(Gamma_1, alpha, w_0, eps=w_2)308 w_xx = w_2 + w_1309 if not silent:310 print(("Gap is {}. Phonon thermal energy is {}. Phonon SD peak is {}. N={}.".format(gap, phonon_energy, 311 SD_peak_position(Gamma, 1, w_0), N)))312 J = J_minimal313 H_sub = w_1*XO_proj + w_2*OX_proj + V*(site_coherence+site_coherence.dag())314 coupling_ops = [sigma_m1.dag()*sigma_m1, sigma_m2.dag()*sigma_m2] # system-RC operators315 PARAM_names = ['H_sub', 'coupling_ops', 'w_1', 'w_2', 'V', 'bias', 'w_xx', 'T_1', 'T_2',316 'w0_1', 'w0_2', 'T_EM', 'alpha_EM','mu', 'num_cpus', 'J',317 'dipole_1','dipole_2', 'Gamma_1', 'Gamma_2', 'parity_flip']318 scope = locals() # Lets eval below use local variables, not global319 PARAMS = dict((name, eval(name, scope)) for name in PARAM_names)320 PARAMS.update({'alpha_1': alpha+alpha_bias, 'alpha_2': alpha})321 PARAMS.update({'N_1': N_1, 'N_2': N_2, 'exc': exc})322 PARAMS.update({'sys_dim' : sys_dim})323 return PARAMS324def PARAMS_update_bias(PARAMS_init=None, bias_value=10.):325 # Sets up the parameter dict326 bias = bias_value327 w_2 = PARAMS_init['w_2']328 w_1 = w_2 + bias329 dipole_1, dipole_2 = PARAMS_init['dipole_1'], PARAMS_init['dipole_2']330 mu = (w_2*dipole_2)/(w_1*dipole_1)331 w_xx = w_2 + w_1332 H_sub = w_1*XO_proj + w_2*OX_proj + PARAMS_init['V']*(site_coherence+site_coherence.dag())333 PARAM_names = ['H_sub', 'w_1', 'w_2', 'bias', 'w_xx', 'mu']334 scope = locals() # Lets eval below use local variables, not global335 PARAMS_init.update(dict((name, eval(name, scope)) for name in PARAM_names))336 return PARAMS_init337def displace(offset, a):338 return (offset*(a.dag()) - offset.conjugate()*a).expm()339def undisplaced_initial(init_sys, PARAMS):340 n1 = Occupation(PARAMS['w0_1'], PARAMS['T_1'])341 n2 = Occupation(PARAMS['w0_2'], PARAMS['T_2'])342 return tensor(init_sys, qt.enr_thermal_dm([PARAMS['N_1'], PARAMS['N_2']], PARAMS['exc'], 343 [n1, n2]))344def position_ops(PARAMS):345 atemp = enr_destroy([PARAMS['N_1'], PARAMS['N_2']], PARAMS['exc'])346 return [tensor(I_sys, (a + a.dag())/sqrt(2)) for a in atemp] # Should have a 0.5 in this347def displaced_initial(init_sys, PARAMS, silent=False, return_error=False):348 # Works for 349 offset_1 = sqrt(pi*PARAMS['alpha_1']/(2*PARAMS['w0_1']))350 offset_2 = sqrt(pi*PARAMS['alpha_2']/(2*PARAMS['w0_2']))351 atemp = enr_destroy([PARAMS['N_1'], PARAMS['N_2']], PARAMS['exc'])352 x = position_ops(PARAMS)353 354 r0 = undisplaced_initial(init_sys, PARAMS)355 disp = copy.deepcopy(r0)356 for offset, a_ in zip([offset_1, offset_2], atemp):357 d = tensor(I_sys, displace(offset, a_))358 disp = d * disp * d.dag()359 error = 100*(abs((disp*x[0]).tr()- offset_1)/offset_1 + abs((disp*x[1]).tr()- offset_2)/offset_2)360 if not silent:361 print ("Error in displacement: {:0.8f}%".format(error))362 print ("Ratio of kBT to Omega: {:0.4f}".format(0.695*PARAMS['T_1']/PARAMS['w0_1']))363 if ((PARAMS['T_1'] != PARAMS['T_2']) or (PARAMS['w0_1'] != PARAMS['w0_2'])):364 print("Ratio of kBT to Omega (2): {:0.4f}".format(0.695*PARAMS['T_2']/PARAMS['w0_2']))365 if return_error: 366 return disp, error367 else:368 return disp369def get_converged_N(PARAMS, err_threshold=1e-2, min_N=4, max_N=10, silent=True, exc_diff_N=False):370 err = 0371 for N in range(min_N,max_N+1):372 if exc_diff_N:373 exc_diff = N # when using partial traces we can't use ENR374 else:375 exc_diff = 0376 PARAMS.update({'N_1':N, 'N_2':N, 'exc':N+exc_diff})377 disp, err = displaced_initial(OO_proj, PARAMS, silent=True, return_error=True)378 if err<err_threshold:379 return PARAMS380 print("Error could only converge to {}".format(err))381 return PARAMS...
ragged_gather_op_test.py
Source:ragged_gather_op_test.py
1# Copyright 2018 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for ragged_array_ops.gather."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19from absl.testing import parameterized20import numpy as np21from tensorflow.python.eager import context22from tensorflow.python.framework import constant_op23from tensorflow.python.framework import dtypes24from tensorflow.python.framework import errors25from tensorflow.python.framework import indexed_slices26from tensorflow.python.framework import ops27from tensorflow.python.framework import test_util28from tensorflow.python.ops import array_ops29from tensorflow.python.ops import gradients_impl30from tensorflow.python.ops.ragged import ragged_factory_ops31from tensorflow.python.ops.ragged import ragged_gather_ops32from tensorflow.python.ops.ragged import ragged_tensor33from tensorflow.python.platform import googletest34@test_util.run_all_in_graph_and_eager_modes35class RaggedGatherOpTest(test_util.TensorFlowTestCase, parameterized.TestCase):36 @parameterized.named_parameters([37 # Basic gather (axis=0 and batch_dims=0)38 dict(testcase_name='Params1DTensor_Indices1DTensor',39 params=['a', 'b', 'c', 'd', 'e'],40 indices=[2, 0, 2, 1],41 expected=['c', 'a', 'c', 'b']),42 dict(testcase_name='Params1DTensor_Indices2DRagged',43 params=['a', 'b', 'c', 'd', 'e'],44 indices=[[3, 1, 2], [1], [], [0]],45 expected=[['d', 'b', 'c'], ['b'], [], ['a']]),46 dict(testcase_name='Params2DRagged_Indices0DTensor',47 params=[['a', 'b'], ['c', 'd', 'e'], ['f'], [], ['g']],48 indices=1,49 expected=['c', 'd', 'e']),50 dict(testcase_name='Params2DRagged_Indices1DTensor',51 params=[['a', 'b', 'c'], ['d'], [], ['e']],52 indices=[3, 1, 2, 1, 0],53 expected=[54 ['e'], ['d'], [], ['d'], ['a', 'b', 'c']]),55 dict(testcase_name='Params2DRagged_Indices2DRagged',56 params=[['a', 'b', 'c'], ['d'], [], ['e']],57 indices=[[3, 1, 2], [1], [], [0]],58 expected=[59 [['e'], ['d'], []], [['d']], [], [['a', 'b', 'c']]]),60 dict(testcase_name='Params3DRagged_Indices2DTensor',61 params=[62 [['a', 'b'], []], [['c', 'd'], ['e'], ['f']], [['g']]],63 indices=[[1, 2], [0, 1], [2, 2]],64 indices_ragged_rank=0,65 expected=[66 [[['c', 'd'], ['e'], ['f']], [['g']]],67 [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]],68 [[['g']], [['g']]]]),69 dict(testcase_name='Params3DRagged_Indices3DTensor',70 params=[[['a', 'b'], []],71 [['c', 'd'], ['e'], ['f']],72 [['g']]],73 indices=[[[1, 2], [0, 1], [2, 2]], [[0, 0], [1, 2], [0, 1]]],74 indices_ragged_rank=0,75 expected=[76 [[[['c', 'd'], ['e'], ['f']], [['g']]],77 [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]],78 [[['g']], [['g']]]],79 [[[['a', 'b'], []], [['a', 'b'], []]],80 [[['c', 'd'], ['e'], ['f']], [['g']]],81 [[['a', 'b'], []], [['c', 'd'], ['e'], ['f']]]]]),82 dict(testcase_name='Params1DTensor_Indices4DRaggedRank2',83 params=['a', 'b', 'c', 'd', 'e', 'f', 'g'],84 indices=[[[[3, 4], [0, 6]], []],85 [[[2, 1], [1, 0]], [[2, 5]], [[2, 3]]],86 [[[1, 0]]]],87 indices_ragged_rank=2,88 expected=[89 [[['d', 'e'], ['a', 'g']], []],90 [[['c', 'b'], ['b', 'a']], [['c', 'f']], [['c', 'd']]],91 [[['b', 'a']]]]),92 # Batch gather (batch_dims=1)93 dict(testcase_name='Batch1D_Params2DRagged_Indices1DTensor',94 params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],95 indices=[1, 0, 3, 0],96 batch_dims=1,97 expected=['b', 'c', 'g', 'h']),98 dict(testcase_name='Batch1D_Params2DRagged_Indices2DTensor',99 params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],100 indices=[[1, 0], [0, 0], [3, 1], [0, 0]],101 indices_ragged_rank=0,102 batch_dims=1,103 expected=[['b', 'a'], ['c', 'c'], ['g', 'e'], ['h', 'h']]),104 dict(testcase_name='Batch1D_Params2DRagged_Indices2DRagged',105 params=[['a', 'b'], ['c'], ['d', 'e', 'f', 'g'], ['h']],106 indices=[[1, 0], [], [3, 2, 1], [0]],107 batch_dims=1,108 expected=[['b', 'a'], [], ['g', 'f', 'e'], ['h']]),109 dict(testcase_name='Batch1D_Params3DRagged_Indices3DRagged',110 params=[[['a'], ['b', 'c']],111 [],112 [['d', 'e', 'f'], ['g'], ['h', 'i'], ['j']],113 [['k']]],114 indices=[[[1, 0], []], [], [[3, 2, 1], [0]], [[0]]],115 batch_dims=1,116 expected=[[[['b', 'c'], ['a']], []],117 [],118 [[['j'], ['h', 'i'], ['g']], [['d', 'e', 'f']]],119 [[['k']]]]),120 # Batch gather (batch_dims=2)121 dict(testcase_name='Batch2D_Params3DRagged_Indices2DRagged',122 params=[[['a', 'b', 'c'], ['d', 'e'], ['f']],123 [['g'], ['h', 'i']]],124 indices=[[0, 1, 0], [0, 1]],125 batch_dims=2,126 expected=[['a', 'e', 'f'], ['g', 'i']]),127 dict(testcase_name='Batch2D_Params3DRagged_Indices3DRagged',128 params=[[['a', 'b', 'c'], ['d', 'e'], ['f']],129 [['g'], ['h', 'i']]],130 indices=[[[2, 1, 0], [1, 1], [0]], [[0], []]],131 batch_dims=2,132 expected=[[['c', 'b', 'a'], ['e', 'e'], ['f']], [['g'], []]]),133 # Batch gather (batch_dims=3)134 dict(testcase_name='Batch3D_Params4DRagged_Indices3DRagged',135 params=[[[['a', 'b', 'c'], ['d', 'e'], ['f']],136 [['g'], ['h', 'i']]], [[['j']]]],137 indices=[[[0, 1, 0], [0, 1]], [[0]]],138 batch_dims=3,139 expected=[[['a', 'e', 'f'], ['g', 'i']], [['j']]]),140 ]) # pyformat: disable141 def testRaggedGather(self,142 params,143 indices,144 expected,145 axis=None,146 batch_dims=0,147 params_ragged_rank=None,148 indices_ragged_rank=None):149 params = ragged_factory_ops.constant(params, ragged_rank=params_ragged_rank)150 indices = ragged_factory_ops.constant(151 indices, ragged_rank=indices_ragged_rank)152 actual = ragged_gather_ops.gather(153 params, indices, axis=axis, batch_dims=batch_dims)154 self.assertAllEqual(actual, self._str_to_bytes(expected))155 def _str_to_bytes(self, x):156 if isinstance(x, list):157 return [self._str_to_bytes(v) for v in x]158 elif isinstance(x, str) and bytes is not str:159 return bytes(x, 'utf-8')160 else:161 return x162 def testOutOfBoundsError(self):163 tensor_params = ['a', 'b', 'c']164 tensor_indices = [0, 1, 2]165 ragged_params = ragged_factory_ops.constant([['a', 'b'], ['c']])166 ragged_indices = ragged_factory_ops.constant([[0, 3]])167 with self.assertRaisesRegexp(errors.InvalidArgumentError,168 r'indices\[1\] = 3 is not in \[0, 3\)'):169 self.evaluate(ragged_gather_ops.gather(tensor_params, ragged_indices))170 with self.assertRaisesRegexp(errors.InvalidArgumentError,171 r'indices\[2\] = 2 is not in \[0, 2\)'):172 self.evaluate(ragged_gather_ops.gather(ragged_params, tensor_indices))173 with self.assertRaisesRegexp(errors.InvalidArgumentError,174 r'indices\[1\] = 3 is not in \[0, 2\)'):175 self.evaluate(ragged_gather_ops.gather(ragged_params, ragged_indices))176 def testUnknownIndicesRankError(self):177 if context.executing_eagerly():178 return179 params = ragged_factory_ops.constant([], ragged_rank=1)180 indices = constant_op.constant([0], dtype=dtypes.int64)181 indices = array_ops.placeholder_with_default(indices, None)182 self.assertRaisesRegexp(ValueError,183 r'rank\(indices\) must be known statically',184 ragged_gather_ops.gather, params, indices)185 # pylint: disable=bad-whitespace186 @parameterized.parameters([187 # params.shape=[2, None]; indices.shape=[3]188 dict(189 params = [[1.0, 2.0], [3.0, 4.0, 5.0]],190 indices = [0, 0, 1],191 expected_out = [[1.0, 2.0], [1.0, 2.0], [3.0, 4.0, 5.0]],192 out_grad = [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6, 0.7]],193 expected_grad = [[0.4, 0.6], [0.5, 0.6, 0.7]]),194 # params.shape=[2, None]; indices.shape=[0]195 dict(196 params = [[1, 2], [3, 4, 5]],197 indices = [],198 expected_out = [],199 out_grad = [],200 expected_grad = [[0, 0], [0, 0, 0]]),201 # params.shape=[2, None]; indices.shape=[2, 2]202 dict(203 params = [[1.0, 2.0], [3.0, 4.0, 5.0]],204 indices = [[0, 0], [1, 0]],205 expected_out = [[[1.0, 2.0], [1.0, 2.0]],206 [[3.0, 4.0, 5.0], [1.0, 2.0]]],207 out_grad = [[[0.1, 0.2], [0.3, 0.4]],208 [[0.5, 0.6, 0.7], [0.8, 0.9]]],209 expected_grad = [[1.2, 1.5], [0.5, 0.6, 0.7]]),210 # params.shape=[3, None, None]; indices.shape=[3]211 dict(212 params = [[[1, 2], [3, 4, 5]], [[6.0]], [[7.0, 8.0]]],213 indices = [2, 1, 2],214 expected_out = [[[7.0, 8.0]], [[6.0]], [[7.0, 8.0]]],215 out_grad = [[[0.1, 0.2]], [[0.3]], [[0.4, 0.5]]],216 expected_grad = [[[0, 0], [0, 0, 0]], [[0.3]], [[0.5, 0.7]]]),217 # params.shape=[3, None, None]; indices.shape=[0]218 dict(219 params = [[[1, 2], [3, 4, 5]], [[6.0]], [[7.0, 8.0]]],220 indices = [2, 1, 2],221 expected_out = [[[7.0, 8.0]], [[6.0]], [[7.0, 8.0]]],222 out_grad = [[[0.1, 0.2]], [[0.3]], [[0.4, 0.5]]],223 expected_grad = [[[0, 0], [0, 0, 0]], [[0.3]], [[0.5, 0.7]]]),224 # params.shape=[0, None]; indices.shape=[0]225 dict(226 params = [],227 indices = [],228 expected_out = [],229 out_grad = [],230 expected_grad = [],231 params_ragged_rank = 1),232 # params.shape=[2, None, 2]; indices.shape=[3]233 dict(234 params = [[[1, 2], [3, 4]], [], [[5, 6]]],235 indices = [1, 1, 2, 0, 2],236 expected_out = [[], [], [[5, 6]], [[1, 2], [3, 4]], [[5, 6]]],237 out_grad = [[], [], [[1, 2]], [[3, 4], [5, 6]], [[7, 7]]],238 expected_grad = [[[3, 4], [5, 6]], [], [[8, 9]]],239 params_ragged_rank = 1),240 ]) # pyformat: disable241 @test_util.run_deprecated_v1242 def testGradient(self,243 params,244 indices,245 expected_out,246 out_grad,247 expected_grad,248 params_ragged_rank=None):249 """Tests that ragged_gather generates the right gradient.250 Args:251 params: The `params` that should be passed to `gather`.252 indices: The `indices` that should be passed to `gather`.253 expected_out: The expected value of `gather(params, indices)`.254 `expected_out.shape = indices.shape + params.shape[1:]`.255 out_grad: The value that should be fed in as the gradient for `out`256 when testing the gradient of `ragged_gather`. Must have the same257 shape as `expected_out`.258 expected_grad: The expected gradient for that should be returned for259 `params`. Must have hte same shape as `params`.260 params_ragged_rank: The ragged_rank of `params`.261 """262 if context.executing_eagerly():263 return264 params = ragged_factory_ops.constant(265 params, dtype=dtypes.float32, ragged_rank=params_ragged_rank)266 indices = constant_op.constant(indices, dtype=dtypes.int32)267 out_ragged_rank = params.ragged_rank + indices.shape.ndims - 1268 out_grad = ragged_factory_ops.constant(269 out_grad, dtype=dtypes.float32, ragged_rank=out_ragged_rank)270 expected_out = ragged_factory_ops.constant(271 expected_out, dtype=dtypes.float32, ragged_rank=out_ragged_rank)272 expected_grad = ragged_factory_ops.constant(273 expected_grad,274 dtype=dtypes.float32,275 ragged_rank=params.ragged_rank)276 out = ragged_gather_ops.gather(params, indices)277 self.assertAllClose(out, expected_out)278 grads = gradients_impl.gradients(279 out.flat_values,280 (params.nested_row_splits + (params.flat_values, indices,)),281 out_grad.flat_values)282 param_nested_splits_grads = grads[:-2]283 params_flat_values_grad = grads[-2]284 indices_grad = grads[-1]285 self.assertEqual(indices_grad, None)286 for splits_grad in param_nested_splits_grads:287 self.assertEqual(splits_grad, None)288 # The gradient generates an IndexedSlices; convert back to a normal Tensor.289 self.assertIsInstance(params_flat_values_grad, indexed_slices.IndexedSlices)290 params_flat_values_grad = ops.convert_to_tensor(params_flat_values_grad)291 params_grad = params.with_flat_values(params_flat_values_grad)292 self.assertAllClose(params_grad, expected_grad, atol=2e-6, rtol=2e-6)293 @parameterized.parameters([294 # Basic gather (batch_dims == 0, axis == 0)295 dict(params_shape=[3, 4], indices_shape=[], axis=0),296 dict(params_shape=[3, 4], indices_shape=[5], axis=0),297 dict(params_shape=[3, 4], indices_shape=[2, 5], axis=0),298 # Gather over axis (axis > 0)299 dict(params_shape=[3, 4], indices_shape=[], axis=1),300 dict(params_shape=[3, 4], indices_shape=[2], axis=1),301 dict(params_shape=[3, 4], indices_shape=[2, 5], axis=1),302 dict(params_shape=[7, 3, 1], indices_shape=[2, 4], axis=1),303 dict(params_shape=[3, 4, 5, 6], indices_shape=[2, 1, 7], axis=1),304 dict(params_shape=[7, 3, 5], indices_shape=[], axis=2),305 dict(params_shape=[7, 3, 5], indices_shape=[2], axis=2),306 dict(params_shape=[7, 3, 5], indices_shape=[4, 2], axis=2),307 dict(params_shape=[7, 3, 5, 6], indices_shape=[4, 2], axis=2),308 dict(params_shape=[7, 3, 5, 6], indices_shape=[], axis=3),309 dict(params_shape=[7, 3, 5, 6], indices_shape=[4], axis=3),310 dict(params_shape=[7, 3, 5, 6], indices_shape=[8, 4], axis=3),311 dict(params_shape=[7, 3, 5, 6], indices_shape=[2, 3, 2, 3], axis=3),312 # Batched gather (batch_dims > 0)313 dict(params_shape=[7, 3], indices_shape=[7], batch_dims=1),314 dict(params_shape=[7, 3], indices_shape=[7, 5], batch_dims=1),315 dict(params_shape=[5, 3], indices_shape=[5, 7, 4, 2], batch_dims=1),316 dict(params_shape=[2, 3, 6], indices_shape=[2], batch_dims=1),317 dict(params_shape=[7, 3, 6], indices_shape=[7, 5, 4, 2], batch_dims=1),318 dict(params_shape=[7, 3, 5], indices_shape=[7, 3], batch_dims=2),319 dict(params_shape=[7, 3, 5], indices_shape=[7, 3, 2], batch_dims=2),320 dict(params_shape=[7, 3, 5, 6], indices_shape=[7, 3, 5], batch_dims=3),321 dict(params_shape=[2, 3, 5, 6], indices_shape=[2, 3, 5, 7], batch_dims=3),322 # Batched gather with axis (axis > batch_dims > 0)323 dict(params_shape=[2, 3, 6], indices_shape=[2], axis=2, batch_dims=1),324 dict(params_shape=[2, 3, 6], indices_shape=[2, 4], axis=2, batch_dims=1),325 dict(326 params_shape=[3, 1, 6, 7], indices_shape=[3, 4], axis=3,327 batch_dims=1),328 dict(329 params_shape=[3, 2, 6, 7], indices_shape=[3, 4], axis=3,330 batch_dims=1),331 dict(332 params_shape=[2, 3, 6, 7], indices_shape=[2, 3], axis=3,333 batch_dims=2),334 ])335 def testMatchesDenseGather(self,336 params_shape,337 indices_shape,338 axis=None,339 batch_dims=0):340 # Build random params & indices matrics w/ the expected shapes.341 if axis is None:342 axis = batch_dims343 params = np.random.randint(100, size=params_shape, dtype=np.int32)344 indices = np.random.randint(345 params_shape[axis], size=indices_shape, dtype=np.int32)346 # Use array_ops.gather to get the expected value.347 expected = array_ops.gather(348 params, indices, axis=axis, batch_dims=batch_dims)349 # Build ragged tensors with varying ragged_ranks from params & axis.350 params_tensors = [params] + [351 ragged_tensor.RaggedTensor.from_tensor(params, ragged_rank=i)352 for i in range(1, len(params_shape))353 ]354 indices_tensors = [indices] + [355 ragged_tensor.RaggedTensor.from_tensor(indices, ragged_rank=i)356 for i in range(1, len(indices_shape))357 ]358 # For each combination of params & axis tensors, check that359 # ragged_gather_ops.gather matches array_ops.gather.360 for params_tensor in params_tensors:361 for indices_tensor in indices_tensors:362 actual = ragged_gather_ops.gather(363 params_tensor, indices_tensor, axis=axis, batch_dims=batch_dims)364 if isinstance(actual, ragged_tensor.RaggedTensor):365 actual = actual.to_tensor()366 self.assertAllEqual(367 expected, actual, 'params.ragged_rank=%s, indices.ragged_rank=%s' %368 (getattr(params_tensor, 'ragged_rank',369 0), getattr(indices_tensor, 'ragged_rank', 0)))370if __name__ == '__main__':...
params_dict_test.py
Source:params_dict_test.py
1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for official.modeling.hyperparams.params_dict.py."""16import os17import tensorflow as tf18import yaml19from official.modeling.hyperparams import params_dict20class ParamsDictTest(tf.test.TestCase):21 def test_init_from_an_empty_dict(self):22 params = params_dict.ParamsDict()23 with self.assertRaises(AttributeError):24 _ = params.a25 with self.assertRaises(KeyError):26 params.a = 'aa'27 def test_init_from_a_dict(self):28 params = params_dict.ParamsDict({'a': 'aa', 'b': 2})29 self.assertEqual(params.a, 'aa')30 self.assertEqual(params.b, 2)31 def test_init_from_a_param_dict(self):32 params_init = params_dict.ParamsDict({'a': 'aa', 'b': 2})33 params = params_dict.ParamsDict(params_init)34 self.assertEqual(params.a, 'aa')35 self.assertEqual(params.b, 2)36 def test_lock(self):37 params = params_dict.ParamsDict({'a': 1, 'b': 2})38 params.lock()39 with self.assertRaises(ValueError):40 params.a = 1041 with self.assertRaises(ValueError):42 params.override({'b': 20})43 def test_setattr(self):44 params = params_dict.ParamsDict()45 params.override(46 {'a': 'aa', 'b': 2, 'c': None}, is_strict=False)47 params.c = 'ccc'48 self.assertEqual(params.a, 'aa')49 self.assertEqual(params.b, 2)50 self.assertEqual(params.c, 'ccc')51 def test_getattr(self):52 params = params_dict.ParamsDict()53 params.override(54 {'a': 'aa', 'b': 2, 'c': None}, is_strict=False)55 self.assertEqual(params.a, 'aa')56 self.assertEqual(params.b, 2)57 self.assertEqual(params.c, None)58 def test_contains(self):59 params = params_dict.ParamsDict()60 params.override(61 {'a': 'aa'}, is_strict=False)62 self.assertIn('a', params)63 self.assertNotIn('b', params)64 def test_get(self):65 params = params_dict.ParamsDict()66 params.override(67 {'a': 'aa'}, is_strict=False)68 self.assertEqual(params.get('a'), 'aa')69 self.assertEqual(params.get('b', 2), 2)70 self.assertEqual(params.get('b'), None)71 def test_override_is_strict_true(self):72 params = params_dict.ParamsDict(73 {'a': 'aa', 'b': 2, 'c': {'c1': 'cc', 'c2': 20}})74 params.override({'a': 2, 'c': {'c1': 'ccc'}}, is_strict=True)75 self.assertEqual(params.a, 2)76 self.assertEqual(params.c.c1, 'ccc')77 with self.assertRaises(KeyError):78 params.override({'d': 'ddd'}, is_strict=True)79 with self.assertRaises(KeyError):80 params.override({'c': {'c3': 30}}, is_strict=True)81 def test_override_is_strict_false(self):82 params = params_dict.ParamsDict(83 {'a': 'aa', 'b': 2, 'c': {'c1': 10, 'c2': 20}})84 params.override({'a': 2, 'c': {'c3': 3000}}, is_strict=False)85 self.assertEqual(params.a, 2)86 self.assertEqual(params.c.c3, 3000)87 params.override({'d': 'ddd'}, is_strict=False)88 self.assertEqual(params.d, 'ddd')89 params.override({'c': {'c4': 4444}}, is_strict=False)90 self.assertEqual(params.c.c4, 4444)91 def test_as_dict(self):92 params = params_dict.ParamsDict(93 {'a': 'aa', 'b': 2, 'c': {'c1': 10, 'c2': 20}})94 params_d = params.as_dict()95 self.assertEqual(params_d['a'], 'aa')96 self.assertEqual(params_d['b'], 2)97 self.assertEqual(params_d['c']['c1'], 10)98 self.assertEqual(params_d['c']['c2'], 20)99 def test_validate(self):100 # Raise error due to the unknown parameter.101 with self.assertRaises(KeyError):102 params = params_dict.ParamsDict(103 {'a': 1, 'b': {'a': 11}}, ['a == c'])104 # OK to check equality of two nested dicts.105 params = params_dict.ParamsDict(106 {'a': 1, 'b': {'a': 10}, 'c': {'a': 10}}, ['b == c'])107 # Raise error due to inconsistency108 with self.assertRaises(KeyError):109 params = params_dict.ParamsDict(110 {'a': 1, 'c': {'a': 10}}, ['a == c.a'])111 # Valid rule.112 params = params_dict.ParamsDict(113 {'a': 1, 'c': {'a': 1}}, ['a == c.a'])114 # Overridding violates the existing rule, raise error upon validate.115 params.override({'a': 11})116 with self.assertRaises(KeyError):117 params.validate()118class ParamsDictIOTest(tf.test.TestCase):119 def write_temp_file(self, filename, text):120 temp_file = os.path.join(self.get_temp_dir(), filename)121 with tf.io.gfile.GFile(temp_file, 'w') as writer:122 writer.write(text)123 return temp_file124 def test_save_params_dict_to_yaml(self):125 params = params_dict.ParamsDict(126 {'a': 'aa', 'b': 2, 'c': {'c1': 10, 'c2': 20}})127 output_yaml_file = os.path.join(self.get_temp_dir(), 'params.yaml')128 params_dict.save_params_dict_to_yaml(params, output_yaml_file)129 with tf.io.gfile.GFile(output_yaml_file, 'r') as f:130 params_d = yaml.load(f)131 self.assertEqual(params.a, params_d['a'])132 self.assertEqual(params.b, params_d['b'])133 self.assertEqual(params.c.c1, params_d['c']['c1'])134 self.assertEqual(params.c.c2, params_d['c']['c2'])135 def test_read_yaml_to_params_dict(self):136 input_yaml_file = self.write_temp_file(137 'params.yaml', r"""138 a: 'aa'139 b: 2140 c:141 c1: 10142 c2: 20143 """)144 params = params_dict.read_yaml_to_params_dict(input_yaml_file)145 self.assertEqual(params.a, 'aa')146 self.assertEqual(params.b, 2)147 self.assertEqual(params.c.c1, 10)148 self.assertEqual(params.c.c2, 20)149 def test_override_params_dict_using_dict(self):150 params = params_dict.ParamsDict({151 'a': 1, 'b': 2.5, 'c': [3, 4], 'd': 'hello', 'e': False})152 override_dict = {'b': 5.2, 'c': [30, 40]}153 params = params_dict.override_params_dict(154 params, override_dict, is_strict=True)155 self.assertEqual(1, params.a)156 self.assertEqual(5.2, params.b)157 self.assertEqual([30, 40], params.c)158 self.assertEqual('hello', params.d)159 self.assertEqual(False, params.e)160 def test_override_params_dict_using_yaml_string(self):161 params = params_dict.ParamsDict({162 'a': 1, 'b': 2.5, 'c': [3, 4], 'd': 'hello', 'e': False})163 override_yaml_string = "'b': 5.2\n'c': [30, 40]"164 params = params_dict.override_params_dict(165 params, override_yaml_string, is_strict=True)166 self.assertEqual(1, params.a)167 self.assertEqual(5.2, params.b)168 self.assertEqual([30, 40], params.c)169 self.assertEqual('hello', params.d)170 self.assertEqual(False, params.e)171 def test_override_params_dict_using_json_string(self):172 params = params_dict.ParamsDict({173 'a': 1, 'b': {'b1': 2, 'b2': [2, 3],},174 'd': {'d1': {'d2': 'hello'}}, 'e': False})175 override_json_string = "{ b: { b2: [3, 4] }, d: { d1: { d2: 'hi' } } }"176 params = params_dict.override_params_dict(177 params, override_json_string, is_strict=True)178 self.assertEqual(1, params.a)179 self.assertEqual(2, params.b.b1)180 self.assertEqual([3, 4], params.b.b2)181 self.assertEqual('hi', params.d.d1.d2)182 self.assertEqual(False, params.e)183 def test_override_params_dict_using_csv_string(self):184 params = params_dict.ParamsDict({185 'a': 1, 'b': {'b1': 2, 'b2': [2, 3],},186 'd': {'d1': {'d2': 'hello'}}, 'e': False})187 override_csv_string = "b.b2=[3,4], d.d1.d2='hi, world', e=gs://test"188 params = params_dict.override_params_dict(189 params, override_csv_string, is_strict=True)190 self.assertEqual(1, params.a)191 self.assertEqual(2, params.b.b1)192 self.assertEqual([3, 4], params.b.b2)193 self.assertEqual('hi, world', params.d.d1.d2)194 self.assertEqual('gs://test', params.e)195 def test_override_params_dict_using_yaml_file(self):196 params = params_dict.ParamsDict({197 'a': 1, 'b': 2.5, 'c': [3, 4], 'd': 'hello', 'e': False})198 override_yaml_file = self.write_temp_file(199 'params.yaml', r"""200 b: 5.2201 c: [30, 40]202 """)203 params = params_dict.override_params_dict(204 params, override_yaml_file, is_strict=True)205 self.assertEqual(1, params.a)206 self.assertEqual(5.2, params.b)207 self.assertEqual([30, 40], params.c)208 self.assertEqual('hello', params.d)209 self.assertEqual(False, params.e)210class IOTest(tf.test.TestCase):211 def test_basic_csv_str_to_json_str(self):212 csv_str = 'a=1,b=2,c=3'213 json_str = '{a : 1, b : 2, c : 3}'214 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)215 self.assertEqual(converted_csv_str, json_str)216 def test_basic_csv_str_load(self):217 csv_str = 'a=1,b=2,c=3'218 expected_output = {'a': 1, 'b': 2, 'c': 3}219 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)220 converted_dict = yaml.load(converted_csv_str)221 self.assertDictEqual(converted_dict, expected_output)222 def test_basic_nested_csv_str_to_json_str(self):223 csv_str = 'a=1,b.b1=2'224 json_str = '{a : 1, b : {b1 : 2}}'225 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)226 self.assertEqual(converted_csv_str, json_str)227 def test_basic_nested_csv_str_load(self):228 csv_str = 'a=1,b.b1=2,c.c1=3'229 expected_output = {'a': 1, 'b': {'b1': 2}, 'c': {'c1': 3}}230 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)231 converted_dict = yaml.load(converted_csv_str)232 self.assertDictEqual(converted_dict, expected_output)233 def test_complex_nested_csv_str_to_json_str(self):234 csv_str = 'a.aa.aaa.aaaaa.a=1'235 json_str = '{a : {aa : {aaa : {aaaaa : {a : 1}}}}}'236 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)237 self.assertEqual(converted_csv_str, json_str)238 def test_complex_nested_csv_str_load(self):239 csv_str = 'a.aa.aaa.aaaaa.a=1,a.a=2'240 expected_output = {'a': {'aa': {'aaa': {'aaaaa': {'a': 1}}}, 'a': 2}}241 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)242 converted_dict = yaml.load(converted_csv_str)243 self.assertDictEqual(converted_dict, expected_output)244 def test_csv_str_load_supported_datatypes(self):245 csv_str = 'a=1,b=2.,c=[1,2,3],d=\'hello, there\',e=\"Hi.\"'246 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)247 converted_dict = yaml.load(converted_csv_str)248 self.assertEqual(converted_dict['a'], 1)249 self.assertEqual(converted_dict['b'], 2.)250 self.assertEqual(converted_dict['c'], [1, 2, 3])251 self.assertEqual(converted_dict['d'], 'hello, there')252 self.assertEqual(converted_dict['e'], 'Hi.')253 def test_csv_str_load_unsupported_datatypes(self):254 csv_str = 'a=[[1,2,3],[4,5,6]]'255 self.assertRaises(ValueError,256 params_dict.nested_csv_str_to_json_str,257 csv_str)258 def test_csv_str_to_json_str_spacing(self):259 csv_str1 = 'a=1,b=2,c=3'260 csv_str2 = 'a = 1, b = 2, c = 3'261 json_str = '{a : 1, b : 2, c : 3}'262 converted_csv_str1 = params_dict.nested_csv_str_to_json_str(csv_str1)263 converted_csv_str2 = params_dict.nested_csv_str_to_json_str(csv_str2)264 self.assertEqual(converted_csv_str1, converted_csv_str2)265 self.assertEqual(converted_csv_str1, json_str)266 self.assertEqual(converted_csv_str2, json_str)267 def test_gcs_added_quotes(self):268 csv_str = 'a=gs://abc, b=gs://def'269 expected_output = '{a : \'gs://abc\', b : \'gs://def\'}'270 converted_csv_str = params_dict.nested_csv_str_to_json_str(csv_str)271 self.assertEqual(converted_csv_str, expected_output)272if __name__ == '__main__':...
validate.py
Source:validate.py
2import re3import logging4import os5import json6def validate_params(params):7 """What do we expect params to have as keys:8 genome_ref9 mutantpool_ref10 exps_ref11 sets_ref12 output_name13 workspace_name14 Returns: ^ with strings as values for all15 """16 for p in ["genome_ref", "mutantpool_ref", "exps_ref"]:17 if p not in params:18 raise Exception(p + " missing from params.")19 elif len(params[p].split('/')) != 3:20 raise Exception(p + " doesn't have form A/B/C as expected:\n"...
models.py
Source:models.py
...74 grouper = ParamGrouper(self.model)75 noptim = params.optim.args.copy()76 noptim['weight_decay'] = 077 param_groups = [78 grouper.create_param_group(grouper.kernel_params(with_norm=False), **params.optim.args),79 grouper.create_param_group(grouper.bias_params(with_norm=False), **noptim),80 grouper.create_param_group(grouper.norm_params(), **noptim),81 ]82 self.optim = params.optim.build(param_groups)83 if not params.distributed:84 self.to(self.device)85class SimCLRMixin(ModelMixin):86 """base end-to-end model"""87 def predict(self, xs) -> torch.Tensor:88 with torch.no_grad():89 if self.params.ema:90 model = self.ema_model91 else:92 model = self.model93 with torch.no_grad():94 return model.fc(model(xs))95 def models(self, params: SimCLRParams):96 params.with_fc = False97 backbone = load_backbone(params)98 from arch.ssmodel import ContrastiveModel99 model = ContrastiveModel(backbone, params.mid_dim,100 feature_dim=params.feature_dim,101 n_classes=params.n_classes)102 if params.distributed:103 from torch.nn.modules import SyncBatchNorm104 model = SyncBatchNorm.convert_sync_batchnorm(model.cuda())105 self.model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[params.local_rank])106 else:107 self.model = model108 if params.ema:109 self.ema_model = EMA(self.model)110 grouper = ParamGrouper(self.model)111 noptim = params.optim.args.copy()112 noptim['weight_decay'] = 0113 param_groups = [114 grouper.create_param_group(grouper.kernel_params(with_norm=False), **params.optim.args),115 grouper.create_param_group(grouper.bias_params(with_norm=False), **noptim),116 grouper.create_param_group(grouper.norm_params(), **noptim),117 ]118 self.optim = params.optim.build(param_groups)119 if not params.distributed:...
factory.py
Source:factory.py
1# Copyright 2019 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Model architecture factory."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19from official.vision.detection.dataloader import maskrcnn_parser20from official.vision.detection.dataloader import retinanet_parser21from official.vision.detection.dataloader import shapemask_parser22def parser_generator(params, mode):23 """Generator function for various dataset parser."""24 if params.architecture.parser == 'retinanet_parser':25 anchor_params = params.anchor26 parser_params = params.retinanet_parser27 parser_fn = retinanet_parser.Parser(28 output_size=parser_params.output_size,29 min_level=anchor_params.min_level,30 max_level=anchor_params.max_level,31 num_scales=anchor_params.num_scales,32 aspect_ratios=anchor_params.aspect_ratios,33 anchor_size=anchor_params.anchor_size,34 match_threshold=parser_params.match_threshold,35 unmatched_threshold=parser_params.unmatched_threshold,36 aug_rand_hflip=parser_params.aug_rand_hflip,37 aug_scale_min=parser_params.aug_scale_min,38 aug_scale_max=parser_params.aug_scale_max,39 use_autoaugment=parser_params.use_autoaugment,40 autoaugment_policy_name=parser_params.autoaugment_policy_name,41 skip_crowd_during_training=parser_params.skip_crowd_during_training,42 max_num_instances=parser_params.max_num_instances,43 use_bfloat16=parser_params.use_bfloat16,44 mode=mode)45 elif params.architecture.parser == 'maskrcnn_parser':46 anchor_params = params.anchor47 parser_params = params.maskrcnn_parser48 parser_fn = maskrcnn_parser.Parser(49 output_size=parser_params.output_size,50 min_level=anchor_params.min_level,51 max_level=anchor_params.max_level,52 num_scales=anchor_params.num_scales,53 aspect_ratios=anchor_params.aspect_ratios,54 anchor_size=anchor_params.anchor_size,55 rpn_match_threshold=parser_params.rpn_match_threshold,56 rpn_unmatched_threshold=parser_params.rpn_unmatched_threshold,57 rpn_batch_size_per_im=parser_params.rpn_batch_size_per_im,58 rpn_fg_fraction=parser_params.rpn_fg_fraction,59 aug_rand_hflip=parser_params.aug_rand_hflip,60 aug_scale_min=parser_params.aug_scale_min,61 aug_scale_max=parser_params.aug_scale_max,62 skip_crowd_during_training=parser_params.skip_crowd_during_training,63 max_num_instances=parser_params.max_num_instances,64 include_mask=parser_params.include_mask,65 mask_crop_size=parser_params.mask_crop_size,66 use_bfloat16=parser_params.use_bfloat16,67 mode=mode)68 elif params.architecture.parser == 'shapemask_parser':69 anchor_params = params.anchor70 parser_params = params.shapemask_parser71 parser_fn = shapemask_parser.Parser(72 output_size=parser_params.output_size,73 min_level=anchor_params.min_level,74 max_level=anchor_params.max_level,75 num_scales=anchor_params.num_scales,76 aspect_ratios=anchor_params.aspect_ratios,77 anchor_size=anchor_params.anchor_size,78 use_category=parser_params.use_category,79 outer_box_scale=parser_params.outer_box_scale,80 box_jitter_scale=parser_params.box_jitter_scale,81 num_sampled_masks=parser_params.num_sampled_masks,82 mask_crop_size=parser_params.mask_crop_size,83 mask_min_level=parser_params.mask_min_level,84 mask_max_level=parser_params.mask_max_level,85 upsample_factor=parser_params.upsample_factor,86 match_threshold=parser_params.match_threshold,87 unmatched_threshold=parser_params.unmatched_threshold,88 aug_rand_hflip=parser_params.aug_rand_hflip,89 aug_scale_min=parser_params.aug_scale_min,90 aug_scale_max=parser_params.aug_scale_max,91 skip_crowd_during_training=parser_params.skip_crowd_during_training,92 max_num_instances=parser_params.max_num_instances,93 use_bfloat16=parser_params.use_bfloat16,94 mask_train_class=parser_params.mask_train_class,95 mode=mode)96 else:97 raise ValueError('Parser %s is not supported.' % params.architecture.parser)...
Using AI Code Generation
1var wpt = require('webpagetest');2var params = {3};4 if (err) return console.log(err);5 console.log(data);6});7var wpt = require('webpagetest');8var params = {9};10 if (err) return console.log(err);11 console.log(data);12});13var wpt = require('webpagetest');14var params = {15};16 if (err) return console.log(err);17 console.log(data);18});19var wpt = require('webpagetest');20var params = {21};22 if (err) return console.log(err);23 console.log(data);24});25var wpt = require('webpagetest');26var params = {27};28 if (err) return console.log(err);29 console.log(data);30});
Using AI Code Generation
1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org');3}, function(err, data) {4 if (err) return console.error(err);5 console.log('Test status: ' + data.statusText);6 console.log('View results at: ' + data.data.userUrl);7});8var wpt = require('webpagetest');9var test = wpt('www.webpagetest.org');10}, function(err, data) {11 if (err) return console.error(err);12 console.log('Test status: ' + data.statusText);13 console.log('View results at: ' + data.data.userUrl);14});15var wpt = require('webpagetest');16var test = wpt('www.webpagetest.org');17}, function(err, data) {18 if (err) return console.error(err);19 console.log('Test status: ' + data.statusText);20 console.log('View results at: ' + data.data.userUrl);21});22var wpt = require('webpagetest');23var test = wpt('www.webpagetest.org');24}, function(err, data) {25 if (err) return console.error(err);26 console.log('Test status: ' + data.statusText);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!