Search is not available for this dataset
text
stringlengths
75
104k
def upload_file(self, filepath): """ 上传素材 (图片/音频/视频) :param filepath: 本地文件路径 :return: 直接返回上传后的文件 ID (fid) :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可 (常见错误内容: ``file not exist``: 找不到本地文件, ``audio too long``: 音频文件过长, ``file invalid type``: 文件格式不正确, 还有其他错误请自行检查) """ self._init_ticket() url = 'https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&ticket_id={ticket_id}&ticket={ticket}&token={token}&lang=zh_CN'.format( ticket_id=self.__ticket_id, ticket=self.__ticket, token=self.__token, ) try: files = {'file': open(filepath, 'rb')} except IOError: raise ValueError('file not exist') payloads = { 'Filename': filepath, 'folder': '/cgi-bin/uploads', 'Upload': 'Submit Query', } headers = { 'referer': 'http://mp.weixin.qq.com/cgi-bin/indexpage?t=wxm-upload&lang=zh_CN&type=2&formId=1', 'cookie': self.__cookies, } r = requests.post(url, files=files, data=payloads, headers=headers) try: message = json.loads(r.text) except ValueError: raise NeedLoginError(r.text) try: if message['base_resp']['ret'] != 0: raise ValueError(message['base_resp']['err_msg']) except KeyError: raise NeedLoginError(r.text) return message['content']
def send_file(self, fakeid, fid, type): """ 向特定用户发送媒体文件 :param fakeid: 用户 UID (即 fakeid) :param fid: 文件 ID :param type: 文件类型 (2: 图片, 3: 音频, 15: 视频) :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可 (常见错误内容: ``system error`` 或 ``can not send this type of msg``: 文件类型不匹配, ``user not exist``: 用户 fakeid 不存在, ``file not exist``: 文件 fid 不存在, 还有其他错误请自行检查) """ if type == 4: # 此处判断为兼容历史版本, 微信官方已经将视频类型修改为 15 type = 15 url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token={token}&lang=zh_CN'.format( token=self.__token, ) payloads = {} if type == 2 or type == 3: # 如果文件类型是图片或者音频 payloads = { 'token': self.__token, 'lang': 'zh_CN', 'f': 'json', 'ajax': 1, 'random': random.random(), 'type': type, 'file_id': fid, 'tofakeid': fakeid, 'fileid': fid, 'imgcode': '', } elif type == 15: # 如果文件类型是视频 payloads = { 'token': self.__token, 'lang': 'zh_CN', 'f': 'json', 'ajax': 1, 'random': random.random(), 'type': type, 'app_id': fid, 'tofakeid': fakeid, 'appmsgid': fid, 'imgcode': '', } headers = { 'referer': 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?tofakeid={fakeid}&t=message/send&action=index&token={token}&lang=zh_CN'.format( fakeid=fakeid, token=self.__token, ), 'cookie': self.__cookies, 'x-requested-with': 'XMLHttpRequest', } r = requests.post(url, data=payloads, headers=headers) try: message = json.loads(r.text) except ValueError: raise NeedLoginError(r.text) try: if message['base_resp']['ret'] != 0: raise ValueError(message['base_resp']['err_msg']) except KeyError: raise NeedLoginError(r.text)
def get_user_info(self, fakeid): """ 获取指定用户的个人信息 返回JSON示例:: { "province": "湖北", "city": "武汉", "gender": 1, "nick_name": "Doraemonext", "country": "中国", "remark_name": "", "fake_id": 844735403, "signature": "", "group_id": 0, "user_name": "" } :param fakeid: 用户的 UID (即 fakeid) :return: 返回的 JSON 数据 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 """ url = 'https://mp.weixin.qq.com/cgi-bin/getcontactinfo' payloads = { 'ajax': 1, 'lang': 'zh_CN', 'random': round(random.random(), 3), 'token': self.__token, 't': 'ajax-getcontactinfo', 'fakeid': fakeid, } headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token={token}'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.post(url, data=payloads, headers=headers) try: message = json.dumps(json.loads(r.text)['contact_info'], ensure_ascii=False) except (KeyError, ValueError): raise NeedLoginError(r.text) return message
def get_avatar(self, fakeid): """ 获取用户头像信息 :param fakeid: 用户的 UID (即 fakeid) :return: 二进制 JPG 数据字符串, 可直接作为 File Object 中 write 的参数 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 """ url = 'https://mp.weixin.qq.com/misc/getheadimg?fakeid={fakeid}&token={token}&lang=zh_CN'.format( fakeid=fakeid, token=self.__token, ) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token={token}'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.get(url, headers=headers, stream=True) return r.raw.data
def get_new_message_num(self, lastid=0): """ 获取新消息的数目 :param lastid: 最近获取的消息 ID, 为 0 时获取总消息数目 :return: 消息数目 """ url = 'https://mp.weixin.qq.com/cgi-bin/getnewmsgnum?f=json&t=ajax-getmsgnum&lastmsgid={lastid}&token={token}&lang=zh_CN'.format( lastid=lastid, token=self.__token, ) payloads = { 'ajax': 1, 'f': 'json', 'random': random.random(), 'lang': 'zh_CN', 'token': self.__token, } headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token={token}&lang=zh_CN'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.get(url, data=payloads, headers=headers) try: return int(json.loads(r.text)['newTotalMsgCount']) except (KeyError, ValueError): raise NeedLoginError(r.text)
def get_message_list(self, lastid=0, offset=0, count=20, day=7, star=False): """ 获取消息列表 返回JSON示例:: { "msg_item": [ { "id": 206439583, "type": 1, "fakeid": "844735403", "nick_name": "Doraemonext", "date_time": 1408671892, "content": "测试消息", "source": "", "msg_status": 4, "has_reply": 0, "refuse_reason": "", "multi_item": [ ], "to_uin": 2391068708, "send_stat": { "total": 0, "succ": 0, "fail": 0 } }, { "id": 206439579, "type": 1, "fakeid": "844735403", "nick_name": "Doraemonext", "date_time": 1408671889, "content": "wechat-python-sdk", "source": "", "msg_status": 4, "has_reply": 0, "refuse_reason": "", "multi_item": [ ], "to_uin": 2391068708, "send_stat": { "total": 0, "succ": 0, "fail": 0 } } ] } :param lastid: 传入最后的消息 id 编号, 为 0 则从最新一条起倒序获取 :param offset: lastid 起算第一条的偏移量 :param count: 获取数目 :param day: 最近几天消息 (0: 今天, 1: 昨天, 2: 前天, 3: 更早, 7: 全部), 这里的全部仅有5天 :param star: 是否只获取星标消息 :return: 返回的 JSON 数据 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 """ if star: star_param = '&action=star' else: star_param = '' if lastid == 0: lastid = '' url = 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&f=json&lang=zh_CN{star}&count={count}&day={day}&frommsgid={lastid}&offset={offset}&token={token}'.format( star=star_param, count=count, day=day, lastid=lastid, offset=offset, token=self.__token, ) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token={token}&lang=zh_CN'.format(token=self.__token), 'cookie': self.__cookies, } r = requests.get(url, headers=headers) try: message = json.loads(r.text)['msg_items'] except (KeyError, ValueError): raise NeedLoginError(r.text) return message
def get_message_voice(self, msgid): """ 根据消息 ID 获取语音消息内容 :param msgid: 消息 ID :return: 二进制 MP3 音频字符串, 可直接作为 File Object 中 write 的参数 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可, 错误内容: ``voice message not exist``: msg参数无效 """ url = 'https://mp.weixin.qq.com/cgi-bin/getvoicedata?msgid={msgid}&fileid=&token={token}&lang=zh_CN'.format( msgid=msgid, token=self.__token, ) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&token={token}&count=20&day=7'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.get(url, headers=headers, stream=True) # 检测会话是否超时 if r.headers.get('content-type', None) == 'text/html; charset=UTF-8': raise NeedLoginError(r.text) # 检测语音是否存在 if not r.raw.data: raise ValueError('voice message not exist') return r.raw.data
def _init_self_information(self): """ 初始化公众号自身的属性值 (目前包括 ``Ticket`` 值 及 公众号自身的 ``fakeid`` 值) :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 """ url = 'https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token={token}'.format(token=self.__token) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com', 'cookie': self.__cookies, } r = requests.get(url, headers=headers) # 获取 Ticket ID 值 ticket_id = re.search(r'user_name:\"(.*)\"', r.text) if not ticket_id: raise NeedLoginError(r.text) self.__ticket_id = ticket_id.group(1) # 获取 Ticket 值 ticket = re.search(r'ticket:\"(.*)\"', r.text) if not ticket: raise NeedLoginError(r.text) self.__ticket = ticket.group(1) # 获取公众号自身的 fakeid 值 fakeid = re.search(r'uin:\"(.*)\"', r.text) if not fakeid: raise NeedLoginError(r.text) self.__fakeid = fakeid.group(1)
def _init_plugin_token_appid(self): """ 初始化公众号的 ``PluginToken`` 值及公众号自身的 ``appid`` 值 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 """ if not self.__plugin_token or not self.__appid: url = 'https://mp.weixin.qq.com/misc/pluginloginpage?action=stat_article_detail&pluginid=luopan&t=statistics/index&token={token}&lang=zh_CN'.format( token=self.__token, ) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/misc/pluginloginpage?action=stat_article_detail&pluginid=luopan&t=statistics/index&token={token}&lang=zh_CN'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.get(url, headers=headers) plugin_token = re.search(r"pluginToken : '(\S+)',", r.text) if not plugin_token: raise NeedLoginError(r.text) self.__plugin_token = plugin_token.group(1) appid = re.search(r"appid : '(\S+)',", r.text) if not appid: raise NeedLoginError(r.text) self.__appid = appid.group(1)
def set_appid_appsecret(self, appid, appsecret): """ 设置当前 App ID 及 App Secret""" self.__appid = appid self.__appsecret = appsecret self._update_crypto()
def access_token(self): """ 获取当前 access token 值, 本方法会自行维护 access token 有效性 """ self._check_appid_appsecret() if callable(self.__access_token_getfunc): self.__access_token, self.__access_token_expires_at = self.__access_token_getfunc() if self.__access_token: now = time.time() if self.__access_token_expires_at - now > 60: return self.__access_token self.grant_access_token() # 从腾讯服务器获取 access token 并更新 return self.__access_token
def jsapi_ticket(self): """ 获取当前 jsapi ticket 值, 本方法会自行维护 jsapi ticket 有效性 """ self._check_appid_appsecret() if callable(self.__jsapi_ticket_getfunc): self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self.__jsapi_ticket_getfunc() if self.__jsapi_ticket: now = time.time() if self.__jsapi_ticket_expires_at - now > 60: return self.__jsapi_ticket self.grant_jsapi_ticket() # 从腾讯服务器获取 jsapi ticket 并更新 return self.__jsapi_ticket
def grant_access_token(self): """ 获取 access token 并更新当前配置 :return: 返回的 JSON 数据包 (传入 access_token_refreshfunc 参数后返回 None) """ self._check_appid_appsecret() if callable(self.__access_token_refreshfunc): self.__access_token, self.__access_token_expires_at = self.__access_token_refreshfunc() return response_json = self.__request.get( url="https://api.weixin.qq.com/cgi-bin/token", params={ "grant_type": "client_credential", "appid": self.__appid, "secret": self.__appsecret, }, access_token=self.__access_token ) self.__access_token = response_json['access_token'] self.__access_token_expires_at = int(time.time()) + response_json['expires_in'] if callable(self.__access_token_setfunc): self.__access_token_setfunc(self.__access_token, self.__access_token_expires_at) return response_json
def grant_jsapi_ticket(self): """ 获取 jsapi ticket 并更新当前配置 :return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 None) """ self._check_appid_appsecret() if callable(self.__jsapi_ticket_refreshfunc): self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self.__jsapi_ticket_refreshfunc() return response_json = self.__request.get( url="https://api.weixin.qq.com/cgi-bin/ticket/getticket", params={ "type": "jsapi", }, access_token=self.access_token, ) self.__jsapi_ticket = response_json['ticket'] self.__jsapi_ticket_expires_at = int(time.time()) + response_json['expires_in'] if callable(self.__jsapi_ticket_setfunc): self.__jsapi_ticket_setfunc(self.__jsapi_ticket, self.__jsapi_ticket_expires_at) return response_json
def _update_crypto(self): """ 根据当前配置内容更新 Crypto 类 """ if self.__encrypt_mode in ['compatible', 'safe'] and self.__encoding_aes_key is not None: if self.__token is None or self.__appid is None: raise NeedParamError('Please provide token and appid parameters in the construction of class.') self.__crypto = BasicCrypto(self.__token, self.__encoding_aes_key, self.__appid) else: self.__crypto = None
def conf(self, conf): """ 设置当前 WechatConf 实例 """ self.__conf = conf self.__request = WechatRequest(conf=self.__conf)
def check_signature(self, signature, timestamp, nonce): """ 验证微信消息真实性 :param signature: 微信加密签名 :param timestamp: 时间戳 :param nonce: 随机数 :return: 通过验证返回 True, 未通过验证返回 False """ if not signature or not timestamp or not nonce: return False tmp_list = [self.conf.token, timestamp, nonce] tmp_list.sort() tmp_str = ''.join(tmp_list) if signature != hashlib.sha1(tmp_str.encode('utf-8')).hexdigest(): return False return True
def generate_jsapi_signature(self, timestamp, noncestr, url, jsapi_ticket=None): """ 使用 jsapi_ticket 对 url 进行签名 :param timestamp: 时间戳 :param noncestr: 随机数 :param url: 要签名的 url,不包含 # 及其后面部分 :param jsapi_ticket: (可选参数) jsapi_ticket 值 (如不提供将自动通过 appid 和 appsecret 获取) :return: 返回sha1签名的hexdigest值 """ if not jsapi_ticket: jsapi_ticket = self.conf.jsapi_ticket data = { 'jsapi_ticket': jsapi_ticket, 'noncestr': noncestr, 'timestamp': timestamp, 'url': url, } keys = list(data.keys()) keys.sort() data_str = '&'.join(['%s=%s' % (key, data[key]) for key in keys]) signature = hashlib.sha1(data_str.encode('utf-8')).hexdigest() return signature
def parse_data(self, data, msg_signature=None, timestamp=None, nonce=None): """ 解析微信服务器发送过来的数据并保存类中 :param data: HTTP Request 的 Body 数据 :param msg_signature: EncodingAESKey 的 msg_signature :param timestamp: EncodingAESKey 用时间戳 :param nonce: EncodingAESKey 用随机数 :raises ParseError: 解析微信服务器数据错误, 数据不合法 """ result = {} if isinstance(data, six.text_type): # unicode to str(PY2), str to bytes(PY3) data = data.encode('utf-8') if self.conf.encrypt_mode == 'safe': if not (msg_signature and timestamp and nonce): raise ParseError('must provide msg_signature/timestamp/nonce in safe encrypt mode') data = self.conf.crypto.decrypt_message( msg=data, msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, ) try: xml = XMLStore(xmlstring=data) except Exception: raise ParseError() result = xml.xml2dict result['raw'] = data result['type'] = result.pop('MsgType').lower() message_type = MESSAGE_TYPES.get(result['type'], UnknownMessage) self.__message = message_type(result) self.__is_parse = True
def response_text(self, content, escape=False): """ 将文字信息 content 组装为符合微信服务器要求的响应数据 :param content: 回复文字 :param escape: 是否转义该文本内容 (默认不转义) :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() content = self._transcoding(content) if escape: if six.PY2: content = cgi.escape(content) else: import html content = html.escape(content) response = TextReply(message=self.__message, content=content).render() return self._encrypt_response(response)
def response_image(self, media_id): """ 将 media_id 所代表的图片组装为符合微信服务器要求的响应数据 :param media_id: 图片的 MediaID :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() response = ImageReply(message=self.__message, media_id=media_id).render() return self._encrypt_response(response)
def response_voice(self, media_id): """ 将 media_id 所代表的语音组装为符合微信服务器要求的响应数据 :param media_id: 语音的 MediaID :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() response = VoiceReply(message=self.__message, media_id=media_id).render() return self._encrypt_response(response)
def response_video(self, media_id, title=None, description=None): """ 将 media_id 所代表的视频组装为符合微信服务器要求的响应数据 :param media_id: 视频的 MediaID :param title: 视频消息的标题 :param description: 视频消息的描述 :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() title = self._transcoding(title) description = self._transcoding(description) response = VideoReply(message=self.__message, media_id=media_id, title=title, description=description).render() return self._encrypt_response(response)
def response_music(self, music_url, title=None, description=None, hq_music_url=None, thumb_media_id=None): """ 将音乐信息组装为符合微信服务器要求的响应数据 :param music_url: 音乐链接 :param title: 音乐标题 :param description: 音乐描述 :param hq_music_url: 高质量音乐链接, WIFI环境优先使用该链接播放音乐 :param thumb_media_id: 缩略图的 MediaID :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() music_url = self._transcoding(music_url) title = self._transcoding(title) description = self._transcoding(description) hq_music_url = self._transcoding(hq_music_url) response = MusicReply(message=self.__message, title=title, description=description, music_url=music_url, hq_music_url=hq_music_url, thumb_media_id=thumb_media_id).render() return self._encrypt_response(response)
def response_news(self, articles): """ 将新闻信息组装为符合微信服务器要求的响应数据 :param articles: list 对象, 每个元素为一个 dict 对象, key 包含 `title`, `description`, `picurl`, `url` :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() for article in articles: if article.get('title'): article['title'] = self._transcoding(article['title']) if article.get('description'): article['description'] = self._transcoding(article['description']) if article.get('picurl'): article['picurl'] = self._transcoding(article['picurl']) if article.get('url'): article['url'] = self._transcoding(article['url']) news = ArticleReply(message=self.__message) for article in articles: article = Article(**article) news.add_article(article) response = news.render() return self._encrypt_response(response)
def group_transfer_message(self): """ 将 message 群发到多客服系统 :return: 符合微信服务器要求的 XML 响应数据 """ self._check_parse() response = GroupTransferReply(message=self.__message).render() return self._encrypt_response(response)
def create_menu(self, menu_data): """ 创建自定义菜单 :: # -*- coding: utf-8 -*- wechat = WechatBasic(appid='appid', appsecret='appsecret') wechat.create_menu({ 'button':[ { 'type': 'click', 'name': '今日歌曲', 'key': 'V1001_TODAY_MUSIC' }, { 'type': 'click', 'name': '歌手简介', 'key': 'V1001_TODAY_SINGER' }, { 'name': '菜单', 'sub_button': [ { 'type': 'view', 'name': '搜索', 'url': 'http://www.soso.com/' }, { 'type': 'view', 'name': '视频', 'url': 'http://v.qq.com/' }, { 'type': 'click', 'name': '赞一下我们', 'key': 'V1001_GOOD' } ] } ]}) 详情请参考 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html :param menu_data: Python 字典 :return: 返回的 JSON 数据包 """ menu_data = self._transcoding_dict(menu_data) return self.request.post( url='https://api.weixin.qq.com/cgi-bin/menu/create', data=menu_data )
def upload_media(self, media_type, media_file, extension=''): """ 上传多媒体文件 详情请参考 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb) :param media_file: 要上传的文件,一个 File object 或 StringIO object :param extension: 如果 media_file 传入的为 StringIO object,那么必须传入 extension 显示指明该媒体文件扩展名,如 ``mp3``, ``amr``;如果 media_file 传入的为 File object,那么该参数请留空 :return: 返回的 JSON 数据包 """ if six.PY2: return self._upload_media_py2(media_type, media_file, extension) else: return self._upload_media_py3(media_type, media_file, extension)
def download_media(self, media_id): """ 下载多媒体文件 详情请参考 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html :param media_id: 媒体文件 ID :return: requests 的 Response 实例 """ return self.request.get( 'https://api.weixin.qq.com/cgi-bin/media/get', params={ 'media_id': media_id, }, stream=True, )
def move_user(self, user_id, group_id): """ 移动用户分组 详情请参考 http://mp.weixin.qq.com/wiki/13/be5272dc4930300ba561d927aead2569.html :param user_id: 用户 ID 。 就是你收到的 WechatMessage 的 source :param group_id: 分组 ID :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/groups/members/update', data={ 'openid': user_id, 'to_groupid': group_id, } )
def get_user_info(self, user_id, lang='zh_CN'): """ 获取用户基本信息 详情请参考 http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 """ return self.request.get( url='https://api.weixin.qq.com/cgi-bin/user/info', params={ 'openid': user_id, 'lang': lang, } )
def get_followers(self, first_user_id=None): """ 获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 """ params = dict() if first_user_id: params['next_openid'] = first_user_id return self.request.get('https://api.weixin.qq.com/cgi-bin/user/get', params=params)
def send_text_message(self, user_id, content): """ 发送文本消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param content: 消息正文 :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'text', 'text': { 'content': content, }, } )
def send_image_message(self, user_id, media_id): """ 发送图片消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。 :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'image', 'image': { 'media_id': media_id, }, } )
def send_voice_message(self, user_id, media_id): """ 发送语音消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。 :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'voice', 'voice': { 'media_id': media_id, }, } )
def send_video_message(self, user_id, media_id, title=None, description=None): """ 发送视频消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param media_id: 发送的视频的媒体ID。 可以通过 :func:`upload_media` 上传。 :param title: 视频消息的标题 :param description: 视频消息的描述 :return: 返回的 JSON 数据包 """ video_data = { 'media_id': media_id, } if title: video_data['title'] = title if description: video_data['description'] = description return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'video', 'video': video_data, } )
def send_article_message(self, user_id, articles=None, media_id=None): """ 发送图文消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source :param articles: list 对象, 每个元素为一个 dict 对象, key 包含 `title`, `description`, `picurl`, `url` :param media_id: 待发送的图文 Media ID :return: 返回的 JSON 数据包 """ # neither 'articles' nor 'media_id' is specified if articles is None and media_id is None: raise TypeError('must provide one parameter in "articles" and "media_id"') # articles specified if articles: articles_data = [] for article in articles: article = Article(**article) articles_data.append({ 'title': article.title, 'description': article.description, 'url': article.url, 'picurl': article.picurl, }) return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'news', 'news': { 'articles': articles_data, }, } ) # media_id specified return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/custom/send', data={ 'touser': user_id, 'msgtype': 'mpnews', 'mpnews': { 'media_id': media_id, }, } )
def create_qrcode(self, data): """ 创建二维码 详情请参考 http://mp.weixin.qq.com/wiki/18/28fc21e7ed87bec960651f0ce873ef8a.html :param data: 你要发送的参数 dict :return: 返回的 JSON 数据包 """ data = self._transcoding_dict(data) return self.request.post( url='https://api.weixin.qq.com/cgi-bin/qrcode/create', data=data )
def set_template_industry(self, industry_id1, industry_id2): """ 设置所属行业 详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html :param industry_id1: 主营行业代码 :param industry_id2: 副营行业代码 :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/template/api_set_industry', data={ 'industry_id1': str(industry_id1), 'industry_id2': str(industry_id2), } )
def get_template_id(self, template_id_short): """ 获得模板ID 详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html :param template_id_short: 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式 :return: 返回的 JSON 数据包 """ return self.request.post( url='https://api.weixin.qq.com/cgi-bin/template/api_add_template', data={ 'template_id_short': str(template_id_short), } )
def send_template_message(self, user_id, template_id, data, url='', topcolor='#FF0000'): """ 发送模版消息 详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html :param user_id: 用户 ID, 就是你收到的 WechatMessage 的 source (OpenID) :param template_id: 模板ID :param data: 模板消息数据 (dict形式),示例如下: { "first": { "value": "恭喜你购买成功!", "color": "#173177" }, "keynote1":{ "value": "巧克力", "color": "#173177" }, "keynote2": { "value": "39.8元", "color": "#173177" }, "keynote3": { "value": "2014年9月16日", "color": "#173177" }, "remark":{ "value": "欢迎再次购买!", "color": "#173177" } } :param url: 跳转地址 (默认为空) :param topcolor: 顶部颜色RGB值 (默认 '#FF0000' ) :return: 返回的 JSON 数据包 """ unicode_data = {} if data: unicode_data = self._transcoding_dict(data) return self.request.post( url='https://api.weixin.qq.com/cgi-bin/message/template/send', data={ 'touser': user_id, "template_id": template_id, "url": url, "topcolor": topcolor, "data": unicode_data } )
def _check_official_error(self, json_data): """ 检测微信公众平台返回值中是否包含错误的返回码 :raises OfficialAPIError: 如果返回码提示有错误,抛出异常;否则返回 True """ if "errcode" in json_data and json_data["errcode"] != 0: raise OfficialAPIError(errcode=json_data.get('errcode'), errmsg=json_data.get('errmsg', ''))
def request(self, method, url, access_token=None, **kwargs): """ 向微信服务器发送请求 :param method: 请求方法 :param url: 请求地址 :param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值 :param kwargs: 附加数据 :return: 微信服务器响应的 JSON 数据 """ access_token = self.__conf.access_token if self.__conf is not None else access_token if "params" not in kwargs: kwargs["params"] = { "access_token": access_token } else: kwargs["params"]["access_token"] = access_token if isinstance(kwargs.get("data", ""), dict): body = json.dumps(kwargs["data"], ensure_ascii=False) if isinstance(body, six.text_type): body = body.encode('utf8') kwargs["data"] = body r = requests.request( method=method, url=url, **kwargs ) r.raise_for_status() try: response_json = r.json() except ValueError: # 非 JSON 数据 return r headimgurl = response_json.get('headimgurl') if headimgurl: response_json['headimgurl'] = headimgurl.replace('\\', '') self._check_official_error(response_json) return response_json
def post(self, url, access_token=None, **kwargs): """ 使用 POST 方法向微信服务器发出请求 :param url: 请求地址 :param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值 :param kwargs: 附加数据 :return: 微信服务器响应的 JSON 数据 """ return self.request( method="post", url=url, access_token=access_token, **kwargs )
def xml2dict(self): """ 将 XML 转换为 dict """ self._remove_whitespace_nodes(self._doc.childNodes[0]) return self._element2dict(self._doc.childNodes[0])
def _element2dict(self, parent): """ 将单个节点转换为 dict """ d = {} for node in parent.childNodes: if not isinstance(node, minidom.Element): continue if not node.hasChildNodes(): continue if node.childNodes[0].nodeType == minidom.Node.ELEMENT_NODE: try: d[node.tagName] except KeyError: d[node.tagName] = [] d[node.tagName].append(self._element2dict(node)) elif len(node.childNodes) == 1 and node.childNodes[0].nodeType in [minidom.Node.CDATA_SECTION_NODE, minidom.Node.TEXT_NODE]: d[node.tagName] = node.childNodes[0].data return d
def _remove_whitespace_nodes(self, node, unlink=True): """ 删除空白无用节点 """ remove_list = [] for child in node.childNodes: if child.nodeType == Node.TEXT_NODE and not child.data.strip(): remove_list.append(child) elif child.hasChildNodes(): self._remove_whitespace_nodes(child, unlink) for node in remove_list: node.parentNode.removeChild(node) if unlink: node.unlink()
def to_binary(value, encoding='utf-8'): """将 values 转为 bytes,默认编码 utf-8 :param value: 待转换的值 :param encoding: 编码 """ if not value: return b'' if isinstance(value, six.binary_type): return value if isinstance(value, six.text_type): return value.encode(encoding) if six.PY3: return six.binary_type(str(value), encoding) # For Python 3 return six.binary_type(value)
def _transcoding(cls, data): """编码转换 :param data: 需要转换的数据 :return: 转换好的数据 """ if not data: return data result = None if isinstance(data, str) and hasattr(data, 'decode'): result = data.decode('utf-8') else: result = data return result
def _transcoding_list(cls, data): """编码转换 for list :param data: 需要转换的 list 数据 :return: 转换好的 list """ if not isinstance(data, list): raise ValueError('Parameter data must be list object.') result = [] for item in data: if isinstance(item, dict): result.append(cls._transcoding_dict(item)) elif isinstance(item, list): result.append(cls._transcoding_list(item)) else: result.append(item) return result
def _transcoding_dict(cls, data): """ 编码转换 for dict :param data: 需要转换的 dict 数据 :return: 转换好的 dict """ if not isinstance(data, dict): raise ValueError('Parameter data must be dict object.') result = {} for k, v in data.items(): k = cls._transcoding(k) if isinstance(v, dict): v = cls._transcoding_dict(v) elif isinstance(v, list): v = cls._transcoding_list(v) else: v = cls._transcoding(v) result.update({k: v}) return result
def encode(cls, text): """ 对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串 """ text_length = len(text) # 计算需要填充的位数 amount_to_pad = cls.block_size - (text_length % cls.block_size) if amount_to_pad == 0: amount_to_pad = cls.block_size # 获得补位所用的字符 pad = to_binary(chr(amount_to_pad)) return text + pad * amount_to_pad
def decode(cls, decrypted): """ 删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文 """ pad = ord(decrypted[-1]) if pad < 1 or pad > 32: pad = 0 return decrypted[:-pad]
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception as e: raise DecryptAESError(e) try: if six.PY2: pad = ord(plain_text[-1]) else: pad = plain_text[-1] # 去掉补位字符串 # pkcs7 = PKCS7Encoder() # plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0]) xml_content = content[4: xml_len + 4] from_appid = content[xml_len + 4:] except Exception as e: raise IllegalBuffer(e) if from_appid != appid: raise ValidateAppIDError() return xml_content
def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.ascii_letters + string.digits return "".join(random.sample(rule, 16))
def _check_signature(self, msg_signature, timestamp, nonce, echostr): """验证签名有效性 :param msg_signature: 签名串,对应URL参数的msg_signature :param timestamp: 时间戳,对应URL参数的timestamp :param nonce: 随机串,对应URL参数的nonce :param echostr: 随机串,对应URL参数的echostr :return: 解密之后的echostr :raise ValidateSignatureError: 签名无效异常 """ signature = get_sha1_signature(self.__token, timestamp, nonce, echostr) if not signature == msg_signature: raise ValidateSignatureError() try: return self.__pc.decrypt(echostr, self.__id) except DecryptAESError as e: raise ValidateSignatureError(e)
def _encrypt_message(self, msg, nonce, timestamp=None): """将公众号回复用户的消息加密打包 :param msg: 待回复用户的消息,xml格式的字符串 :param nonce: 随机串,可以自己生成,也可以用URL参数的nonce :param timestamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间 :return: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 """ xml = """<xml> <Encrypt><![CDATA[{encrypt}]]></Encrypt> <MsgSignature><![CDATA[{signature}]]></MsgSignature> <TimeStamp>{timestamp}</TimeStamp> <Nonce><![CDATA[{nonce}]]></Nonce> </xml>""" nonce = to_binary(nonce) timestamp = to_binary(timestamp) or to_binary(int(time.time())) encrypt = self.__pc.encrypt(to_text(msg), self.__id) # 生成安全签名 signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt) return to_text(xml.format( encrypt=to_text(encrypt), signature=to_text(signature), timestamp=to_text(timestamp), nonce=to_text(nonce) ))
def _decrypt_message(self, msg, msg_signature, timestamp, nonce): """检验消息的真实性,并且获取解密后的明文 :param msg: 密文,对应POST请求的数据 :param msg_signature: 签名串,对应URL参数的msg_signature :param timestamp: 时间戳,对应URL参数的timestamp :param nonce: 随机串,对应URL参数的nonce :return: 解密后的原文 """ timestamp = to_binary(timestamp) nonce = to_binary(nonce) if isinstance(msg, six.string_types): try: msg = xmltodict.parse(to_text(msg))['xml'] except Exception as e: raise ParseError(e) encrypt = msg['Encrypt'] signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt) if signature != msg_signature: raise ValidateSignatureError() return self.__pc.decrypt(encrypt, self.__id)
def Lastovka_Shaw(T, similarity_variable, cyclic_aliphatic=False): r'''Calculate ideal-gas constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. .. math:: C_p^0 = \left(A_2 + \frac{A_1 - A_2}{1 + \exp(\frac{\alpha-A_3}{A_4})}\right) + (B_{11} + B_{12}\alpha)\left(-\frac{(C_{11} + C_{12}\alpha)}{T}\right)^2 \frac{\exp(-(C_{11} + C_{12}\alpha)/T)}{[1-\exp(-(C_{11}+C_{12}\alpha)/T)]^2}\\ + (B_{21} + B_{22}\alpha)\left(-\frac{(C_{21} + C_{22}\alpha)}{T}\right)^2 \frac{\exp(-(C_{21} + C_{22}\alpha)/T)}{[1-\exp(-(C_{21}+C_{22}\alpha)/T)]^2} Parameters ---------- T : float Temperature of gas [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- Cpg : float Gas constant-pressure heat capacitiy, [J/kg/K] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! A1 = 0.58, A2 = 1.25, A3 = 0.17338003, A4 = 0.014, B11 = 0.73917383, B12 = 8.88308889, C11 = 1188.28051, C12 = 1813.04613, B21 = 0.0483019, B22 = 4.35656721, C21 = 2897.01927, C22 = 5987.80407. Examples -------- >>> Lastovka_Shaw(1000.0, 0.1333) 2467.113309084757 References ---------- .. [1] Lastovka, Vaclav, and John M. Shaw. "Predictive Correlations for Ideal Gas Heat Capacities of Pure Hydrocarbons and Petroleum Fractions." Fluid Phase Equilibria 356 (October 25, 2013): 338-370. doi:10.1016/j.fluid.2013.07.023. ''' a = similarity_variable if cyclic_aliphatic: A1 = -0.1793547 A2 = 3.86944439 first = A1 + A2*a else: A1 = 0.58 A2 = 1.25 A3 = 0.17338003 # 803 instead of 8003 in another paper A4 = 0.014 first = A2 + (A1-A2)/(1. + exp((a - A3)/A4)) # Personal communication confirms the change B11 = 0.73917383 B12 = 8.88308889 C11 = 1188.28051 C12 = 1813.04613 B21 = 0.0483019 B22 = 4.35656721 C21 = 2897.01927 C22 = 5987.80407 Cp = first + (B11 + B12*a)*((C11+C12*a)/T)**2*exp(-(C11 + C12*a)/T)/(1.-exp(-(C11+C12*a)/T))**2 Cp += (B21 + B22*a)*((C21+C22*a)/T)**2*exp(-(C21 + C22*a)/T)/(1.-exp(-(C21+C22*a)/T))**2 return Cp*1000.
def Lastovka_Shaw_integral_over_T(T, similarity_variable, cyclic_aliphatic=False): r'''Calculate the integral over temperature of ideal-gas constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Parameters ---------- T : float Temperature of gas [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- S : float Difference in entropy from 0 K, [J/kg/K] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! Integral was computed with SymPy. See Also -------- Lastovka_Shaw Lastovka_Shaw_integral Examples -------- >>> Lastovka_Shaw_integral_over_T(300.0, 0.1333) 3609.791928945323 References ---------- .. [1] Lastovka, Vaclav, and John M. Shaw. "Predictive Correlations for Ideal Gas Heat Capacities of Pure Hydrocarbons and Petroleum Fractions." Fluid Phase Equilibria 356 (October 25, 2013): 338-370. doi:10.1016/j.fluid.2013.07.023. ''' from cmath import log, exp a = similarity_variable if cyclic_aliphatic: A1 = -0.1793547 A2 = 3.86944439 first = A1 + A2*a else: A1 = 0.58 A2 = 1.25 A3 = 0.17338003 # 803 instead of 8003 in another paper A4 = 0.014 first = A2 + (A1-A2)/(1. + exp((a - A3)/A4)) a2 = a*a B11 = 0.73917383 B12 = 8.88308889 C11 = 1188.28051 C12 = 1813.04613 B21 = 0.0483019 B22 = 4.35656721 C21 = 2897.01927 C22 = 5987.80407 S = (first*log(T) + (-B11 - B12*a)*log(exp((-C11 - C12*a)/T) - 1.) + (-B11*C11 - B11*C12*a - B12*C11*a - B12*C12*a2)/(T*exp((-C11 - C12*a)/T) - T) - (B11*C11 + B11*C12*a + B12*C11*a + B12*C12*a2)/T) S += ((-B21 - B22*a)*log(exp((-C21 - C22*a)/T) - 1.) + (-B21*C21 - B21*C22*a - B22*C21*a - B22*C22*a2)/(T*exp((-C21 - C22*a)/T) - T) - (B21*C21 + B21*C22*a + B22*C21*a + B22*C22*a**2)/T) # There is a non-real component, but it is only a function of similariy # variable and so will always cancel out. return S.real*1000.
def TRCCp(T, a0, a1, a2, a3, a4, a5, a6, a7): r'''Calculates ideal gas heat capacity using the model developed in [1]_. The ideal gas heat capacity is given by: .. math:: C_p = R\left(a_0 + (a_1/T^2) \exp(-a_2/T) + a_3 y^2 + (a_4 - a_5/(T-a_7)^2 )y^j \right) y = \frac{T-a_7}{T+a_6} \text{ for } T > a_7 \text{ otherwise } 0 Parameters ---------- T : float Temperature [K] a1-a7 : float Coefficients Returns ------- Cp : float Ideal gas heat capacity , [J/mol/K] Notes ----- j is set to 8. Analytical integrals are available for this expression. Examples -------- >>> TRCCp(300, 4.0, 7.65E5, 720., 3.565, -0.052, -1.55E6, 52., 201.) 42.06525682312236 References ---------- .. [1] Kabo, G. J., and G. N. Roganov. Thermodynamics of Organic Compounds in the Gas State, Volume II: V. 2. College Station, Tex: CRC Press, 1994. ''' if T <= a7: y = 0. else: y = (T - a7)/(T + a6) Cp = R*(a0 + (a1/T**2)*exp(-a2/T) + a3*y**2 + (a4 - a5/(T-a7)**2 )*y**8.) return Cp
def TRCCp_integral(T, a0, a1, a2, a3, a4, a5, a6, a7, I=0): r'''Integrates ideal gas heat capacity using the model developed in [1]_. Best used as a delta only. The difference in enthalpy with respect to 0 K is given by: .. math:: \frac{H(T) - H^{ref}}{RT} = a_0 + a_1x(a_2)/(a_2T) + I/T + h(T)/T h(T) = (a_5 + a_7)\left[(2a_3 + 8a_4)\ln(1-y)+ \left\{a_3\left(1 + \frac{1}{1-y}\right) + a_4\left(7 + \frac{1}{1-y}\right)\right\}y + a_4\left\{3y^2 + (5/3)y^3 + y^4 + (3/5)y^5 + (1/3)y^6\right\} + (1/7)\left\{a_4 - \frac{a_5}{(a_6+a_7)^2}\right\}y^7\right] h(T) = 0 \text{ for } T \le a_7 y = \frac{T-a_7}{T+a_6} \text{ for } T > a_7 \text{ otherwise } 0 Parameters ---------- T : float Temperature [K] a1-a7 : float Coefficients I : float, optional Integral offset Returns ------- H-H(0) : float Difference in enthalpy from 0 K , [J/mol] Notes ----- Analytical integral as provided in [1]_ and verified with numerical integration. Examples -------- >>> TRCCp_integral(298.15, 4.0, 7.65E5, 720., 3.565, -0.052, -1.55E6, 52., ... 201., 1.2) 10802.532600592816 References ---------- .. [1] Kabo, G. J., and G. N. Roganov. Thermodynamics of Organic Compounds in the Gas State, Volume II: V. 2. College Station, Tex: CRC Press, 1994. ''' if T <= a7: y = 0. else: y = (T - a7)/(T + a6) y2 = y*y y4 = y2*y2 if T <= a7: h = 0.0 else: first = a6 + a7 second = (2.*a3 + 8.*a4)*log(1. - y) third = (a3*(1. + 1./(1. - y)) + a4*(7. + 1./(1. - y)))*y fourth = a4*(3.*y2 + 5./3.*y*y2 + y4 + 0.6*y4*y + 1/3.*y4*y2) fifth = 1/7.*(a4 - a5/((a6 + a7)**2))*y4*y2*y h = first*(second + third + fourth + fifth) return (a0 + a1*exp(-a2/T)/(a2*T) + I/T + h/T)*R*T
def TRCCp_integral_over_T(T, a0, a1, a2, a3, a4, a5, a6, a7, J=0): r'''Integrates ideal gas heat capacity over T using the model developed in [1]_. Best used as a delta only. The difference in ideal-gas entropy with respect to 0 K is given by: .. math:: \frac{S^\circ}{R} = J + a_0\ln T + \frac{a_1}{a_2^2}\left(1 + \frac{a_2}{T}\right)x(a_2) + s(T) s(T) = \left[\left\{a_3 + \left(\frac{a_4 a_7^2 - a_5}{a_6^2}\right) \left(\frac{a_7}{a_6}\right)^4\right\}\left(\frac{a_7}{a_6}\right)^2 \ln z + (a_3 + a_4)\ln\left(\frac{T+a_6}{a_6+a_7}\right) +\sum_{i=1}^7 \left\{\left(\frac{a_4 a_7^2 - a_5}{a_6^2}\right)\left( \frac{-a_7}{a_6}\right)^{6-i} - a_4\right\}\frac{y^i}{i} - \left\{\frac{a_3}{a_6}(a_6 + a_7) + \frac{a_5 y^6}{7a_7(a_6+a_7)} \right\}y\right] s(T) = 0 \text{ for } T \le a_7 z = \frac{T}{T+a_6} \cdot \frac{a_7 + a_6}{a_7} y = \frac{T-a_7}{T+a_6} \text{ for } T > a_7 \text{ otherwise } 0 Parameters ---------- T : float Temperature [K] a1-a7 : float Coefficients J : float, optional Integral offset Returns ------- S-S(0) : float Difference in entropy from 0 K , [J/mol/K] Notes ----- Analytical integral as provided in [1]_ and verified with numerical integration. Examples -------- >>> TRCCp_integral_over_T(300, 4.0, 124000, 245, 50.539, -49.469, ... 220440000, 560, 78) 213.80148972435018 References ---------- .. [1] Kabo, G. J., and G. N. Roganov. Thermodynamics of Organic Compounds in the Gas State, Volume II: V. 2. College Station, Tex: CRC Press, 1994. ''' # Possible optimizations: pre-cache as much as possible. # If this were replaced by a cache, much of this would not need to be computed. if T <= a7: y = 0. else: y = (T - a7)/(T + a6) z = T/(T + a6)*(a7 + a6)/a7 if T <= a7: s = 0. else: a72 = a7*a7 a62 = a6*a6 a7_a6 = a7/a6 # a7/a6 a7_a6_2 = a7_a6*a7_a6 a7_a6_4 = a7_a6_2*a7_a6_2 x1 = (a4*a72 - a5)/a62 # part of third, sum first = (a3 + ((a4*a72 - a5)/a62)*a7_a6_4)*a7_a6_2*log(z) second = (a3 + a4)*log((T + a6)/(a6 + a7)) fourth = -(a3/a6*(a6 + a7) + a5*y**6/(7.*a7*(a6 + a7)))*y third = sum([(x1*(-a7_a6)**(6-i) - a4)*y**i/i for i in range(1, 8)]) s = first + second + third + fourth return R*(J + a0*log(T) + a1/(a2*a2)*(1. + a2/T)*exp(-a2/T) + s)
def Rowlinson_Poling(T, Tc, omega, Cpgm): r'''Calculate liquid constant-pressure heat capacitiy with the [1]_ CSP method. This equation is not terrible accurate. The heat capacity of a liquid is given by: .. math:: \frac{Cp^{L} - Cp^{g}}{R} = 1.586 + \frac{0.49}{1-T_r} + \omega\left[ 4.2775 + \frac{6.3(1-T_r)^{1/3}}{T_r} + \frac{0.4355}{1-T_r}\right] Parameters ---------- T : float Temperature of fluid [K] Tc : float Critical temperature of fluid [K] omega : float Acentric factor for fluid, [-] Cpgm : float Constant-pressure gas heat capacity, [J/mol/K] Returns ------- Cplm : float Liquid constant-pressure heat capacitiy, [J/mol/K] Notes ----- Poling compared 212 substances, and found error at 298K larger than 10% for 18 of them, mostly associating. Of the other 194 compounds, AARD is 2.5%. Examples -------- >>> Rowlinson_Poling(350.0, 435.5, 0.203, 91.21) 143.80194441498296 References ---------- .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' Tr = T/Tc Cplm = Cpgm+ R*(1.586 + 0.49/(1.-Tr) + omega*(4.2775 + 6.3*(1-Tr)**(1/3.)/Tr + 0.4355/(1.-Tr))) return Cplm
def Rowlinson_Bondi(T, Tc, omega, Cpgm): r'''Calculate liquid constant-pressure heat capacitiy with the CSP method shown in [1]_. The heat capacity of a liquid is given by: .. math:: \frac{Cp^L - Cp^{ig}}{R} = 1.45 + 0.45(1-T_r)^{-1} + 0.25\omega [17.11 + 25.2(1-T_r)^{1/3}T_r^{-1} + 1.742(1-T_r)^{-1}] Parameters ---------- T : float Temperature of fluid [K] Tc : float Critical temperature of fluid [K] omega : float Acentric factor for fluid, [-] Cpgm : float Constant-pressure gas heat capacity, [J/mol/K] Returns ------- Cplm : float Liquid constant-pressure heat capacitiy, [J/mol/K] Notes ----- Less accurate than `Rowlinson_Poling`. Examples -------- >>> Rowlinson_Bondi(T=373.28, Tc=535.55, omega=0.323, Cpgm=119.342) 175.39760730048116 References ---------- .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. .. [2] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition. Berlin; New York:: Springer, 2010. .. [3] J.S. Rowlinson, Liquids and Liquid Mixtures, 2nd Ed., Butterworth, London (1969). ''' Tr = T/Tc Cplm = Cpgm + R*(1.45 + 0.45/(1.-Tr) + 0.25*omega*(17.11 + 25.2*(1-Tr)**(1/3.)/Tr + 1.742/(1.-Tr))) return Cplm
def Dadgostar_Shaw(T, similarity_variable): r'''Calculate liquid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. .. math:: C_{p} = 24.5(a_{11}\alpha + a_{12}\alpha^2)+ (a_{21}\alpha + a_{22}\alpha^2)T +(a_{31}\alpha + a_{32}\alpha^2)T^2 Parameters ---------- T : float Temperature of liquid [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- Cpl : float Liquid constant-pressure heat capacitiy, [J/kg/K] Notes ----- Many restrictions on its use. Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! a11 = -0.3416; a12 = 2.2671; a21 = 0.1064; a22 = -0.3874l; a31 = -9.8231E-05; a32 = 4.182E-04 Examples -------- >>> Dadgostar_Shaw(355.6, 0.139) 1802.5291501191516 References ---------- .. [1] Dadgostar, Nafiseh, and John M. Shaw. "A Predictive Correlation for the Constant-Pressure Specific Heat Capacity of Pure and Ill-Defined Liquid Hydrocarbons." Fluid Phase Equilibria 313 (January 15, 2012): 211-226. doi:10.1016/j.fluid.2011.09.015. ''' a = similarity_variable a11 = -0.3416 a12 = 2.2671 a21 = 0.1064 a22 = -0.3874 a31 = -9.8231E-05 a32 = 4.182E-04 # Didn't seem to improve the comparison; sum of errors on some # points included went from 65.5 to 286. # Author probably used more precision in their calculation. # theta = 151.8675 # constant = 3*R*(theta/T)**2*exp(theta/T)/(exp(theta/T)-1)**2 constant = 24.5 Cp = (constant*(a11*a + a12*a**2) + (a21*a + a22*a**2)*T + (a31*a + a32*a**2)*T**2) Cp = Cp*1000 # J/g/K to J/kg/K return Cp
def Dadgostar_Shaw_integral(T, similarity_variable): r'''Calculate the integral of liquid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Parameters ---------- T : float Temperature of gas [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- H : float Difference in enthalpy from 0 K, [J/kg] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! Integral was computed with SymPy. See Also -------- Dadgostar_Shaw Dadgostar_Shaw_integral_over_T Examples -------- >>> Dadgostar_Shaw_integral(300.0, 0.1333) 238908.15142664989 References ---------- .. [1] Dadgostar, Nafiseh, and John M. Shaw. "A Predictive Correlation for the Constant-Pressure Specific Heat Capacity of Pure and Ill-Defined Liquid Hydrocarbons." Fluid Phase Equilibria 313 (January 15, 2012): 211-226. doi:10.1016/j.fluid.2011.09.015. ''' a = similarity_variable a2 = a*a T2 = T*T a11 = -0.3416 a12 = 2.2671 a21 = 0.1064 a22 = -0.3874 a31 = -9.8231E-05 a32 = 4.182E-04 constant = 24.5 H = T2*T/3.*(a2*a32 + a*a31) + T2*0.5*(a2*a22 + a*a21) + T*constant*(a2*a12 + a*a11) return H*1000.
def Dadgostar_Shaw_integral_over_T(T, similarity_variable): r'''Calculate the integral of liquid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Parameters ---------- T : float Temperature of gas [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- S : float Difference in entropy from 0 K, [J/kg/K] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! Integral was computed with SymPy. See Also -------- Dadgostar_Shaw Dadgostar_Shaw_integral Examples -------- >>> Dadgostar_Shaw_integral_over_T(300.0, 0.1333) 1201.1409113147927 References ---------- .. [1] Dadgostar, Nafiseh, and John M. Shaw. "A Predictive Correlation for the Constant-Pressure Specific Heat Capacity of Pure and Ill-Defined Liquid Hydrocarbons." Fluid Phase Equilibria 313 (January 15, 2012): 211-226. doi:10.1016/j.fluid.2011.09.015. ''' a = similarity_variable a2 = a*a a11 = -0.3416 a12 = 2.2671 a21 = 0.1064 a22 = -0.3874 a31 = -9.8231E-05 a32 = 4.182E-04 constant = 24.5 S = T*T*0.5*(a2*a32 + a*a31) + T*(a2*a22 + a*a21) + a*constant*(a*a12 + a11)*log(T) return S*1000.
def Zabransky_quasi_polynomial(T, Tc, a1, a2, a3, a4, a5, a6): r'''Calculates liquid heat capacity using the model developed in [1]_. .. math:: \frac{C}{R}=A_1\ln(1-T_r) + \frac{A_2}{1-T_r} + \sum_{j=0}^m A_{j+3} T_r^j Parameters ---------- T : float Temperature [K] Tc : float Critical temperature of fluid, [K] a1-a6 : float Coefficients Returns ------- Cp : float Liquid heat capacity, [J/mol/K] Notes ----- Used only for isobaric heat capacities, not saturation heat capacities. Designed for reasonable extrapolation behavior caused by using the reduced critical temperature. Used by the authors of [1]_ when critical temperature was available for the fluid. Analytical integrals are available for this expression. Examples -------- >>> Zabransky_quasi_polynomial(330, 591.79, -3.12743, 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989) 165.4728226923247 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' Tr = T/Tc return R*(a1*log(1-Tr) + a2/(1-Tr) + a3 + a4*Tr + a5*Tr**2 + a6*Tr**3)
def Zabransky_quasi_polynomial_integral(T, Tc, a1, a2, a3, a4, a5, a6): r'''Calculates the integral of liquid heat capacity using the quasi-polynomial model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a6 : float Coefficients Returns ------- H : float Difference in enthalpy from 0 K, [J/mol] Notes ----- The analytical integral was derived with SymPy; it is a simple polynomial plus some logarithms. Examples -------- >>> H2 = Zabransky_quasi_polynomial_integral(300, 591.79, -3.12743, ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989) >>> H1 = Zabransky_quasi_polynomial_integral(200, 591.79, -3.12743, ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989) >>> H2 - H1 14662.026406892925 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' Tc2 = Tc*Tc Tc3 = Tc2*Tc term = T - Tc return R*(T*(T*(T*(T*a6/(4.*Tc3) + a5/(3.*Tc2)) + a4/(2.*Tc)) - a1 + a3) + T*a1*log(1. - T/Tc) - 0.5*Tc*(a1 + a2)*log(term*term))
def Zabransky_quasi_polynomial_integral_over_T(T, Tc, a1, a2, a3, a4, a5, a6): r'''Calculates the integral of liquid heat capacity over T using the quasi-polynomial model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a6 : float Coefficients Returns ------- S : float Difference in entropy from 0 K, [J/mol/K] Notes ----- The analytical integral was derived with Sympy. It requires the Polylog(2,x) function, which is unimplemented in SciPy. A very accurate numerical approximation was implemented as :obj:`thermo.utils.polylog2`. Relatively slow due to the use of that special function. Examples -------- >>> S2 = Zabransky_quasi_polynomial_integral_over_T(300, 591.79, -3.12743, ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989) >>> S1 = Zabransky_quasi_polynomial_integral_over_T(200, 591.79, -3.12743, ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989) >>> S2 - S1 59.16997291893654 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' term = T - Tc logT = log(T) Tc2 = Tc*Tc Tc3 = Tc2*Tc return R*(a3*logT -a1*polylog2(T/Tc) - a2*(-logT + 0.5*log(term*term)) + T*(T*(T*a6/(3.*Tc3) + a5/(2.*Tc2)) + a4/Tc))
def Zabransky_cubic(T, a1, a2, a3, a4): r'''Calculates liquid heat capacity using the model developed in [1]_. .. math:: \frac{C}{R}=\sum_{j=0}^3 A_{j+1} \left(\frac{T}{100}\right)^j Parameters ---------- T : float Temperature [K] a1-a4 : float Coefficients Returns ------- Cp : float Liquid heat capacity, [J/mol/K] Notes ----- Most often form used in [1]_. Analytical integrals are available for this expression. Examples -------- >>> Zabransky_cubic(298.15, 20.9634, -10.1344, 2.8253, -0.256738) 75.31462591538556 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' T = T/100. return R*(((a4*T + a3)*T + a2)*T + a1)
def Zabransky_cubic_integral(T, a1, a2, a3, a4): r'''Calculates the integral of liquid heat capacity using the model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a4 : float Coefficients Returns ------- H : float Difference in enthalpy from 0 K, [J/mol] Notes ----- The analytical integral was derived with Sympy; it is a simple polynomial. Examples -------- >>> Zabransky_cubic_integral(298.15, 20.9634, -10.1344, 2.8253, -0.256738) 31051.679845520586 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' T = T/100. return 100*R*T*(T*(T*(T*a4*0.25 + a3/3.) + a2*0.5) + a1)
def Zabransky_cubic_integral_over_T(T, a1, a2, a3, a4): r'''Calculates the integral of liquid heat capacity over T using the model developed in [1]_. Parameters ---------- T : float Temperature [K] a1-a4 : float Coefficients Returns ------- S : float Difference in entropy from 0 K, [J/mol/K] Notes ----- The analytical integral was derived with Sympy; it is a simple polynomial, plus a logarithm Examples -------- >>> Zabransky_cubic_integral_over_T(298.15, 20.9634, -10.1344, 2.8253, ... -0.256738) 24.73245695987246 References ---------- .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski. Heat Capacity of Liquids: Critical Review and Recommended Values. 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996. ''' T = T/100. return R*(T*(T*(T*a4/3 + a3/2) + a2) + a1*log(T))
def Lastovka_solid(T, similarity_variable): r'''Calculate solid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. .. math:: C_p = 3(A_1\alpha + A_2\alpha^2)R\left(\frac{\theta}{T}\right)^2 \frac{\exp(\theta/T)}{[\exp(\theta/T)-1]^2} + (C_1\alpha + C_2\alpha^2)T + (D_1\alpha + D_2\alpha^2)T^2 Parameters ---------- T : float Temperature of solid [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- Cps : float Solid constant-pressure heat capacitiy, [J/kg/K] Notes ----- Many restrictions on its use. Trained on data with MW from 12.24 g/mol to 402.4 g/mol, C mass fractions from 61.3% to 95.2%, H mass fractions from 3.73% to 15.2%, N mass fractions from 0 to 15.4%, O mass fractions from 0 to 18.8%, and S mass fractions from 0 to 29.6%. Recommended for organic compounds with low mass fractions of hetero-atoms and especially when molar mass exceeds 200 g/mol. This model does not show and effects of phase transition but should not be used passed the triple point. Original model is in terms of J/g/K. Note that the model s for predicting mass heat capacity, not molar heat capacity like most other methods! A1 = 0.013183; A2 = 0.249381; theta = 151.8675; C1 = 0.026526; C2 = -0.024942; D1 = 0.000025; D2 = -0.000123. Examples -------- >>> Lastovka_solid(300, 0.2139) 1682.063629222013 References ---------- .. [1] Laštovka, Václav, Michal Fulem, Mildred Becerra, and John M. Shaw. "A Similarity Variable for Estimating the Heat Capacity of Solid Organic Compounds: Part II. Application: Heat Capacity Calculation for Ill-Defined Organic Solids." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 134-41. doi:10.1016/j.fluid.2008.03.018. ''' A1 = 0.013183 A2 = 0.249381 theta = 151.8675 C1 = 0.026526 C2 = -0.024942 D1 = 0.000025 D2 = -0.000123 Cp = (3*(A1*similarity_variable + A2*similarity_variable**2)*R*(theta/T )**2*exp(theta/T)/(exp(theta/T)-1)**2 + (C1*similarity_variable + C2*similarity_variable**2)*T + (D1*similarity_variable + D2*similarity_variable**2)*T**2) Cp = Cp*1000 # J/g/K to J/kg/K return Cp
def Lastovka_solid_integral(T, similarity_variable): r'''Integrates solid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Uses a explicit form as derived with Sympy. Parameters ---------- T : float Temperature of solid [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- H : float Difference in enthalpy from 0 K, [J/kg] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! See Also -------- Lastovka_solid Examples -------- >>> Lastovka_solid_integral(300, 0.2139) 283246.1242170376 References ---------- .. [1] Laštovka, Václav, Michal Fulem, Mildred Becerra, and John M. Shaw. "A Similarity Variable for Estimating the Heat Capacity of Solid Organic Compounds: Part II. Application: Heat Capacity Calculation for Ill-Defined Organic Solids." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 134-41. doi:10.1016/j.fluid.2008.03.018. ''' A1 = 0.013183 A2 = 0.249381 theta = 151.8675 C1 = 0.026526 C2 = -0.024942 D1 = 0.000025 D2 = -0.000123 similarity_variable2 = similarity_variable*similarity_variable return (T*T*T*(1000.*D1*similarity_variable/3. + 1000.*D2*similarity_variable2/3.) + T*T*(500.*C1*similarity_variable + 500.*C2*similarity_variable2) + (3000.*A1*R*similarity_variable*theta + 3000.*A2*R*similarity_variable2*theta)/(exp(theta/T) - 1.))
def Lastovka_solid_integral_over_T(T, similarity_variable): r'''Integrates over T solid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Uses a explicit form as derived with Sympy. Parameters ---------- T : float Temperature of solid [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ------- S : float Difference in entropy from 0 K, [J/kg/K] Notes ----- Original model is in terms of J/g/K. Note that the model is for predicting mass heat capacity, not molar heat capacity like most other methods! See Also -------- Lastovka_solid Examples -------- >>> Lastovka_solid_integral_over_T(300, 0.2139) 1947.553552666818 References ---------- .. [1] Laštovka, Václav, Michal Fulem, Mildred Becerra, and John M. Shaw. "A Similarity Variable for Estimating the Heat Capacity of Solid Organic Compounds: Part II. Application: Heat Capacity Calculation for Ill-Defined Organic Solids." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 134-41. doi:10.1016/j.fluid.2008.03.018. ''' A1 = 0.013183 A2 = 0.249381 theta = 151.8675 C1 = 0.026526 C2 = -0.024942 D1 = 0.000025 D2 = -0.000123 sim2 = similarity_variable*similarity_variable exp_theta_T = exp(theta/T) return (-3000.*R*similarity_variable*(A1 + A2*similarity_variable)*log(exp_theta_T - 1.) + T**2*(500.*D1*similarity_variable + 500.*D2*sim2) + T*(1000.*C1*similarity_variable + 1000.*C2*sim2) + (3000.*A1*R*similarity_variable*theta + 3000.*A2*R*sim2*theta)/(T*exp_theta_T - T) + (3000.*A1*R*similarity_variable*theta + 3000.*A2*R*sim2*theta)/T)
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [] Tmins, Tmaxs = [], [] if self.CASRN in TRC_gas_data.index: methods.append(TRCIG) _, self.TRCIG_Tmin, self.TRCIG_Tmax, a0, a1, a2, a3, a4, a5, a6, a7, _, _, _ = _TRC_gas_data_values[TRC_gas_data.index.get_loc(self.CASRN)].tolist() self.TRCIG_coefs = [a0, a1, a2, a3, a4, a5, a6, a7] Tmins.append(self.TRCIG_Tmin); Tmaxs.append(self.TRCIG_Tmax) if self.CASRN in Poling_data.index and not np.isnan(Poling_data.at[self.CASRN, 'a0']): _, self.POLING_Tmin, self.POLING_Tmax, a0, a1, a2, a3, a4, Cpg, Cpl = _Poling_data_values[Poling_data.index.get_loc(self.CASRN)].tolist() methods.append(POLING) self.POLING_coefs = [a0, a1, a2, a3, a4] Tmins.append(self.POLING_Tmin); Tmaxs.append(self.POLING_Tmax) if self.CASRN in Poling_data.index and not np.isnan(Poling_data.at[self.CASRN, 'Cpg']): methods.append(POLING_CONST) self.POLING_T = 298.15 self.POLING_constant = float(Poling_data.at[self.CASRN, 'Cpg']) if self.CASRN in CRC_standard_data.index and not np.isnan(CRC_standard_data.at[self.CASRN, 'Cpg']): methods.append(CRCSTD) self.CRCSTD_T = 298.15 self.CRCSTD_constant = float(CRC_standard_data.at[self.CASRN, 'Cpg']) if self.CASRN in _VDISaturationDict: # NOTE: VDI data is for the saturation curve, i.e. at increasing # pressure; it is normally substantially higher than the ideal gas # value methods.append(VDI_TABULAR) Ts, props = VDI_tabular_data(self.CASRN, 'Cp (g)') self.VDI_Tmin = Ts[0] self.VDI_Tmax = Ts[-1] self.tabular_data[VDI_TABULAR] = (Ts, props) Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax) if has_CoolProp and self.CASRN in coolprop_dict: methods.append(COOLPROP) self.CP_f = coolprop_fluids[self.CASRN] Tmins.append(self.CP_f.Tt); Tmaxs.append(self.CP_f.Tc) if self.MW and self.similarity_variable: methods.append(LASTOVKA_SHAW) self.all_methods = set(methods) if Tmins and Tmaxs: self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)
def calculate(self, T, method): r'''Method to calculate surface tension of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate heat capacity, [K] method : str Method name to use Returns ------- Cp : float Calculated heat capacity, [J/mol/K] ''' if method == TRCIG: Cp = TRCCp(T, *self.TRCIG_coefs) elif method == COOLPROP: Cp = PropsSI('Cp0molar', 'T', T,'P', 101325.0, self.CASRN) elif method == POLING: Cp = R*(self.POLING_coefs[0] + self.POLING_coefs[1]*T + self.POLING_coefs[2]*T**2 + self.POLING_coefs[3]*T**3 + self.POLING_coefs[4]*T**4) elif method == POLING_CONST: Cp = self.POLING_constant elif method == CRCSTD: Cp = self.CRCSTD_constant elif method == LASTOVKA_SHAW: Cp = Lastovka_Shaw(T, self.similarity_variable) Cp = property_mass_to_molar(Cp, self.MW) elif method in self.tabular_data: Cp = self.interpolate(T, method) return Cp
def calculate_integral(self, T1, T2, method): r'''Method to calculate the integral of a property with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units*K`] ''' if method == TRCIG: H2 = TRCCp_integral(T2, *self.TRCIG_coefs) H1 = TRCCp_integral(T1, *self.TRCIG_coefs) return H2 - H1 elif method == POLING: A, B, C, D, E = self.POLING_coefs H2 = (((((0.2*E)*T2 + 0.25*D)*T2 + C/3.)*T2 + 0.5*B)*T2 + A)*T2 H1 = (((((0.2*E)*T1 + 0.25*D)*T1 + C/3.)*T1 + 0.5*B)*T1 + A)*T1 return R*(H2 - H1) elif method == POLING_CONST: return (T2 - T1)*self.POLING_constant elif method == CRCSTD: return (T2 - T1)*self.CRCSTD_constant elif method == LASTOVKA_SHAW: dH = (Lastovka_Shaw_integral(T2, self.similarity_variable) - Lastovka_Shaw_integral(T1, self.similarity_variable)) return property_mass_to_molar(dH, self.MW) elif method in self.tabular_data or method == COOLPROP: return float(quad(self.calculate, T1, T2, args=(method))[0]) else: raise Exception('Method not valid')
def calculate_integral_over_T(self, T1, T2, method): r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units`] ''' if method == TRCIG: S2 = TRCCp_integral_over_T(T2, *self.TRCIG_coefs) S1 = TRCCp_integral_over_T(T1, *self.TRCIG_coefs) return S2 - S1 elif method == CRCSTD: return self.CRCSTD_constant*log(T2/T1) elif method == POLING_CONST: return self.POLING_constant*log(T2/T1) elif method == POLING: A, B, C, D, E = self.POLING_coefs S2 = ((((0.25*E)*T2 + D/3.)*T2 + 0.5*C)*T2 + B)*T2 S1 = ((((0.25*E)*T1 + D/3.)*T1 + 0.5*C)*T1 + B)*T1 return R*(S2-S1 + A*log(T2/T1)) elif method == LASTOVKA_SHAW: dS = (Lastovka_Shaw_integral_over_T(T2, self.similarity_variable) - Lastovka_Shaw_integral_over_T(T1, self.similarity_variable)) return property_mass_to_molar(dS, self.MW) elif method in self.tabular_data or method == COOLPROP: return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0]) else: raise Exception('Method not valid')
def calculate_integral(self, T1, T2): r'''Method to compute the enthalpy integral of heat capacity from `T1` to `T2`. Parameters ---------- T1 : float Initial temperature, [K] T2 : float Final temperature, [K] Returns ------- dH : float Enthalpy difference between `T1` and `T2`, [J/mol] ''' return (Zabransky_quasi_polynomial_integral(T2, self.Tc, *self.coeffs) - Zabransky_quasi_polynomial_integral(T1, self.Tc, *self.coeffs))
def calculate_integral_over_T(self, T1, T2): r'''Method to compute the entropy integral of heat capacity from `T1` to `T2`. Parameters ---------- T1 : float Initial temperature, [K] T2 : float Final temperature, [K] Returns ------- dS : float Entropy difference between `T1` and `T2`, [J/mol/K] ''' return (Zabransky_quasi_polynomial_integral_over_T(T2, self.Tc, *self.coeffs) - Zabransky_quasi_polynomial_integral_over_T(T1, self.Tc, *self.coeffs))
def add_coeffs(self, Tmin, Tmax, coeffs): '''Called internally during the parsing of the Zabransky database, to add coefficients as they are read one per line''' self.n += 1 if not self.Ts: self.Ts = [Tmin, Tmax] self.coeff_sets = [coeffs] else: for ind, T in enumerate(self.Ts): if Tmin < T: # Under an existing coefficient set - assume Tmax will come from another set self.Ts.insert(ind, Tmin) self.coeff_sets.insert(ind, coeffs) return # Must be appended to end instead self.Ts.append(Tmax) self.coeff_sets.append(coeffs)
def _coeff_ind_from_T(self, T): '''Determines the index at which the coefficients for the current temperature are stored in `coeff_sets`. ''' # DO NOT CHANGE if self.n == 1: return 0 for i in range(self.n): if T <= self.Ts[i+1]: return i return self.n - 1
def calculate(self, T): r'''Method to actually calculate heat capacity as a function of temperature. Parameters ---------- T : float Temperature, [K] Returns ------- Cp : float Liquid heat capacity as T, [J/mol/K] ''' return Zabransky_cubic(T, *self.coeff_sets[self._coeff_ind_from_T(T)])
def calculate_integral(self, T1, T2): r'''Method to compute the enthalpy integral of heat capacity from `T1` to `T2`. Analytically integrates across the piecewise spline as necessary. Parameters ---------- T1 : float Initial temperature, [K] T2 : float Final temperature, [K] Returns ------- dS : float Enthalpy difference between `T1` and `T2`, [J/mol/K] ''' # Simplify the problem so we can assume T2 >= T1 if T2 < T1: flipped = True T1, T2 = T2, T1 else: flipped = False # Fastest case - only one coefficient set, occurs surprisingly often if self.n == 1: dH = (Zabransky_cubic_integral(T2, *self.coeff_sets[0]) - Zabransky_cubic_integral(T1, *self.coeff_sets[0])) else: ind_T1, ind_T2 = self._coeff_ind_from_T(T1), self._coeff_ind_from_T(T2) # Second fastest case - both are in the same coefficient set if ind_T1 == ind_T2: dH = (Zabransky_cubic_integral(T2, *self.coeff_sets[ind_T2]) - Zabransky_cubic_integral(T1, *self.coeff_sets[ind_T1])) # Fo through the loop if we need to - inevitably slow else: dH = (Zabransky_cubic_integral(self.Ts[ind_T1], *self.coeff_sets[ind_T1]) - Zabransky_cubic_integral(T1, *self.coeff_sets[ind_T1])) for i in range(ind_T1, ind_T2): diff =(Zabransky_cubic_integral(self.Ts[i+1], *self.coeff_sets[i]) - Zabransky_cubic_integral(self.Ts[i], *self.coeff_sets[i])) dH += diff end = (Zabransky_cubic_integral(T2, *self.coeff_sets[ind_T2]) - Zabransky_cubic_integral(self.Ts[ind_T2], *self.coeff_sets[ind_T2])) dH += end return -dH if flipped else dH
def calculate_integral_over_T(self, T1, T2): r'''Method to compute the entropy integral of heat capacity from `T1` to `T2`. Analytically integrates across the piecewise spline as necessary. Parameters ---------- T1 : float Initial temperature, [K] T2 : float Final temperature, [K] Returns ------- dS : float Entropy difference between `T1` and `T2`, [J/mol/K] ''' # Simplify the problem so we can assume T2 >= T1 if T2 < T1: flipped = True T1, T2 = T2, T1 else: flipped = False # Fastest case - only one coefficient set, occurs surprisingly often if self.n == 1: dS = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[0]) - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[0])) else: ind_T1, ind_T2 = self._coeff_ind_from_T(T1), self._coeff_ind_from_T(T2) # Second fastest case - both are in the same coefficient set if ind_T1 == ind_T2: dS = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[ind_T2]) - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[ind_T1])) # Fo through the loop if we need to - inevitably slow else: dS = (Zabransky_cubic_integral_over_T(self.Ts[ind_T1], *self.coeff_sets[ind_T1]) - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[ind_T1])) for i in range(ind_T1, ind_T2): diff =(Zabransky_cubic_integral_over_T(self.Ts[i+1], *self.coeff_sets[i]) - Zabransky_cubic_integral_over_T(self.Ts[i], *self.coeff_sets[i])) dS += diff end = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[ind_T2]) - Zabransky_cubic_integral_over_T(self.Ts[ind_T2], *self.coeff_sets[ind_T2])) dS += end return -dS if flipped else dS
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [] Tmins, Tmaxs = [], [] if self.CASRN in zabransky_dict_const_s: methods.append(ZABRANSKY_SPLINE) self.Zabransky_spline = zabransky_dict_const_s[self.CASRN] if self.CASRN in zabransky_dict_const_p: methods.append(ZABRANSKY_QUASIPOLYNOMIAL) self.Zabransky_quasipolynomial = zabransky_dict_const_p[self.CASRN] if self.CASRN in zabransky_dict_iso_s: methods.append(ZABRANSKY_SPLINE_C) self.Zabransky_spline_iso = zabransky_dict_iso_s[self.CASRN] if self.CASRN in zabransky_dict_iso_p: methods.append(ZABRANSKY_QUASIPOLYNOMIAL_C) self.Zabransky_quasipolynomial_iso = zabransky_dict_iso_p[self.CASRN] if self.CASRN in Poling_data.index and not np.isnan(Poling_data.at[self.CASRN, 'Cpl']): methods.append(POLING_CONST) self.POLING_T = 298.15 self.POLING_constant = float(Poling_data.at[self.CASRN, 'Cpl']) if self.CASRN in CRC_standard_data.index and not np.isnan(CRC_standard_data.at[self.CASRN, 'Cpl']): methods.append(CRCSTD) self.CRCSTD_T = 298.15 self.CRCSTD_constant = float(CRC_standard_data.at[self.CASRN, 'Cpl']) # Saturation functions if self.CASRN in zabransky_dict_sat_s: methods.append(ZABRANSKY_SPLINE_SAT) self.Zabransky_spline_sat = zabransky_dict_sat_s[self.CASRN] if self.CASRN in zabransky_dict_sat_p: methods.append(ZABRANSKY_QUASIPOLYNOMIAL_SAT) self.Zabransky_quasipolynomial_sat = zabransky_dict_sat_p[self.CASRN] if self.CASRN in _VDISaturationDict: # NOTE: VDI data is for the saturation curve, i.e. at increasing # pressure; it is normally substantially higher than the ideal gas # value methods.append(VDI_TABULAR) Ts, props = VDI_tabular_data(self.CASRN, 'Cp (l)') self.VDI_Tmin = Ts[0] self.VDI_Tmax = Ts[-1] self.tabular_data[VDI_TABULAR] = (Ts, props) Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax) if self.Tc and self.omega: methods.extend([ROWLINSON_POLING, ROWLINSON_BONDI]) if has_CoolProp and self.CASRN in coolprop_dict: methods.append(COOLPROP) self.CP_f = coolprop_fluids[self.CASRN] Tmins.append(self.CP_f.Tt); Tmaxs.append(self.CP_f.Tc) if self.MW and self.similarity_variable: methods.append(DADGOSTAR_SHAW) self.all_methods = set(methods) if Tmins and Tmaxs: # TODO: More Tmin, Tmax ranges self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)
def calculate(self, T, method): r'''Method to calculate heat capacity of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate heat capacity, [K] method : str Name of the method to use Returns ------- Cp : float Heat capacity of the liquid at T, [J/mol/K] ''' if method == ZABRANSKY_SPLINE: return self.Zabransky_spline.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL: return self.Zabransky_quasipolynomial.calculate(T) elif method == ZABRANSKY_SPLINE_C: return self.Zabransky_spline_iso.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL_C: return self.Zabransky_quasipolynomial_iso.calculate(T) elif method == ZABRANSKY_SPLINE_SAT: return self.Zabransky_spline_sat.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT: return self.Zabransky_quasipolynomial_sat.calculate(T) elif method == COOLPROP: return CoolProp_T_dependent_property(T, self.CASRN , 'CPMOLAR', 'l') elif method == POLING_CONST: return self.POLING_constant elif method == CRCSTD: return self.CRCSTD_constant elif method == ROWLINSON_POLING: Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm return Rowlinson_Poling(T, self.Tc, self.omega, Cpgm) elif method == ROWLINSON_BONDI: Cpgm = self.Cpgm(T) if hasattr(self.Cpgm, '__call__') else self.Cpgm return Rowlinson_Bondi(T, self.Tc, self.omega, Cpgm) elif method == DADGOSTAR_SHAW: Cp = Dadgostar_Shaw(T, self.similarity_variable) return property_mass_to_molar(Cp, self.MW) elif method in self.tabular_data: return self.interpolate(T, method) else: raise Exception('Method not valid')
def calculate_integral(self, T1, T2, method): r'''Method to calculate the integral of a property with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data, the case of multiple coefficient sets needed to encompass the temperature range of any of the ZABRANSKY methods, and the CSP methods using the vapor phase properties. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units*K`] ''' if method == ZABRANSKY_SPLINE: return self.Zabransky_spline.calculate_integral(T1, T2) elif method == ZABRANSKY_SPLINE_C: return self.Zabransky_spline_iso.calculate_integral(T1, T2) elif method == ZABRANSKY_SPLINE_SAT: return self.Zabransky_spline_sat.calculate_integral(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL: return self.Zabransky_quasipolynomial.calculate_integral(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL_C: return self.Zabransky_quasipolynomial_iso.calculate_integral(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT: return self.Zabransky_quasipolynomial_sat.calculate_integral(T1, T2) elif method == POLING_CONST: return (T2 - T1)*self.POLING_constant elif method == CRCSTD: return (T2 - T1)*self.CRCSTD_constant elif method == DADGOSTAR_SHAW: dH = (Dadgostar_Shaw_integral(T2, self.similarity_variable) - Dadgostar_Shaw_integral(T1, self.similarity_variable)) return property_mass_to_molar(dH, self.MW) elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]: return float(quad(self.calculate, T1, T2, args=(method))[0]) else: raise Exception('Method not valid')
def calculate_integral_over_T(self, T1, T2, method): r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data, the case of multiple coefficient sets needed to encompass the temperature range of any of the ZABRANSKY methods, and the CSP methods using the vapor phase properties. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units`] ''' if method == ZABRANSKY_SPLINE: return self.Zabransky_spline.calculate_integral_over_T(T1, T2) elif method == ZABRANSKY_SPLINE_C: return self.Zabransky_spline_iso.calculate_integral_over_T(T1, T2) elif method == ZABRANSKY_SPLINE_SAT: return self.Zabransky_spline_sat.calculate_integral_over_T(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL: return self.Zabransky_quasipolynomial.calculate_integral_over_T(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL_C: return self.Zabransky_quasipolynomial_iso.calculate_integral_over_T(T1, T2) elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT: return self.Zabransky_quasipolynomial_sat.calculate_integral_over_T(T1, T2) elif method == POLING_CONST: return self.POLING_constant*log(T2/T1) elif method == CRCSTD: return self.CRCSTD_constant*log(T2/T1) elif method == DADGOSTAR_SHAW: dS = (Dadgostar_Shaw_integral_over_T(T2, self.similarity_variable) - Dadgostar_Shaw_integral_over_T(T1, self.similarity_variable)) return property_mass_to_molar(dS, self.MW) elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]: return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0]) else: raise Exception('Method not valid')
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [] Tmins, Tmaxs = [], [] if self.CASRN and self.CASRN in _PerryI and 'c' in _PerryI[self.CASRN]: self.PERRY151_Tmin = _PerryI[self.CASRN]['c']['Tmin'] if _PerryI[self.CASRN]['c']['Tmin'] else 0 self.PERRY151_Tmax = _PerryI[self.CASRN]['c']['Tmax'] if _PerryI[self.CASRN]['c']['Tmax'] else 2000 self.PERRY151_const = _PerryI[self.CASRN]['c']['Const'] self.PERRY151_lin = _PerryI[self.CASRN]['c']['Lin'] self.PERRY151_quad = _PerryI[self.CASRN]['c']['Quad'] self.PERRY151_quadinv = _PerryI[self.CASRN]['c']['Quadinv'] methods.append(PERRY151) Tmins.append(self.PERRY151_Tmin); Tmaxs.append(self.PERRY151_Tmax) if self.CASRN in CRC_standard_data.index and not np.isnan(CRC_standard_data.at[self.CASRN, 'Cpc']): self.CRCSTD_Cp = float(CRC_standard_data.at[self.CASRN, 'Cpc']) methods.append(CRCSTD) if self.MW and self.similarity_variable: methods.append(LASTOVKA_S) Tmins.append(1.0); Tmaxs.append(10000) # Works above roughly 1 K up to 10K. self.all_methods = set(methods) if Tmins and Tmaxs: self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)
def calculate(self, T, method): r'''Method to calculate heat capacity of a solid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate heat capacity, [K] method : str Name of the method to use Returns ------- Cp : float Heat capacity of the solid at T, [J/mol/K] ''' if method == PERRY151: Cp = (self.PERRY151_const + self.PERRY151_lin*T + self.PERRY151_quadinv/T**2 + self.PERRY151_quad*T**2)*calorie elif method == CRCSTD: Cp = self.CRCSTD_Cp elif method == LASTOVKA_S: Cp = Lastovka_solid(T, self.similarity_variable) Cp = property_mass_to_molar(Cp, self.MW) elif method in self.tabular_data: Cp = self.interpolate(T, method) return Cp
def calculate_integral(self, T1, T2, method): r'''Method to calculate the integral of a property with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units*K`] ''' if method == PERRY151: H2 = (self.PERRY151_const*T2 + 0.5*self.PERRY151_lin*T2**2 - self.PERRY151_quadinv/T2 + self.PERRY151_quad*T2**3/3.) H1 = (self.PERRY151_const*T1 + 0.5*self.PERRY151_lin*T1**2 - self.PERRY151_quadinv/T1 + self.PERRY151_quad*T1**3/3.) return (H2-H1)*calorie elif method == CRCSTD: return (T2-T1)*self.CRCSTD_Cp elif method == LASTOVKA_S: dH = (Lastovka_solid_integral(T2, self.similarity_variable) - Lastovka_solid_integral(T1, self.similarity_variable)) return property_mass_to_molar(dH, self.MW) elif method in self.tabular_data: return float(quad(self.calculate, T1, T2, args=(method))[0]) else: raise Exception('Method not valid')
def calculate_integral_over_T(self, T1, T2, method): r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units`] ''' if method == PERRY151: S2 = (self.PERRY151_const*log(T2) + self.PERRY151_lin*T2 - self.PERRY151_quadinv/(2.*T2**2) + 0.5*self.PERRY151_quad*T2**2) S1 = (self.PERRY151_const*log(T1) + self.PERRY151_lin*T1 - self.PERRY151_quadinv/(2.*T1**2) + 0.5*self.PERRY151_quad*T1**2) return (S2 - S1)*calorie elif method == CRCSTD: S2 = self.CRCSTD_Cp*log(T2) S1 = self.CRCSTD_Cp*log(T1) return (S2 - S1) elif method == LASTOVKA_S: dS = (Lastovka_solid_integral_over_T(T2, self.similarity_variable) - Lastovka_solid_integral_over_T(T1, self.similarity_variable)) return property_mass_to_molar(dS, self.MW) elif method in self.tabular_data: return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0]) else: raise Exception('Method not valid')
def load_all_methods(self): r'''Method to initialize the object by precomputing any values which may be used repeatedly and by retrieving mixture-specific variables. All data are stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods which should work to calculate the property. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [SIMPLE] if len(self.CASs) > 1 and '7732-18-5' in self.CASs: wCASs = [i for i in self.CASs if i != '7732-18-5'] if all([i in _Laliberte_Heat_Capacity_ParametersDict for i in wCASs]): methods.append(LALIBERTE) self.wCASs = wCASs self.index_w = self.CASs.index('7732-18-5') self.all_methods = set(methods)
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- Cplm : float Molar heat capacity of the liquid mixture at the given conditions, [J/mol] ''' if method == SIMPLE: Cplms = [i(T) for i in self.HeatCapacityLiquids] return mixing_simple(zs, Cplms) elif method == LALIBERTE: ws = list(ws) ; ws.pop(self.index_w) Cpl = Laliberte_heat_capacity(T, ws, self.wCASs) MW = mixing_simple(zs, self.MWs) return property_mass_to_molar(Cpl, MW) else: raise Exception('Method not valid')
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a solid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- Cpsm : float Molar heat capacity of the solid mixture at the given conditions, [J/mol] ''' if method == SIMPLE: Cpsms = [i(T) for i in self.HeatCapacitySolids] return mixing_simple(zs, Cpsms) else: raise Exception('Method not valid')
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a gas mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- Cpgm : float Molar heat capacity of the gas mixture at the given conditions, [J/mol] ''' if method == SIMPLE: Cpgms = [i(T) for i in self.HeatCapacityGases] return mixing_simple(zs, Cpgms) else: raise Exception('Method not valid')