def __init__(self, width, height, border): self.button_data = Const() self.button_data.width = 100 self.button_data.large_width = self.button_data.width * 2 self.button_data.height = 50 ## Spread buttons out between sweep and edge self.button_data.done_x = border.inner_x() + Widths.BORDER self.button_data.cancel_x = width - Widths.BORDER - self.button_data.large_width self.button_data.pay_x = (self.button_data.done_x + self.button_data.cancel_x) / 2 self.button_data.y = height - Widths.BORDER - self.button_data.height # Put buttons at bottom of screen ## Put the top bar below the sweep self.top_bar = Const() self.top_bar.x = border.inner_x() + Widths.BORDER self.top_bar.y = border.inner_y() + Widths.BORDER ## This allows caculation of the inner width of the useable screen area self.inner_width = width - self.top_bar.x - Widths.BORDER ## And then the small amount bar can be defined self.amount = Const() self.amount.y = self.top_bar.y self.amount.width = 2 * self.button_data.width self.amount.x = width - Widths.BORDER - self.amount.width ## And finally the top bar width can be defined self.top_bar.width = self.inner_width - self.amount.width - Widths.BORDER ## The first product entry starts below the top bar self.product_entries = Const() self.product_entries.top_y = self.top_bar.y + self.button_data.height + Widths.BORDER # The up/dn scroll buttons cover the whole height of the screen scroll_height = (self.button_data.y - self.product_entries.top_y) / 2 scroll_height -= Widths.BORDER self.scroll = Const() self.scroll.height = scroll_height self.scroll.width = self.button_data.height self.scroll.x = width - Widths.BORDER - self.scroll.width self.scroll.up_y = self.product_entries.top_y self.scroll.dn_y = self.scroll.up_y + self.scroll.height + Widths.BORDER # Position constants for product objects self.product_entries.desc_x = self.top_bar.x self.product_entries.desc_w = self.button_data.large_width * 1.8 self.product_entries.price_x = self.product_entries.desc_x + self.product_entries.desc_w + Widths.BORDER self.product_entries.price_w = self.button_data.large_width / 2 self.product_entries.remove_x = self.product_entries.price_x + self.product_entries.price_w + Widths.BORDER self.product_entries.row_h = self.button_data.height + 20
def split_triple_type(): const = Const() const.novel_tagging() data = utils.read_json(Const.raw_test_filename) normal_triple_data = [] multi_label_data = [] over_lapping_data = [] for i, a_data in enumerate(data): triples = a_data['relationMentions'] triples_ = set() for triple in triples: m1 = nltk.word_tokenize(triple['em1Text'])[-1] m2 = nltk.word_tokenize(triple['em2Text'])[-1] label = triple['label'] if label != 'None': triples_.add((m1, m2, label)) triples = [] for t in triples_: triples.extend(list(t)) if utils.is_normal_triple(triples, is_relation_first=False): normal_triple_data.append(a_data) if utils.is_multi_label(triples, is_relation_first=False): multi_label_data.append(a_data) if utils.is_over_lapping(triples, is_relation_first=False): over_lapping_data.append(a_data) print('Number of normal triple data %s' % len(normal_triple_data)) print('Number of multi triple data %s' % len(multi_label_data)) print('Number of overlapping triple data %s' % len(over_lapping_data)) utils.write_data(open(const.raw_test_normal_triple_filename, 'w'), normal_triple_data) utils.write_data(open(const.raw_test_multi_label_filename, 'w'), multi_label_data) utils.write_data(open(const.raw_test_overlapping_filename, 'w'), over_lapping_data)
def __init__(self): self.config = Config() # setup variables self.const = Const() # Set logging level and info logging.basicConfig(level=self.config.LOG_LEVEL, format=self.const.LOG_FORMAT)
def top_to_tile(top, tile, tile_idx): tile.add_ports(tile_id=magma.In(magma.Bits(16))) top.wire(Const(magma.bits(tile_idx, 16)), tile.tile_id) tile_eq = FromMagma(mantle.DefineEQ(16)) tile.wire(tile.tile_id, tile_eq.I0) tile.wire(tile.config.config_addr[0:16], tile_eq.I1) return tile_eq
def split_triple_number(): const = Const() const.novel_tagging() data = utils.read_json(Const.raw_test_filename) # sentences contains 1, 2, 3, 4, and >5 triples triples_size_1_data, triples_size_2_data, triples_size_3_data, triples_size_4_data, triples_size_5_data = [], [], [], [], [] for i, a_data in enumerate(data): triples = set() for triple in a_data['relationMentions']: m1 = nltk.word_tokenize(triple['em1Text'])[-1] m2 = nltk.word_tokenize(triple['em2Text'])[-1] label = triple['label'] if label != 'None': triples.add((m1, m2, label)) if len(triples) == 1: triples_size_1_data.append(a_data) elif len(triples) == 2: triples_size_2_data.append(a_data) elif len(triples) == 3: triples_size_3_data.append(a_data) elif len(triples) == 4: triples_size_4_data.append(a_data) else: triples_size_5_data.append(a_data) utils.write_data(open(const.raw_test_1_triple_filename, 'w'), triples_size_1_data) utils.write_data(open(const.raw_test_2_triple_filename, 'w'), triples_size_2_data) utils.write_data(open(const.raw_test_3_triple_filename, 'w'), triples_size_3_data) utils.write_data(open(const.raw_test_4_triple_filename, 'w'), triples_size_4_data) utils.write_data(open(const.raw_test_5_triple_filename, 'w'), triples_size_5_data) print 'Sentence-1-Triple: %d' % len(triples_size_1_data) print 'Sentence-2-Triple: %d' % len(triples_size_2_data) print 'Sentence-3-Triple: %d' % len(triples_size_3_data) print 'Sentence-4-Triple: %d' % len(triples_size_4_data) print 'Sentence-5-Triple: %d' % len(triples_size_5_data)
def __init__(self, a=0.3, M_c=5): self.con = Const(a, M_c) self.values = [] self.dValues = [] self.dr = 0.0 self.num = 1000 self.f = []
def __init__(self): super().__init__() self.add_ports( O=magma.Out(magma.Bits(16)), ) self.wire(Const(magma.bits(0, 16)), self.O)
def tile_to_feature(tile, tile_eq, feature, feature_idx): feature.add_ports(config_en=magma.In(magma.Bit)) feature_eq = FromMagma(mantle.DefineEQ(8)) tile.wire(tile.config.config_addr[16:24], feature_eq.I0) tile.wire(Const(magma.bits(feature_idx, 8)), feature_eq.I1) feature_en = FromMagma(mantle.DefineAnd()) tile.wire(feature_eq.O, feature_en.I0) tile.wire(tile_eq.O, feature_en.I1) tile.wire(feature_en.O, feature.config_en)
def __init__(self): # Config and setup self.const = Const() self.config = Config() locale.setlocale(locale.LC_TIME, self.config.LOCALE) # Set logging level and info logging.basicConfig(level=self.config.LOG_LEVEL, format=self.const.LOG_FORMAT) self.covidHandler = CovidHandler() self.temperatureHandler = TemperatureHandler()
def __init__(self): self.config = Config() # Set logging level and info logging.basicConfig( level=self.config.LOG_LEVEL, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.database = mysql.connector.connect(host=self.config.DBHOST, database=self.config.DBNAME, user=self.config.DBUSER, password=self.config.DBPASSWD) self.cursor = self.database.cursor() self.const = Const()
def tile_to_feature(tile, tile_eq, feature, feature_idx): feature.add_ports( config=magma.In(ConfigurationType(8, 32)), config_en=magma.In(magma.Bit), ) tile.wire(tile.config.config_addr[24:], feature.config.config_addr) tile.wire(tile.config.config_data, feature.config.config_data) feature_eq = FromMagma(mantle.DefineEQ(8)) tile.wire(tile.config.config_addr[16:24], feature_eq.I0) tile.wire(Const(magma.bits(feature_idx, 8)), feature_eq.I1) feature_en = FromMagma(mantle.DefineAnd()) tile.wire(feature_eq.O, feature_en.I0) tile.wire(tile_eq.O, feature_en.I1) tile.wire(feature_en.O, feature.config_en)
def __init__(self, product): self.product = product self.formats = Const() self.formats.desc_pence = "%s (%dp)" self.formats.desc_pounds = u"%s (\xA3%.2f)" self.formats.price_pence = "%dp" self.formats.price_pounds = "\xA3%.2f" self.lcars_objects = [None] * 3 self.description = '' self.price_string = '' self.visible = True
def updateData(brokerName, list): sql = "insert into price values" const = Const.Const() for k in list.keys(): pattern = r"[0-9\.]+" matchlist = re.findall(pattern, list[k]) b = matchlist[0] a = matchlist[1] s = round((float(a) - float(b)) * 100000) / 100000 sql = sql + "('" + brokerName + "','" + k + "'," + str(b) + "," + str(a) + "," + str(s) + ", current_timestamp)," sql = sql[0:-1] + ";" db = Db.Db() db.execute(const.POSTGRE_HOST, const.POSTGRE_PORT, const.POSTGRE_DB, const.POSTGRE_USER, const.POSTGRE_PW, "delete from price where broker='" + brokerName + "';") db.execute(const.POSTGRE_HOST, const.POSTGRE_PORT, const.POSTGRE_DB, const.POSTGRE_USER, const.POSTGRE_PW, sql)
def test_simple_kernel(self): """ Implement a simple kernel. """ for case in self.cases: # Form data to work on. space.initialize_space(case['shape']) x_np = comm.allreduce( np.random.randn(*case['shape']).astype(case['dtype'])) x = Grid(x_np, x_overlap=2) s_np = comm.allreduce( np.random.randn(case['shape'][0], 1, 1).astype(case['dtype'])) s = Const(s_np) z = Out(case['dtype']) # Make a kernel. code = Template(""" if (_in_local && _in_global) { z += a * s(_X) * x(0,0,0); // z += a * x(0,0,0); } """).render() fun = Kernel(code, \ ('a', 'number', case['dtype']), \ ('x', 'grid', x.dtype), \ ('s', 'const', s.dtype), \ ('z', 'out', z.dtype), \ shape_filter='all') # Execute and check the result. # fun() while fun.exec_configs: # for k in range(40): fun(case['dtype'](2.0), x, s, z) # fun(case['dtype'](2.0), x, z) gpu_sum = z.get() cpu_sum = np.sum(2 * s_np * x_np) # cpu_sum = np.sum(2 * x_np) err = abs(gpu_sum - cpu_sum) / abs(cpu_sum) if case['dtype'] in (np.float32, np.complex64): self.assertTrue(err < 1e-2, (case, err)) else: self.assertTrue(err < 1e-6, (case, err))
def test_padded_kernel(self): """ Implement a simple padded kernel. """ for case in self.cases: # Form data to work on. space.initialize_space(case['shape']) x_np = comm.allreduce( np.random.randn(*case['shape']).astype(case['dtype'])) x = Grid(x_np, x_overlap=1) s_np = comm.allreduce(np.random.randn(1).astype(case['dtype'])) s = Const(s_np) z = Out(case['dtype']) # Make a kernel. code = Template(""" if (_in_local && _in_global) { x(0,0,0) = s(0) * x(0,0,0); z += a * x(0,0,0); } """).render() fun = Kernel(code, \ ('a', 'number', case['dtype']), \ ('x', 'grid', x.dtype), \ ('s', 'const', s.dtype, s.data.size), \ ('z', 'out', z.dtype), \ padding=(1,1,1,1)) # Execute and check the result. fun(case['dtype'](2), x, s, z) gpu_sum = z.get() cpu_sum = np.sum(2.0 * s_np * x_np) err = abs(gpu_sum - cpu_sum) / abs(cpu_sum) # print case, err if case['dtype'] in (np.float32, np.complex64): self.assertTrue(err < 1e-2, (case, err)) else: self.assertTrue(err < 1e-6, (case, err))
# coding:utf-8 ''' Created on 2020-10-14 @author: Dizzy ''' from CDeviceType import CDeviceType from CDeviceType import CDeviceVersion from CDevice import CDevice from selenium.webdriver.common.keys import Keys #需要引入 keys 包 from selenium.webdriver.support.select import Select from const import Const from selenium.webdriver.common.action_chains import ActionChains import time const = Const() const.NAME_ACCOUNT = "account" const.NAME_PASSWORD = "******" const.NAME_SUBMIT = "btnSubmit" const.LINK_TEXT_CONNECT_TO_INTERNET = "连接到因特网" const.EXTEND_URL_WAN_NEW = "wan_new.asp" const.EXTEND_URL_VLAN_ADD = "vlan_intf_set.asp" const.EXTEND_URL_VLAN_PORT_SET = "vlan_port_set.asp" class CDevice_H3C_ER3200G2(CDevice): ''' classdocs ''' def __init__(self, enDeviceVersion): '''
This template provide a rich console interface thanks to the rich library by @willmcgugan """ import logging from sys import exit as clean_exit from rich.live import Live from instapy import InstaPy from const import Const from parameters import load_from_args from rich_dashboard import RichDashboard from rich_log_filter import RichLogFilter C = Const() parameters = load_from_args() rich_dashboard = RichDashboard(parameters) rich_filter = RichLogFilter(rich_dashboard, [logging.getLogger(parameters.username)]) with Live( rich_dashboard.dashboard_table, console=rich_dashboard.console, refresh_per_second=10, ): try: # get an InstaPy session with rich_dashboard.log_step('Begin session'): session = InstaPy(
Where packettype is the context of the packet data("transaction", "getuser", "ping" etc.) and datatype is the context of the individual data items enclosed, e.g <barcode>12345</barcode> This file is responsible for pushing data to/from Python data structures and XML DOM objects. ''' from xml.dom.minidom import parseString from xml.dom.minidom import getDOMImplementation from const import Const ## Constants defining packet types PacketTypes = Const() PacketTypes.Ping = "ping" PacketTypes.PingReply = "pingreply" PacketTypes.GetRandomProduct = "randomproduct" PacketTypes.AddCredit = "addcredit" PacketTypes.AddProduct = "addproduct" PacketTypes.Transaction = "transaction" PacketTypes.GetUser = "******" PacketTypes.GetProduct = "getproduct" PacketTypes.ProductData = "productdata" PacketTypes.UserData = "userdata" PacketTypes.UnknownProduct = "unknownproduct" PacketTypes.UnknownUser = "******" PacketTypes.RandomProduct = "randomproduct" PacketTypes.Result = "result"
def __init__(self, width, height, owner): ScreenGUI.__init__(self, width, height, owner) self.border = Border(width, height) # Object constant definitions # Reverse draw order - 0 drawn last self.ids = Enum("DONE", "CANCEL", "PAY", "TOPBAR", "AMOUNT", "UP", "DOWN", "PRODUCT", "REMOVE") self.limits = Const() self.limits.screen_products = 5 self.limits.objects_per_product_row = 3 self.logger = logging.getLogger("MainScreen.GUI") self.product_displays = ProductDisplayCollection( self.limits.screen_products) # # # # Fixed position objects # # self.layout = MainScreenLayout(width, height, self.border) self.objects = { self.ids.DONE: LCARSCappedBar(self.layout.get_done_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, "Done", Colours.FG, Colours.BG, False), self.ids.PAY: LCARSCappedBar(self.layout.get_pay_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, "Pay debt", Colours.FG, Colours.BG, False), self.ids.CANCEL: LCARSCappedBar(self.layout.get_cancel_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, "Cancel", Colours.FG, Colours.BG, True), self.ids.TOPBAR: LCARSCappedBar(self.layout.get_top_bar_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, "User: <No user scanned>", Colours.FG, Colours.BG, True), self.ids.UP: LCARSCappedBar(self.layout.get_up_scroll_rect(), CapLocation.CAP_TOP, "UP", Colours.FG, Colours.BG, False), self.ids.DOWN: LCARSCappedBar(self.layout.get_down_scroll_rect(), CapLocation.CAP_BOTTOM, "DN", Colours.FG, Colours.BG, False), self.ids.AMOUNT: LCARSCappedBar(self.layout.get_amount_rect(), CapLocation.CAP_LEFT + CapLocation.CAP_RIGHT, "Total Spend: \xA30.00", Colours.FG, Colours.BG, True) } # # # # Import standard objects # # self.objects.update(self.border.get_border())
from lib import Rakuten from const import Const from lib import Db def updateData(brokerName, list): sql = "insert into price values" const = Const.Const() for k in list.keys(): pattern = r"[0-9\.]+" matchlist = re.findall(pattern, list[k]) b = matchlist[0] a = matchlist[1] s = round((float(a) - float(b)) * 100000) / 100000 sql = sql + "('" + brokerName + "','" + k + "'," + str(b) + "," + str(a) + "," + str(s) + ", current_timestamp)," sql = sql[0:-1] + ";" db = Db.Db() db.execute(const.POSTGRE_HOST, const.POSTGRE_PORT, const.POSTGRE_DB, const.POSTGRE_USER, const.POSTGRE_PW, "delete from price where broker='" + brokerName + "';") db.execute(const.POSTGRE_HOST, const.POSTGRE_PORT, const.POSTGRE_DB, const.POSTGRE_USER, const.POSTGRE_PW, sql) const = Const.Const() raku = Rakuten.Price() raku_data = raku.getPrice(const.URL_RAKUTEN) updateData("rakuten", raku_data)
class Methods(object): con = Const( ) #If the Const you need is not initial, you need to change it. P = None T = None M = None L = None sigma = None L_store = 0 @classmethod def ode_fun(cls, Z, r, c_P, c_T, c_M, others, ST): P, T, M, L = Z g, alpha, beta = others dP = c_P * M * P / (T * r**2) dT = min(c_T * 1e24 * L * P**(alpha + 1) * T**(beta - 4) / M, g) * (T * dP / P) dM = c_M * r**2 * P / T if dT == g * (T * dP / P): dL = 1e-24 * cls.con.M_e * cls.con.T_0 * dM * ST else: dL = 0 return [dP, dT, dM, dL] @classmethod def cal_ML_simple(cls, ST, L_s): c_P, c_T, c_M = cls.con.cal_const() g, alpha, beta = cls.con.g_ad, cls.con.alpha, cls.con.beta R_in, R_out = cls.con.R_p, cls.con.R_out num = 800 r = np.linspace(1, R_in / R_out, num) initial = (1., 1., cls.con.M_p, L_s) others = (g, alpha, beta) result = odeint(cls.ode_fun, initial, r, args=(c_P, c_T, c_M, others, ST)) P, T, M, L = result[:, 0], result[:, 1], result[:, 2], result[:, 3] cls.P, cls.T, cls.M, cls.L = P, T, M, L cls.r = r sigma = cls.con.sigma_1 * T**(3. / 4.) * P**(-1. / 2.) * np.exp( -cls.con.sigma_2 / T) cls.sigma = sigma return M[-1], L[-1] @classmethod def cal_L_safe(cls, ST, L_s): try: warnings.simplefilter('error') M, L = cls.cal_ML_simple(ST, L_s) except: ST = cls.find_safe_point(ST, L_s) L = cls.cal_ML_simple(ST, L_s)[1] finally: return ST, L @classmethod def grad(cls, point1, point2): """Return the grad of two points, so for one-dimention Newton iteration.""" return (point2[1] - point1[1]) / (point2[0] - point1[0]) @classmethod def find_L_M(cls, targets, inits, steps, errors): """The order of targets is [M_c, L_c], of inits is [ST, L_s](Note that the unit of L_s is 1e+24 erg/s), of steps and error is the same as inits and targets.""" """The way to find the result is one-dimention Newton iteration. First adjustion is L_s and then is ST.""" ST, L_s = inits M_c_need, L_c_need = targets error_M_c, error_L_c = errors M_c, L_c = cls.cal_ML_simple(ST, L_s) while abs(M_c - M_c_need) > error_M_c or abs(L_c - L_c_need) > error_L_c: while abs(M_c - M_c_need) > error_M_c: point1 = (L_s, M_c) point2 = (L_s + steps[1], cls.cal_ML_simple(ST, L_s + steps[1])[0]) k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError('k is zero.') else: L_s = (M_c_need - M_c) / k + L_s if L_s < 0: L_s = -L_s M_c, L_c = cls.cal_ML_simple(ST, L_s) while abs(L_c_need - L_c) > error_L_c: ST_next = ST + steps[0] point2 = cls.cal_L_safe(ST_next, L_s) point1 = [ ST_next - steps[0], cls.cal_L_safe(ST_next - steps[0], L_s)[1] ] k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError('k is zero.') else: ST = (L_c_need - L_s) / k + ST ST, L_c = cls.cal_L_safe(ST, L_s) return [[ST, L_s], [M_c, L_c]] @classmethod def change_const(cls, new_const): cls.con = new_const @classmethod def find_safe_point(cls, ST_init, L_s): L = L_s ST = ST_init ST_store = 0 judge = False if ST < 0: ST = -ST while True: try: warnings.simplefilter('error') L_c = cls.cal_ML_simple(ST, L)[1] except: if judge: ST = ST - ST_store break ST /= 10 ST_store = ST else: ST += ST_store judge = True ST_left = ST ST_right = ST + ST_store while abs(L_c) > 0.003: ST = (ST_left + ST_right) / 2 try: warnings.simplefilter('error') L_c = cls.cal_ML_simple(ST, L)[1] except: ST_right = ST L_c = -10 #set a value to continue the loop continue else: ST_left = ST continue return ST
# -*- coding: utf-8 -*- """ Created on Wed Jun 12 17:13:24 2019 @author: 文明研究员 """ import numpy as np import matplotlib.pyplot as plt from calculator import Methods, Calculator from const import Const from scipy.optimize import leastsq def func(p, x): k, b = p return k * x + b def error(p, x, y): return func(p, x) - y / 1e+13 if __name__ == '__main__': cal = Calculator() cal.me.change_const(Const(0.3)) M_p = np.linspace(5.15, 12, 200) cal.creat_data(M_p, 'Data2.xlsx', 'test.png')
Constant values for layout, color, etc. pylint message C0103 disabled due to requiring UPPERCASE identifiers for constants and Proper Case for classes/collections """ from enum import Enum from const import Const # Available snackspace screens Screens = Enum("BLANKSCREEN", "INTROSCREEN", "MAINSCREEN", "NUMERICENTRY", "PRODUCTENTRY", "WAITING") #pylint: disable=C0103 # Global widths for LCARS style interface Widths = Const() #pylint: disable=C0103 Widths.BORDER = 20 #pylint: disable=W0201,C0103 Widths.LARGE_BAR = 60 #pylint: disable=W0201,C0103 Widths.SMALL_BAR = 30 #pylint: disable=W0201,C0103 # Global colour pallette Colours = Const() #pylint: disable=C0103 Colours.BG = (0, 0, 0) #pylint: disable=W0201,C0103 Colours.FG = (40, 89, 45) #pylint: disable=W0201,C0103 Colours.WARN = (255, 255, 0) #pylint: disable=W0201,C0103 Colours.ERR = (255, 0, 0) #pylint: disable=W0201,C0103 Colours.INFO = (0, 255, 0) #pylint: disable=W0201,C0103 Colours.ENTRY = (0, 128, 0) #pylint: disable=W0201,C0103 # Name of sound file for touchscreen press SOUNDFILE = "press_sound.ogg"
def __init__(self): self.config = Config() self.const = Const() logging.basicConfig(level=self.config.LOG_LEVEL, format=self.const.LOG_FORMAT)
import numpy as np import matplotlib.pyplot as plt from calculator import Methods,Calculator from scipy.optimize import leastsq from const import Const def func(p,x): k,b=p return k*x+b def error(p,x,y): return func(p,x)-y/1e+13 if __name__=='__main__': cal=Calculator() cal.me.change_const(Const(0.2)) M_p=np.linspace(5.2,12,200) cal.creat_data(M_p,'Data3.xlsx','test.png')
#!/usr/bin/python # -*- coding: UTF-8 -*- from const import Const ProjectConst = Const() #MP listener IP and port ProjectConst.ListenerIP = "0.0.0.0" ProjectConst.ListenerPort = 12345 ProjectConst.CLOUD_API_URL = "http://localhost:55555/"
class Test(object): con = Const(0.3) values = [] dValues = [] dr = 0.0 num = 1000 f = [] @classmethod def ode_fun_B(cls, Z, r, c_P, c_T, c_M, others, ST): P, T, M, G, DG, L = Z #if L<-1000: #raise LOutOfRangeError('L<-1000') g, alpha, beta, Lambda, R_B = others dP = c_P * M * P / (T * r**2) P_0 = cls.con.P_0 dT = min(c_T * 1e24 * abs(L) * P**(alpha + 1) * T**(beta - 4) / M, g) * (T * dP / P) dM = c_M * r**2 * P / T dG = DG if P <= 0.0: print("Error") dL = Lambda * 7.15e-5 * (dG**2 + G**2 / r**2) / ( 9e9 * 10**cls.f(np.log10(P * P_0) - 6) * R_B) if dT == g * (T * dP / P): dL += 1e-24 * cls.con.M_e * cls.con.T_0 * dM * ST else: dL += 0 ddG = 6 * G / r**2 + ( 0.5 * 1e3 * (cls.f(np.log10(P * P_0) - 6 + 1e-3) - cls.f(np.log10(P * P_0) - 6 - 1e-3)) * dP / P) * dG + (r > cls.con.depth) * 2 * cls.con.M_v * ( 1 / r - cls.con.depth**2 / r**3) / cls.con.c**2 / cls.con.R_B return [dP, dT, dM, dG, ddG, dL] @classmethod def find_RCB_index(cls): P, T, M, L = cls.P, cls.T, cls.M, cls.L judge = (cls.con.c_T * 1e24 * abs(L) * P**(cls.con.alpha + 1) * T**(cls.con.beta - 4) / M) < (np.ones(len(L)) * cls.con.g_ad) for i in range(len(judge)): if judge[i] != judge[0]: cls.RCB_index = i return i return 0 @classmethod def cal_ML_simple_B(cls, ST, L_s, B=False, G=1e-12, dG=1e-15): c_P, c_T, c_M = cls.con.cal_const() g, alpha, beta = cls.con.g_ad, cls.con.alpha, cls.con.beta R_in, R_out = cls.con.R_p, cls.con.R_out num = cls.num base = DataBase() base.creat_sigma() cls.f = base.f_sigma r = np.linspace(1, R_in / R_out, num) cls.dr = r[0] - r[1] if B: initial = (1., 1., cls.con.M_p, G, dG, L_s) else: initial = (1., 1., cls.con.M_p, 0.0, 0.0, L_s) others = (g, alpha, beta, cls.con.Lambda, cls.con.R_B) result = odeint(cls.ode_fun_B, initial, r, args=(c_P, c_T, c_M, others, ST)) P, T, M, G, dg, L = result[:, 0], result[:, 1], result[:, 2], result[:, 3], result[:, 4], result[:, 5] cls.P, cls.T, cls.M, cls.L = P, T, M, L cls.r, cls.g = r, G cls.dg = dg cls.find_RCB_index() return M[-1], L[-1], G[-1] @classmethod def sigma(cls, P, T): return cls.con.sigma_1 * T**(3. / 4) * P**(-1. / 2) * np.exp( -cls.con.sigma_2 / T) @classmethod def find_ML_simple(cls, targets, inits, steps, errors): """The order of targets is [M_c, L_c], of inits is [ST, L_s](Note that the unit of L_s is 1e+24 erg/s), of steps and error is the same as inits and targets.""" """The way to find the result is one-dimention Newton iteration. First adjustion is L_s and then is ST.""" ST, L_s = inits M_c_need, L_c_need = targets error_M_c, error_L_c = errors M_c, L_c = cls.cal_ML_simple_B(ST, L_s, True, 0.0, -1)[0:2] while abs(M_c - M_c_need) > error_M_c or abs(L_c - L_c_need) > error_L_c: while abs(M_c - M_c_need) > error_M_c: point1 = (L_s, M_c) point2 = (L_s + L_s * steps[1], cls.cal_ML_simple_B(ST, L_s + L_s * steps[1], True, 0.0, -1)[0]) k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError( 'k is zero.Error is M_c,M_p is {0}'.format( cls.con.M_p)) else: L_s = (M_c_need - M_c) / k + L_s if L_s < 0: L_s = -L_s / 10 M_c, L_c = cls.cal_ML_simple_B(ST, L_s, True, 0.0, -1)[0:2] print(M_c, L_c) while abs(L_c_need - L_c) > error_L_c: ST_next = ST + steps L_c_next = cls.cal_ML_simple_B(ST_next, L_s, True, 0.0, -1)[1] point1 = [ST, L_c] point2 = [ST_next, L_c_next] k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError( 'k is zero.Error is L_c. M_p is {0}'.format( cls.con.M_p)) else: ST = (L_c_need - L_c) / k + ST L_c = cls.cal_ML_simple_B(ST, L_s, True, 0.0, -1)[1] print(M_c, L_c) return ST, L_s @classmethod def grad(cls, point1, point2): """Return the grad of two points, so for one-dimention Newton iteration.""" return (point2[1] - point1[1]) / (point2[0] - point1[0]) @classmethod def creat_test_data(cls, fileName='TestData.xlsx'): wb = Workbook() wb.create_sheet('result', index=0) sheet = wb[wb.sheetnames[0]] length = len(cls.values) sheet.append([ 'Information: ', 'r_range=linspace({0},{1},{2})'.format(cls.values[0][0], cls.values[length - 1][0], length), 'M_c={0}M_e'.format(cls.con.M_e), 'M_p={0}M_e'.format(cls.con.M_p), 'a={0}AU'.format(cls.con.a) ]) sheet.append(['r', 'P', 'T', 'M', 'G', 'DG', 'L']) for i in range(len(cls.values)): sheet.append(cls.values[i]) sheet.append(['dr', 'dP', 'dT', 'dM', 'dG', 'dDG', 'dL']) for i in range(len(cls.values)): sheet.append(cls.dValues[i]) wb.save(fileName) @classmethod def creat_t(cls, initValues, fileName='TestT.xlsx'): """The order of initValues is M_p, ST, L_s""" M_p, ST, L_s = initValues P = np.ones(len(M_p)) T = np.ones(len(M_p)) L = np.ones(len(M_p)) for order in range(len(M_p)): cls.con.set_M_p(M_p[order]) ST[order] = cls.find_ML_simple(0.0, [ST[order], L_s[order]], 1e-7, 1e-3)[0] print("Finished: {0}/200".format(order)) P[order] = cls.P[-1] T[order] = cls.T[-1] L[order] = cls.L[0] cls.ST = ST cls.t = np.ones(len(M_p)) n_0 = cls.con.R / cls.con.mu C_p = 5. / 2. cls.t[0] = 0.0 for i in range(len(M_p) - 1): T_1, T_2 = cls.T[i], cls.T[i + 1] P_1, P_2 = cls.P[i], cls.P[i + 1] ST_1, ST_2 = cls.ST[i], cls.ST[i + 1] delta_1 = C_p * (1 / T_2 + 1 / T_1) * (T_2 - T_1) delta_2 = (1 / P_2 + 1 / P_1) * (P_2 - P_1) dt = n_0 * (delta_1 + delta_2) / ((ST_1 + ST_2) * cls.con.Myr) cls.t[i + 1] = cls.t[i] + dt wb = Workbook() wb.create_sheet('result', index=0) sheet = wb[wb.sheetnames[0]] length = len(M_p) sheet.append([ 'Information: ', 'range=linspace({0},{1},{2})'.format(M_p[0], M_p[length - 1], length), 'M_c={0}M_e'.format(cls.con.M_e), 'a={0}AU'.format(cls.con.a) ]) sheet.append(['M_p/M_e', 'ST', 'L/e+24erg/s', 't/Myr']) for i in range(len(M_p)): sheet.append([M_p[i], cls.ST[i], cls.L[i], cls.t[i]]) wb.save(fileName)
class Methods(object): con = Const( ) #If the Const you need is not initial, you need to change it. P = [] T = [] M = [] L = [] g = [] dg = [] r = [] L_store = 0 test_sigma = [] test_values = [] RCB_index = 0 f = None f_judge = False @classmethod def ode_fun(cls, Z, r, c_P, c_T, c_M, others, ST): P, T, M, L = Z g, alpha, beta = others dP = c_P * M * P / (T * r**2) dT = min(c_T * 1e24 * abs(L) * P**(alpha + 1) * T**(beta - 4) / M, g) * (T * dP / P) dM = c_M * r**2 * P / T if dT == g * (T * dP / P): dL = 1e-24 * cls.con.M_e * cls.con.T_0 * dM * ST else: dL = 0 return [dP, dT, dM, dL] @classmethod def ode_fun_B(cls, Z, r, c_P, c_T, c_M, others, ST): P, T, M, G, DG, L = Z #if L<-1000: #raise LOutOfRangeError('L<-1000') g, alpha, beta, Lambda, R_B = others dP = c_P * M * P / (T * r**2) dT = min(c_T * 1e24 * abs(L) * P**(alpha + 1) * T**(beta - 4) / M, g) * (T * dP / P) dM = c_M * r**2 * P / T dG = DG control = (cls.con.sigma_2 / T**2) * dT ddG = 6 * G / r**2 + ( (-0.5 * dP / P) + (0.75 / T + cls.con.sigma_2 / T**2 * (abs(control) < 10)) * dT) * dG - (r > cls.con.depth) * 2 * cls.con.M_v * ( 1 / r - cls.con.depth**2 / r**3) / cls.con.c**2 / cls.con.R_B #ddG=6*G/r**2-1/r*dG dL = Lambda * 7.15e-5 * (dG**2 + G**2 / r**2) / (cls.sigma(P, T) * R_B) if dT == g * (T * dP / P): dL += 1e-24 * cls.con.M_e * cls.con.T_0 * dM * ST else: dL += 0 return [dP, dT, dM, dG, ddG, dL] @classmethod def find_RCB_index(cls): P, T, M, L = cls.P, cls.T, cls.M, cls.L judge = (cls.con.c_T * 1e24 * abs(L) * P**(cls.con.alpha + 1) * T**(cls.con.beta - 4) / M) < (np.ones(len(L)) * cls.con.g_ad) for i in range(len(cls.r)): if judge[i] != judge[0]: cls.RCB_index = i return i return 0 @classmethod def cal_ML_simple(cls, ST, L_s): c_P, c_T, c_M = cls.con.cal_const() g, alpha, beta = cls.con.g_ad, cls.con.alpha, cls.con.beta R_in, R_out = cls.con.R_p, cls.con.R_out num = 5000 r = np.linspace(1, R_in / R_out, num) initial = (1., 1., cls.con.M_p, L_s) others = (g, alpha, beta) result = odeint(cls.ode_fun, initial, r, args=(c_P, c_T, c_M, others, ST)) P, T, M, L = result[:, 0], result[:, 1], result[:, 2], result[:, 3] cls.P, cls.T, cls.M, cls.L = P, T, M, L cls.r = r cls.find_RCB_index() return M[-1], L[-1] @classmethod def cal_ML_simple_B(cls, ST, L_s, B=False, G=1e-12, dG=1e-15): c_P, c_T, c_M = cls.con.cal_const() g, alpha, beta = cls.con.g_ad, cls.con.alpha, cls.con.beta R_in, R_out = cls.con.R_p, cls.con.R_out num = 5000 r = np.linspace(1, R_in / R_out, num) cls.test_sigma = [] cls.test_values = [] if B: initial = (1., 1., cls.con.M_p, G, dG, L_s) else: initial = (1., 1., cls.con.M_p, 0.0, 0.0, L_s) others = (g, alpha, beta, cls.con.Lambda, cls.con.R_B) result = odeint(cls.ode_fun_B, initial, r, args=(c_P, c_T, c_M, others, ST)) P, T, M, G, dg, L = result[:, 0], result[:, 1], result[:, 2], result[:, 3], result[:, 4], result[:, 5] cls.P, cls.T, cls.M, cls.L = P, T, M, L cls.r, cls.g = r, G cls.dg = dg cls.find_RCB_index() return M[-1], L[-1], G[-1] @classmethod def sigma(cls, P, T): return cls.con.sigma_1 * T**(3. / 4) * P**(-1. / 2) * np.exp( -cls.con.sigma_2 / T) @classmethod def insert_value(cls): dP = cls.con.c_P * cls.M * cls.P / (cls.T * cls.r**2) nabla = np.ones(len(dP)) for i in range(len(nabla)): nabla[i] = min( cls.con.c_T * 1e24 * abs(cls.L[i]) * cls.P[i]**2 * cls.T[i]**-3 / cls.M[i], cls.con.g_ad) dT = nabla * cls.T / cls.P * dP y = (-0.5 * dP / cls.P) + (0.75 / cls.T + cls.con.sigma_2 / cls.T**2) * dT cls.f = interpolate.interp1d(cls.r, y, kind='cubic') cls.f_judge = True @classmethod def cal_L_safe(cls, ST, L_s): try: L = cls.cal_ML_simple(ST, L_s)[1] except LOutOfRangeError: ST = cls.find_safe_point(ST, L_s) L = cls.cal_ML_simple(ST, L_s)[1] finally: return ST, L @classmethod def grad(cls, point1, point2): """Return the grad of two points, so for one-dimention Newton iteration.""" return (point2[1] - point1[1]) / (point2[0] - point1[0]) @classmethod def find_L_M(cls, targets, inits, steps, errors): """The order of targets is [M_c, L_c], of inits is [ST, L_s](Note that the unit of L_s is 1e+24 erg/s), of steps and error is the same as inits and targets.""" """The way to find the result is one-dimention Newton iteration. First adjustion is L_s and then is ST.""" ST, L_s = inits M_c_need, L_c_need = targets error_M_c, error_L_c = errors M_c, L_c = cls.cal_ML_simple(ST, L_s) while abs(M_c - M_c_need) > error_M_c or abs(L_c - L_c_need) > error_L_c: while abs(M_c - M_c_need) > error_M_c: cls.error_judge = False point1 = (L_s, M_c) point2 = (L_s + L_s * steps[1], cls.cal_ML_simple(ST, L_s + L_s * steps[1])[0]) k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError( 'k is zero.Error is M_c,M_p is {0}'.format( cls.con.M_p)) else: L_s = (M_c_need - M_c) / k + L_s if L_s < 0: L_s = -L_s / 10 M_c, L_c = cls.cal_ML_simple(ST, L_s) while abs(L_c_need - L_c) > error_L_c: ST_next = ST + steps[0] L_c_next = cls.cal_ML_simple(ST_next, L_s)[1] point1 = [ST, L_c] point2 = [ST_next, L_c_next] k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError( 'k is zero.Error is L_c. M_p is {0}'.format( cls.con.M_p)) else: ST = (L_c_need - L_c) / k + ST ST, L_c = cls.cal_L_safe(ST, L_s) return [[ST, L_s], [M_c, L_c]] @classmethod def find_L_simple(cls, targets, inits, steps, errors): """The order of targets is [M_c, L_c], of inits is [ST, L_s](Note that the unit of L_s is 1e+24 erg/s), of steps and error is the same as inits and targets.""" """The way to find the result is one-dimention Newton iteration. First adjustion is L_s and then is ST.""" ST, L_s = inits L_c_need = targets error_L_c = errors L_c = cls.cal_ML_simple_B(ST, L_s, True, 0.0, -1)[1] while abs(L_c_need - L_c) > error_L_c: ST_next = ST + steps L_c_next = cls.cal_ML_simple_B(ST_next, L_s, True, 0.0, -1)[1] point1 = [ST, L_c] point2 = [ST_next, L_c_next] k = cls.grad(point1, point2) if k == 0: raise ZeroDivisionError( 'k is zero.Error is L_c. M_p is {0}'.format(cls.con.M_p)) else: ST = (L_c_need - L_c) / k + ST L_c = cls.cal_ML_simple_B(ST, L_s, True, 0.0, -1)[1] return ST, L_c @classmethod def change_const(cls, new_const): cls.con = new_const @classmethod def find_safe_point(cls, ST_init, L_s): L = L_s ST = ST_init if ST < 0: ST = -ST while True: try: cls.cal_ML_simple(ST, L) except LOutOfRangeError: ST /= 10 else: break return ST
def __init__(self): self.con = Const()
from const import Const from arithmetic_operations import Add, Sub, Mul, Div from variable import Variable from if_cond import IfCond from loop import Loop from program import Program expr = Sub(Add(Const(-2), Const(10)), (Div(Mul(Const(20), Const(3)), Const(5)))) print(str(expr) + " = " + str(expr.calculate())) varX = Variable("x") varX.setValue(Mul(Const(2), Const(5))) varY = Variable("y") varY.setValue(Const(3)) expr2 = Sub(Add(Const(1), varY), varX) #-6 print(str(expr2) + " = " + str(expr2.calculate())) expr3 = IfCond( IfCond(expr2, Const(0), Const(1)), Sub(expr2, Const(10)), #-16 Add(expr2, Const(10))) #4 print(str(expr3) + " = " + str(expr3.execute())) #expr4 = varX.setValue(Sub(varX, Const(1))) #print(str(expr4) + " = " + str(varX.getValue()))