def _compute_eps(lam): session = WolframLanguageSession(wlpath) session.evaluate( wlexpr(''' randomgamma[alpha_, beta_, gamma_, samples_] := RandomVariate[GammaDistribution[alpha, beta, gamma, 0], samples]; ''')) random_gamma = session.function(wlexpr('randomgamma')) session.evaluate( wlexpr(''' integrant[exponents_, beta_, dimension_, clippingbound_, lam_, r_, q_] := Mean[NIntegrate[ (Sin[x]^(dimension-2)*Gamma[dimension/2]/(Sqrt[Pi]*Gamma[(dimension-1)/2]))*(((1-q)*(1-q+ q*Exp[(r^exponents-(r^2+clippingbound^2-2*r*clippingbound*Cos[x])^(exponents/2))/beta])^(lam)) +(q*(1-q+q*Exp[((r^2+clippingbound^2+2*r*clippingbound*Cos[x])^(exponents/2)-r^exponents)/beta])^(lam))),{x,0,Pi} ]]; ''')) integrant_moment = session.function(wlexpr('integrant')) samples = random_gamma(FLAGS.dimension / FLAGS.exponents, beta**(1 / FLAGS.exponents), FLAGS.exponents, FLAGS.num_samples) moment = integrant_moment(FLAGS.exponents, beta, FLAGS.dimension, FLAGS.clippingbound, lam, samples, FLAGS.q) eps = (FLAGS.T * mp.log(moment) + mp.log(1 / FLAGS.delta)) / lam session.terminate() return eps
def __init__(self): ''' ''' self.mathScriptPath = os.path.expanduser( '~') + '/Documents/Hosotani_SO11/Mathematica/SO11_Masses_v7.m' self.session = WolframLanguageSession() self.timeOut = 120 return None
def test_auto_start_session(self): try: session = WolframLanguageSession(self.KERNEL_PATH) res = session.evaluate('1+1') self.assertEqual(res, 2) except Exception as e: logger.exception(e) finally: session.terminate() self.assertTrue(session.stopped)
def test_auto_start_session(self): try: session = WolframLanguageSession(kernel_path) res = session.evaluate("1+1") self.assertEqual(res, 2) except Exception as e: logger.exception(e) finally: session.terminate() self.assertTrue(session.stopped)
def __init__(self): """A wrapper to generateExperiments.wls Written as a class so the Wolfram session is only once at __init__ time. """ self.session = WolframLanguageSession(kernel=wolfram_kernel_path) self.session.evaluate('<<./capture/generate/randomSampling.wls') self.session.evaluate('<<./capture/generate/enumerativeSampling.wls') self._randomlySample = self.session.function('generateExperiments') self._enumerativelySample = self.session.function( 'generateEnumerations')
def __init__(self): config = get_config() wolfram_path = config.get("DEFAULT", "WOLFRAM_PATH") self.image_path = os.path.join(os.getcwd(), 'static', 'city') atexit.register(self.cleanup) if wolfram_path is None or len(wolfram_path) == 0: self.session = WolframLanguageSession() print("Wolfram Engine session opened on default path.") else: self.session = WolframLanguageSession(wolfram_path) print(f"Wolfram Engine session opened on '{wolfram_path}'.") self._define_wolfram_functions()
def test_terminated_session_autorestart(self): session = None try: session = WolframLanguageSession(kernel_path) session.start() session.stop() res = session.evaluate("1+1") self.assertEqual(res, 2) finally: if session: session.terminate()
def test_terminated_session_autorestart(self): session = None try: session = WolframLanguageSession(self.KERNEL_PATH) session.start() session.stop() res = session.evaluate('1+1') self.assertEqual(res, 2) finally: if session: session.terminate()
def test_set_loglevel(self): with WolframLanguageSession(self.KERNEL_PATH, kernel_loglevel=logging.WARN) as session: res = session.evaluate( 'ClientLibrary`Private`$LogLevel == ClientLibrary`Private`$WARN' ) self.assertTrue(res)
class WOLFRAM: MADE = False def __init__(self): # err('dont use this for now') if self.MADE: raise Exception('just use one wl kernel') self.MADE = True # not working, need to debug atexit.register(self.terminate) self.session = None @log_invokation(timer=True) def _start_session(self, kwargs): self.session = WolframLanguageSession( kernel_loglevel=logging.DEBUG, # kernel_loglevel=logging.FATAL, **kwargs, ) def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): self.terminate() def terminate(self): if self.session is not None: self.session.terminate() @log_invokation(first_only=True, with_args=True) def eval(self, s): if self.session is None: kwargs = {} if ismac() else dict( kernel='/home/matt/WOLFRAM/Executables/WolframKernel') self._start_session(kwargs) ev = self.session.evaluate_wrap_future(wl.UsingFrontEnd(s)) ev = ev.result() if ev.messages is not None: for m in ev.messages: err(m) return ev.result def __getattr__(self, name): return weval(name)
def test_evaluate_multiple_async(self): with WolframLanguageSession(self.KERNEL_PATH) as kernel_session: future1 = kernel_session.evaluate_future('3+4') result1 = future1.result(timeout=3) self.assertEqual(result1, 7) future2 = kernel_session.evaluate_future('10+1') self.assertEqual(future2.result(timeout=1), 11) future3 = kernel_session.evaluate_future('100+1') self.assertEqual(future3.result(timeout=1), 101)
def test_evaluate_multiple_async(self): with WolframLanguageSession(kernel_path) as kernel_session: future1 = kernel_session.evaluate_future("3+4") result1 = future1.result(timeout=3) self.assertEqual(result1, 7) future2 = kernel_session.evaluate_future("10+1") self.assertEqual(future2.result(timeout=2), 11) future3 = kernel_session.evaluate_future("100+1") self.assertEqual(future3.result(timeout=2), 101)
def open_wolfram_language_session(WolframKernel_path, max_retry=5): for _ in range(max_retry): try: session = WolframLanguageSession(WolframKernel_path, stdout=sys.stdout) return session except Exception as e: print(f"- failed to check license ({e}), retrying", flush=True) time.sleep(1) return None
def solveFeasible(self,agentNum,u_N,UD): session=WolframLanguageSession() eps = 1/np.sqrt(agentNum)/agentNum/2.0 # N[FindInstance[x^2 - 3 y^2 == 1 && 10 < x < 100, {x, y}, Integers]] ans = [] result = [] while len(result) == 0: expr = "" # expr to evaluate for i in range(agentNum-1): expr = expr + "x" + str(i) + "> 0.05 &&" expr = expr + "x" + str(agentNum-1) + "> 0.05 &&" for i in range(agentNum): for j in range(i+1, agentNum): # abs(x_i - x_j) <= U_{i,j} expr = expr + "Abs[x" + str(i) + "-x" + str(j) + "-(" + str(UD[i,j]) + ")]<=" + str(eps) + "&&" for i in range(agentNum-1): expr = expr + "x" + str(i) + "+" expr = expr + "x" + str(agentNum-1) + "==" + str(u_N) + "&&" for i in range(agentNum-1): expr = expr + "x" + str(i) + "+" expr = expr + "x" + str(agentNum-1) + "<=" + str(u_N) expr = expr + ", {" for i in range(agentNum-1): expr = expr + "x" + str(i) + "," expr = expr + "x" + str(agentNum-1) + "}, Reals" expr = "N[FindInstance[" + expr + "]]" # print(expr) result = session.evaluate(wlexpr(expr)) session.terminate() # print(result) if len(result) > 0: ans = [result[0][i][1] for i in range(agentNum)] eps = eps * 1.1 print(eps) # for i in range(agentNum): # if ans[i] < 0.0000001: # ans[i] = ans[i] + 0.0000001 print(ans) return ans
def test_default_loglevel(self): with WolframLanguageSession(kernel_path) as session: res = session.evaluate("ClientLibrary`Private`$LogLevel == Infinity") self.assertTrue(res) # This is not possible. Logging was not enabled in the first place. session.evaluate("ClientLibrary`SetInfoLogLevel[]") # Log level remains to NOTSET res = session.evaluate( "ClientLibrary`Private`$LogLevel == ClientLibrary`Private`$NOTSET" ) logger.info("LOG LEVEL: %s", session.evaluate("ClientLibrary`Private`$LogLevel")) self.assertTrue(res)
def compute_dp(lam): session = WolframLanguageSession(wlpath) session.evaluate( wlexpr(''' randomgamma[alpha_, beta_, gamma_, samples_] := RandomVariate[GammaDistribution[alpha, beta, gamma, 0], samples]; ''')) random_gamma = session.function(wlexpr('randomgamma')) session.evaluate( wlexpr(''' integrant[p_, beta_, d_, Delta_, lam_, r_] := Mean[NIntegrate[ Sin[x]^(d-2)*Gamma[d/2]/(Sqrt[Pi]*Gamma[(d-1)/2])*(0.99+0.01*Exp[(r^p-(r^2+Delta^2+2*r*Delta*Cos[x])^(p/2))/beta])^(-lam),{x,0,Pi} ]]; ''')) integrant_moment = session.function(wlexpr('integrant')) samples = random_gamma(d / p, beta**(1 / p), p, num_samples) # print(samples) moment = integrant_moment(p, beta, d, Delta, lam, samples) # print(moment) eps = (T * mp.log(moment) + mp.log(1 / delta)) / lam session.terminate() return eps
def test_default_loglevel(self): with WolframLanguageSession(self.KERNEL_PATH) as session: res = session.evaluate( 'ClientLibrary`Private`$LogLevel == Infinity') self.assertTrue(res) # This is not possible. Logging was not enabled in the first place. session.evaluate('ClientLibrary`SetInfoLogLevel[]') # Log level remains to NOTSET res = session.evaluate( 'ClientLibrary`Private`$LogLevel == ClientLibrary`Private`$NOTSET' ) logger.info('LOG LEVEL: %s', session.evaluate('ClientLibrary`Private`$LogLevel')) self.assertTrue(res)
class SequenceTagger: def __init__(self, wl_kernel=None): """Initialize the SentenceTagger wl_kernel -- location of Wolfram kernel """ self.session = WolframLanguageSession() if wl_kernel == None else WolframLanguageSession(wl_kernel) def close(self): """Stop the Wolfram Kernel associated with this tagger""" self.session.stop() def predict(self, text: str, **kwargs) -> dict: """Get text entities in text text -- text to get entities from Keyword arguments: entity_types -- list of entity types to include """ forms = wl.System.Automatic if "entity_types" in kwargs: forms = wl.System.List(*kwargs["entity_types"]) expr = wl.System.TextContents(text, forms, wl.System.All) response = self.session.evaluate(expr) entities = [] for entity in response[0]: entities.append({ "text": entity["String"], "start_pos": entity["Position"][0] - 1, "end_pos": entity["Position"][1], "type": entity["Type"], "confidence": entity["Probability"], "interpretation": entity["Interpretation"] }) return { "text": text, "entities": entities }
def wolfram_stability(model, M): r"""Use the wolfram Noptimize to numerically compute if the given model is stable somewhere in the Kähler cone Parameters ---------- model : np.array[5, M.len] sum of line bundles M : pyCICY.CICY CICY object Returns ------- bool True if stable else False """ session = WolframLanguageSession()#kernel_loglevel=logging.ERROR line_slope = [] for line in model: tmp = M.line_slope() for i in range(M.len): tmp = tmp.subs({'m'+str(i): line[i]}) line_slope += [tmp] str_slope = str(line_slope).replace('**', '^').replace('[','{').replace(']', '}') str_cone = str(['t'+str(i)+'> 1' for i in range(M.len)]).replace('\'', '').replace('[','{').replace(']', '}') str_vars = str(['t'+str(i) for i in range(M.len)]).replace('\'', '').replace('[','{').replace(']', '}') success = False full_string = 'NMinimize[Join[{{Plus @@ (#^2 & /@ {})}}, '.format(str_slope) full_string += '{}],'.format(str_cone) full_string += '{}, AccuracyGoal -> 20, PrecisionGoal -> 20, WorkingPrecision -> 20]'.format(str_vars) optimize = wlexpr(full_string) results = session.evaluate(optimize) if np.allclose([0.], [results[0].__float__()], atol=0.01): success = True session.terminate() return success
import random from itertools import product, combinations from copy import copy from wolframclient.evaluation import WolframLanguageSession from wolframclient.language import wl, wlexpr session = WolframLanguageSession() arrays = [] comb_behavior = {} def pareto_dominates(new_val, old_val): failed = False reallyGained = False for player in range(players): if new_val[player] < old_val[player]: failed = True elif new_val[player] > old_val[player]: reallyGained = True return reallyGained and not failed def generate_valuation(base): variable_string = "{" variables = [] constraint_string = "" constraints = []
from wolframclient.evaluation import WolframLanguageSession from wolframclient.language import wl from statistics import mean session = WolframLanguageSession() sample = session.evaluate(wl.RandomVariate(wl.NormalDistribution(0, 1), 1e6)) print(sample[:5]) session.evaluate(wl.Mean(sample)) mean(sample)
from wolframclient.evaluation import WolframLanguageSession from pickle_jar import savePickles, loadPickles, file_open from wolframclient.language import wl, wlexpr session = WolframLanguageSession() #Entity["Species", "Species:CorvusCorax"]["Dataset"] # animal_list = file_open('../constants/animals.txt') #for animal in animal_list: #print(session.evaluate(f'Interpreter["Species"][{animal}]["Image"]')) #print(session.evaluate(f'Interpreter["Species", "raven"]["MaximumLifeSpan"]')) print( session.evaluate( f'Interpreter["Species", "Species:CorvusCorax"]["MaximumLifeSpan"]'))
if self.imageQuestion == True: self.ui.verticalLayout.removeWidget(self.label1) self.label1.deleteLater() self.label1 = None self.newQuestion() if __name__ == '__main__': session = WolframLanguageSession() commands = [ '''Get["definitions.mx"];''', '''questionRepo=Quiet@Import["repo.mx"];''' ] for i in commands: session.evaluate(wlexpr(i)) app = QtWidgets.QApplication([]) application = mywindow() application.show() try: sys.exit(app.exec()) except SystemExit: session.terminate() print("Wolfram Link has been terminated.")
from time import perf_counter from wolframclient.evaluation import WolframLanguageSession with WolframLanguageSession() as session: start = perf_counter() print('Starting an evaluation delayed by 2 seconds.') future = session.evaluate_future('Pause[2]; 1+1') print( 'After %.04fs, the code is running in the background, Python execution continues.' % (perf_counter() - start)) # wait for up to 5 seconds. expr = future.result(timeout=5) print( 'After %.02fs, result was available. Kernel evaluation returned: %s' % (perf_counter() - start, expr))
class Engine: def __init__(self): config = get_config() wolfram_path = config.get("DEFAULT", "WOLFRAM_PATH") self.image_path = os.path.join(os.getcwd(), 'static', 'city') atexit.register(self.cleanup) if wolfram_path is None or len(wolfram_path) == 0: self.session = WolframLanguageSession() print("Wolfram Engine session opened on default path.") else: self.session = WolframLanguageSession(wolfram_path) print(f"Wolfram Engine session opened on '{wolfram_path}'.") self._define_wolfram_functions() def _define_wolfram_functions(self): self.get_weather = self.session.function(wlexpr('<|"Temperature" -> WeatherData[#, "Temperature"], "WindSpeed" ->WeatherData[#, "WindSpeed"],"Pressure"-> WeatherData[#,"Pressure"]|>&')) self.get_city = self.session.function(wlexpr('Module[{cities}, cities = TextCases[#, "City"];If[Length[cities] > 0, First[cities], ""]]&')) def test(self): self.check_session() return self.session.evaluate(wlexpr('NIntegrate[Sin[Sin[x]], {x, 0, 2}]')) def get_city_image(self, name): # search existing images if present lname = str.lower(name) for file in os.listdir(self.image_path): if file.endswith(".png"): if file == f"{lname}.png": print(f"Found image for '{name}' in cache.") return # get the image via websearch graphic = self.session.evaluate(wlexpr(f'WebImageSearch["{name}", "Images", MaxItems -> 1][[1]]')) path = os.path.join(self.image_path, f"{lname}.png") png_export = wl.Export(path, graphic, "PNG") return self.session.evaluate(png_export) def get_weather_info(self, text) -> dict: """ Returns a dictionary with some weather info for the first city found in the given (natural language) text. :param text: any text """ self.check_session() if text is None or len(text) == 0: return {} city = self.get_city(text) if city is None or len(city) == 0: return {} print(f"Found city: {city}") found = self.get_weather(city) if isinstance(found, dict) and found["Temperature"].args[0] != "NotAvailable": self.get_city_image(city) return { "Input": text, "City": city, "Temperature": found["Temperature"].args[0], "WindSpeed": found["WindSpeed"].args[0], "Pressure": found["Pressure"].args[0], "Info": self.session.evaluate(wlexpr(f'TextSentences[WikipediaData["{city}"]][[;; 5]]'))[0] } else: return {} def check_session(self): if self.session is None: raise Exception("The Engine is not present.") # noinspection PyBroadException def cleanup(self): """ Note that there is no way to catch the SIGKILL and stop the engine gracefully if this happens. :return: """ try: if self.session is not None: self.session.stop() print("Wolfram Engine stopped.") except Exception: pass
args = parser.parse_args() # check whether an xlsx file was provided and open it (or a new one) if args.x: file = args.x wb = load_workbook(file) else: file = '../output/values.xlsx' wb = load_workbook(file) # create new sheet for this round ws = wb.create_sheet('beta_b{}s{}{}'.format(args.a, args.s, 'm' if args.m else '')) # access the specified kernel with WolframLanguageSession(KERNEL_PATH) as session: # check whether to include xm if args.m: session.evaluate(wlexpr('a = {};'.format(args.a))) session.evaluate(wlexpr('cantor[0] = {0, 1};')) session.evaluate( wlexpr( 'cantor[n_] := Join[cantor[n - 1] / a, (a - 1 + cantor[n - 1]) / a];' )) session.evaluate(wlexpr('s = {};'.format(args.s))) session.evaluate(wlexpr('set = cantor[s - 1]')) set = session.evaluate(wlexpr('N[set]')) session.evaluate(wlexpr('next = cantor[s];')) next = session.evaluate(wlexpr('N[next]'))
from wolframclient.evaluation import WolframLanguageSession from wolframclient.language import wl, wlexpr session = WolframLanguageSession() print(session.evaluate(wlexpr('Select[Range[5],PrimeQ]')))
def test_stop_start_restart_status(self): session = WolframLanguageSession(kernel_path) self.assertFalse(session.started) self.assertTrue(session.stopped) session.start() self.assertTrue(session.started) self.assertFalse(session.stopped) session.stop() self.assertFalse(session.started) self.assertTrue(session.stopped) session.restart() self.assertTrue(session.started) self.assertFalse(session.stopped) session.terminate() self.assertFalse(session.started) self.assertTrue(session.stopped) session = WolframLanguageSession(kernel_path) session.stop() self.assertFalse(session.started) self.assertTrue(session.stopped) session.terminate() self.assertFalse(session.started) self.assertTrue(session.stopped)
def test_kernel_init_bad_path(self): with self.assertRaises(WolframKernelException): WolframLanguageSession("path/that/does/not/exists")
def setupKernelSession(cls): cls.kernel_session = WolframLanguageSession(kernel_path, kernel_loglevel=logging.INFO) cls.kernel_session.set_parameter("STARTUP_TIMEOUT", 5) cls.kernel_session.set_parameter("TERMINATE_TIMEOUT", 3) cls.kernel_session.start()