Exemple #1
0
    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 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 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_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()
Exemple #6
0
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
Exemple #7
0
    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
Exemple #8
0
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
        }
Exemple #9
0
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
class WolframSampler:
    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 randomlySample(self,
                       reagentVectors,
                       oldReagents=None,
                       nExpt=96,
                       maxMolarity=9.,
                       finalVolume=500.):
        """Randomly sample possible experiments in the convex hull of concentration space defined by the reagentVectors

        Runs Josh's Mathematica function called `generateExperiments` defined in `randomSampling.wls`
        Shadows default arguments set at Wolfram level.
        Currently does not expose processVaules argument.

        :param reagentVectors: a dictionary of vector representations of reagents living in species-concentration space
        :param nExpt: the number of samples to draw
        :param maxMolarity: the maximum concentration of any species: defines a hypercube bounding the convex hull
        :param finalVolume: a scalar to act on the concentrations to convert to desired volume
        :return: a dictionary mapping: {reagents => list(volumes)} where list(volumes) has length nExpt
        :raises TypeError: since Mathematica will fail silently on incorrect types
        """
        ## Easy mathematica debugging (get an error, uncomment here for vectors)
        #print("new", reagentVectors, '\n')
        #print('to be removed', oldReagents, '\n')
        if not isinstance(reagentVectors, dict):
            raise TypeError('reagentVectors must be dict, got {}'.format(
                type(reagentVectors)))
        if not isinstance(nExpt, int):
            raise TypeError('nExpt must be int, got {}'.format(type(nExpt)))
        if not isinstance(maxMolarity, float):
            raise TypeError('maxMolarity must be float, got {}'.format(
                type(maxMolarity)))
        if not isinstance(finalVolume, float):
            raise TypeError('finalVolume must be float, got {}'.format(
                type(finalVolume)))
        if oldReagents:
            if not isinstance(oldReagents, dict):
                raise TypeError('oldReagents must be dict, got {}'.format(
                    type(oldReagents)))
        if oldReagents:
            result = self._randomlySample(reagentVectors, oldReagents, nExpt,
                                          maxMolarity, finalVolume)
            #            result = self._randomlySample(oldReagents, reagentVectors, nExpt, maxMolarity, finalVolume)
            if "Volume of remaining space is zero" in result:
                raise ValueError(
                    'New reagents define a convex hull that is covered by that of old reagents.'
                )
        else:
            result = self._randomlySample(reagentVectors, nExpt, maxMolarity,
                                          finalVolume)

        return result

    def enumerativelySample(self,
                            reagentVectors,
                            uniqueChemNames,
                            deltaV=10.,
                            maxMolarity=9.,
                            finalVolume=500.):
        """Enumeratively sample possible experiments in the convex hull of concentration space defined by the reagentVectors

        Runs Josh's Mathematica function called `achievableGrid` defined in `enumerativeSampling.wls`
        Shadows default arguments set at Wolfram level.

        :param reagentVectors: a dictionary of vector representations of reagents living in species-concentration space
        :param uniqueChemNames: list of chemicals making up the reagents
        :param maxMolarity: the maximum concentration of any species: defines a hypercube bounding the convex hull
        :param deltaV: the spacing of reagent volumes that define the spacing of the grid in concentration space
        :param finalVolume: a scalar to act on the concentration points to convert to desired volume
        :return:  a dictionary mapping: {reagents => list(volumes)}
        :raises TypeError: since Mathematica will fail silently on incorrect types
        """

        if not isinstance(reagentVectors, dict):
            raise TypeError('reagentVectors must be dict, got {}'.format(
                type(reagentVectors)))
        if not isinstance(uniqueChemNames, list):
            raise TypeError('uniqueChemNames must be a list, got {}'.format(
                type(uniqueChemNames)))
        if not isinstance(maxMolarity, float):
            raise TypeError('maxMolarity must be float, got {}'.format(
                type(maxMolarity)))
        if not isinstance(deltaV, float):
            raise TypeError('deltaV must be float, got {}'.format(
                type(deltaV)))
        if not isinstance(finalVolume, float):
            raise TypeError('finalVolume must be float, got {}'.format(
                type(finalVolume)))

        return self._enumerativelySample(reagentVectors, uniqueChemNames,
                                         deltaV, maxMolarity, finalVolume)

    def terminate(self):
        """Kill the session thread"""
        self.session.terminate()
Exemple #11
0
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"]'))
Exemple #12
0
			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.")

Exemple #13
0
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
DATABASE_FILE = "travelogues.sqlite3"

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
session = WolframLanguageSession(WOLFRAM_KERNEL_LOCATION)

connection = sqlite3.connect(DATABASE_FILE)
db = connection.cursor()

db.execute("SELECT id, name, gender FROM travelers")
travelers = db.fetchall()

for traveler in travelers:
    if traveler[2] == None:  #traveler[2] is gender
        name = traveler[1]
        traveler_id = traveler[0]
        # The following evaluates
        # Classify["NameGender", First[TextCases[name, "GivenName"]]]
        # in Wolfram Kernel
        gender = session.evaluate(
            wl.System.Classify(
                "NameGender",
                wl.System.First(wl.System.TextCases(name, "GivenName"))))
        if type(gender) is str and gender != "Indeterminate":
            db.execute(
                """UPDATE travelers
                        SET gender = ?
                        WHERE id = ?""", (gender, traveler_id))

connection.commit()
session.stop()
Exemple #15
0
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)
Exemple #16
0
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl, wlexpr
session = WolframLanguageSession()
print(session.evaluate(wlexpr('Select[Range[5],PrimeQ]')))
Exemple #17
0
from wolframclient.language import wl
from wolframclient.evaluation import WolframLanguageSession

session = WolframLanguageSession()
session.evaluate(wl.StringReverse('abc'))  # StringReverse["abc"]
session.evaluate(wl.MinMax([1, 5, -3, 9])  # MinMax[{1, 5, -3, 9}]
Exemple #18
0
from wolframclient.evaluation import WolframLanguageSession
import logging

# set the root level to INFO
logging.basicConfig(level=logging.INFO)

try:
    session = WolframLanguageSession()
    # this will trigger some log messages with the process ID, the sockets
    # address and the startup timer.
    session.start()
    # Warning: Infinite expression Power[0, -1] encountered.
    res = session.evaluate('1/0')
finally:
    session.terminate()
class engineClass:
    '''
    '''
    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 _getRequiredAttributes(self,
                               paramsDict,
                               threadNumber="0",
                               runDict={},
                               pointKey=''):
        '''
        '''
        phaseSpacePoint = {}
        phaseSpacePoint[pointKey] = runDict
        phaseSpacePoint[pointKey].update(paramsDict)

        return phaseSpacePoint

    def _clean(self, threadNumber):
        '''
        '''
        return None

    def _check0Mass(self, phaseSpaceDict):
        '''
        '''
        pointID = list(phaseSpaceDict.keys())[0]
        validPoint = True

        if (bool(phaseSpaceDict[pointID]) is True):
            if phaseSpaceDict[pointID]['Triviality'] is 0:
                validPoint = True
            else:
                validPoint = False
        else:
            validPoint = False

        return validPoint

    def runPoint(self, paramsDict, threadNumber='0', debug=False):
        '''
        '''
        # Set up logging utility
        logFileName = 'SO11_Analysis-' + threadNumber + '.log'
        logging.basicConfig(level=logging.INFO, filename=logFileName)

        # Export the data rules to the Mathematica association filetype
        paramsDict_wl = export(paramsDict, pandas_dataframe_head='association')
        dataRuleExpr = wlexpr(bytes('dataRule=', 'utf-8') + paramsDict_wl)

        resOut = {}
        try:

            #  Run the Mathematica Weinber Angle Code
            with open(self.mathScriptPath, 'r') as mathIn:
                strMath = mathIn.read()

            analysExpr = wlexpr(strMath)
            self.session.evaluate(dataRuleExpr)

            # print(paramsDict)
            timeConstrEval = wl.TimeConstrained(analysExpr, self.timeOut)
            resOut = self.session.evaluate(timeConstrEval)
            # resOut = self.session.evaluate(analysExpr)
            # resOut = wl.TimeConstrained(self.session.evaluate(analysExpr), 60)
            # print(resOut)
        except Exception as e:
            print(e)
            raise
            # print('-------')
            return {'Triviality': 1}

        # finally:
        # self.session.terminate()
        # print('Results for run: ', resOut)
        try:
            resStatus = resOut.name
        except Exception as e:
            resStatus = None

        if resStatus == '$Aborted' or bool(resOut) is False:
            return {'Triviality': 1}
        else:
            return resOut

    def _terminateSession(self):
        '''
            Terminates the current Wolfram session
        '''
        self.session.terminate()
        return None
"""
外环是逆时针,内环顺时针

"""
from wolframclient.evaluation import WolframLanguageSession  # MMA
from wolframclient.language import wl, wlexpr, Global  # MMA
session = WolframLanguageSession()
result = session.evaluate(wlexpr('Range[6]'))
print(result)