Пример #1
0
    def apply_list(self, zmin, zmax, ns, evaluation):
        'RandomComplex[{zmin_, zmax_}, ns_]'
        expr = Expression('RandomComplex', Expression('List', zmin, zmax), ns)

        min_value, max_value = self.to_complex(zmin,
                                               evaluation), self.to_complex(
                                                   zmax, evaluation)
        if min_value is None or max_value is None:
            return evaluation.message('RandomComplex', 'unifr',
                                      Expression('List', zmin, zmax))

        py_ns = ns.to_python()
        if not isinstance(py_ns, list):
            py_ns = [py_ns]

        if not all([isinstance(i, int) and i >= 0 for i in py_ns]):
            return evaluation.message('RandomComplex', 'array', ns, expr)

        with RandomEnv(evaluation) as rand:
            real = rand.randreal(min_value.real, max_value.real, py_ns)
            imag = rand.randreal(min_value.imag, max_value.imag, py_ns)
            return instantiate_elements(
                stack(real, imag),
                lambda c: Complex(Real(c[0]), Real(c[1])),
                d=2)
Пример #2
0
 def apply_for_color(self, color, evaluation):
     "ColorNegate[color_RGBColor]"
     # Get components
     r, g, b = [leaf.to_python() for leaf in color.leaves]
     # Invert
     r, g, b = (1.0 - r, 1.0 - g, 1.0 - b)
     # Reconstitute
     return Expression("RGBColor", Real(r), Real(g), Real(b))
Пример #3
0
    def apply(self, z, evaluation):
        "Precision[z_]"

        if not z.is_inexact():
            return Symbol("Infinity")
        elif z.to_sympy().is_zero:
            return Real(0)
        else:
            return Real(dps(z.get_precision()))
Пример #4
0
    def testReal(self):
        self.check('1.5', Real('1.5'))
        self.check('1.5`', Real('1.5'))
        self.check('0.0', Real(0))
        self.check('-1.5`', Real('-1.5'))

        self.check('0.00000000000000000', '0.')
        self.check('0.000000000000000000`', '0.')
        self.check('0.000000000000000000', '0.``18')
Пример #5
0
    def testReal(self):
        self.check("1.5", Real("1.5"))
        self.check("1.5`", Real("1.5"))
        self.check("0.0", Real(0))
        self.check("-1.5`", Real("-1.5"))

        self.check("0.00000000000000000", "0.")
        self.check("0.000000000000000000`", "0.")
        self.check("0.000000000000000000", "0.``18")
Пример #6
0
 def eval_f(x_value, y_value):
     value = stored.get((x_value, y_value), False)
     if value == False:
         value = quiet_evaluate(f, {x: Real(x_value), y: Real(y_value)}, evaluation)
         #value = dynamic_scoping(f.evaluate, {x: Real(x_value), y: Real(y_value)}, evaluation)
         #value = chop(value).get_real_value()
         if value is not None:
             value = float(value)
         stored[(x_value, y_value)] = value
     return value
Пример #7
0
 def testReal(self):
     _test_group(
         MachineReal(1.17361),
         MachineReal(-1.42),
         MachineReal(42.846195714),
         MachineReal(42.846195714),
         MachineReal(42.846195713),
         Real("42.846195713", 18),
         Real("-1.42", 3),
     )
Пример #8
0
    def apply(self, zmin, zmax, evaluation):
        'RandomComplex[{zmin_, zmax_}]'

        min_value, max_value = self.to_complex(zmin, evaluation), self.to_complex(zmax, evaluation)
        if min_value is None or max_value is None:
            return evaluation.message('RandomComplex', 'unifr', Expression('List', zmin, zmax))

        with RandomEnv(evaluation) as rand:
            real = Real(rand.randreal(min_value.real, max_value.real))
            imag = Real(rand.randreal(min_value.imag, max_value.imag))
            return Complex(real, imag)
Пример #9
0
 def compute(a, b):
     return Expression(
         "Apply",
         distance_function,
         Expression(
             "List",
             Expression(
                 "List",
                 *[Real(val) for val in a.to_color_space("LAB")]),
             Expression(
                 "List",
                 *[Real(val) for val in b.to_color_space("LAB")]),
         ),
     )
Пример #10
0
    def apply(self, zmin, zmax, evaluation):
        "RandomComplex[{zmin_, zmax_}]"

        min_value, max_value = (
            self.to_complex(zmin, evaluation),
            self.to_complex(zmax, evaluation),
        )
        if min_value is None or max_value is None:
            return evaluation.message("RandomComplex", "unifr",
                                      Expression("List", zmin, zmax))

        with RandomEnv(evaluation) as rand:
            real = Real(rand.randreal(min_value.real, max_value.real))
            imag = Real(rand.randreal(min_value.imag, max_value.imag))
            return Complex(real, imag)
Пример #11
0
 def apply(self, text1, text2, evaluation, options):
     'WordSimilarity[text1_String, text2_String, OptionsPattern[%(name)s]]'
     doc1 = self._nlp(text1.get_string_value(), evaluation, options)
     if doc1:
         doc2 = self._nlp(text2.get_string_value(), evaluation, options)
         if doc2:
             return Real(doc1.similarity(doc2))
Пример #12
0
    def apply(self, expr, evaluation):
        "AbsoluteTiming[expr_]"

        start = time.time()
        result = expr.evaluate(evaluation)
        stop = time.time()
        return Expression("List", Real(stop - start), result)
Пример #13
0
    def apply_complex(self, x, evaluation):
        'Precision[x_Complex]'

        if x.is_inexact():
            return Real(dps(x.get_precision()))
        else:
            return Symbol('Infinity')
Пример #14
0
    def apply(self, expr, evaluation):
        'Timing[expr_]'

        start = time.clock()
        result = expr.evaluate(evaluation)
        stop = time.clock()
        return Expression('List', Real(stop - start), result)
Пример #15
0
 def eval_f(self, f, x_name, x_value, evaluation):
     value = quiet_evaluate(f, {x_name: Real(x_value)},
                            evaluation,
                            expect_list=True)
     if value is None or len(value) != 2:
         return None
     return value
Пример #16
0
 def apply_N(self, prec, evaluation):
     'N[E, prec_]'
     
     prec = get_precision(prec, evaluation)
     if prec is not None:
         with workprec(prec):
             return Real(mpmath2gmpy(mpmath.e))
Пример #17
0
    def apply_any(self, args, evaluation, options):
        "DateObject[args_, OptionsPattern[]]"
        datelist = None
        tz = None
        if isinstance(args, Expression):
            if args.get_head_name() in ("System`Rule", "System`DelayedRule"):
                options[args.leaves[0].get_name()] = args.leaves[1]
                args = Expression("AbsoluteTime").evaluate(evaluation)
            elif args.get_head_name() == "System`DateObject":
                datelist = args._leaves[0]
                tz = args._leaves[3]

        if datelist is None:
            datelist = self.to_datelist(args, evaluation)
            tz = Real(-time.timezone / 3600.0)
        if datelist is None:
            return

        fmt = None

        if options["System`TimeZone"].sameQ(Symbol("Automatic")):
            timezone = Real(-time.timezone / 3600.0)
        else:
            timezone = options["System`TimeZone"].evaluate(evaluation)
            if not timezone.is_numeric(evaluation):
                evaluation.message("DateObject", "notz", timezone)

        # TODO: if tz != timezone, shift the datetime list.
        if not tz == timezone:
            dt = timezone.to_python() - tz.to_python()
            if len(datelist) > 3:
                newhour = datelist[3] + dt
                datelist = datelist[:3] + [newhour] + datelist[4:]

        epoch = Symbol("Eternity")
        if datelist[-1] == 0:
            for i in range(len(datelist)):
                if datelist[-1 - i] != 0:
                    datelist = datelist[:-i]
                    epoch = self.granularities[-i - 1]
                    break
        else:
            epoch = Symbol("Instant")

        fmt = options["System`DateFormat"]
        if len(datelist) < 6:
            datelist = [Integer(d) for d in datelist]
        else:
            datelist = [Integer(d) for d in datelist[:5]] + [Real(datelist[5])]
        return Expression(
            "DateObject",
            datelist,
            epoch,
            Symbol("Gregorian"),
            timezone,
            fmt,
        )
Пример #18
0
 def search_product(i):
     if i == len(result) - 1:
             return Expression('List', *[
                 Real(rand.randreal(min_value, max_value))
                 for j in range(result[i])])
     else:
         return Expression('List', *[
             search_product(i + 1) for j in range(result[i])])
Пример #19
0
 def apply(self, word, evaluation, options):
     'WordFrequencyData[word_String,  OptionsPattern[%(name)s]]'
     doc = self._nlp(word.get_string_value(), evaluation, options)
     frequency = 0.
     if doc:
         if len(doc) == 1:
             frequency = math.exp(doc[0].prob)  # convert log probability
     return Real(frequency)
Пример #20
0
 def testAcrossTypes(self):
     _test_group(
         Integer(1),
         Rational(1, 1),
         Real(1),
         Complex(Integer(1), Integer(1)),
         String("1"),
         Symbol("1"),
     )
Пример #21
0
 def apply(self, evaluation):
     "TimeRemaining[]"
     if len(evaluation.timeout_queue) > 0:
         t, start_time = evaluation.timeout_queue[-1]
         curr_time = datetime.now().timestamp()
         deltat = t + start_time - curr_time
         return Real(deltat)
     else:
         return SymbolInfinity
Пример #22
0
    def apply(self, min, max, evaluation):
        'RandomReal[{min_, max_}]'

        min_value = min.get_real_value()
        max_value = max.get_real_value()
        if min_value is None or max_value is None:
            return evaluation.message('RandomReal', 'unifr',
                                      Expression('List', min, max))
        with RandomEnv(evaluation) as rand:
            return Real(rand.randreal(min_value, max_value))
Пример #23
0
        def get_magnitude(leaves, targetUnit, evaluation):
            quanity = Q_(leaves[0], leaves[1].get_string_value())
            converted_quantity = quanity.to(targetUnit)
            q_mag = converted_quantity.magnitude.evaluate(
                evaluation).get_float_value()

            # Displaying the magnitude in Integer form if the convert rate is an Integer
            if q_mag - int(q_mag) > 0:
                return Real(q_mag)
            else:
                return Integer(q_mag)
Пример #24
0
    def apply(self, xmin, xmax, evaluation):
        'RandomReal[{xmin_, xmax_}]'

        if not (isinstance(xmin, (Real, Integer))
                and isinstance(xmax, (Real, Integer))):
            return evaluation.message('RandomReal', 'unifr',
                                      Expression('List', xmin, xmax))

        min_value, max_value = xmin.to_python(), xmax.to_python()

        with RandomEnv(evaluation) as rand:
            return Real(rand.randreal(min_value, max_value))
Пример #25
0
 def eval_color(x, y, v):
     v_scaled = (v - v_min) / v_range
     if color_function_scaling and color_function_min is not None and color_function_max is not None:
         v_color_scaled = color_function_min + v_scaled * color_function_range
     else:
         v_color_scaled = v
     v_lookup = int(v_scaled * 100 + 0.5)     # calculate and store 100 different shades max.
     value = colors.get(v_lookup)
     if value is None:
         value = Expression(color_func, Real(v_color_scaled))
         value = value.evaluate(evaluation)
         colors[v_lookup] = value
     return value
Пример #26
0
    def apply(self, expr, evaluation):
        'Precedence[expr_]'

        from mathics.builtin import builtins

        name = expr.get_name()
        precedence = 1000
        if name:
            builtin = builtins.get(name)
            if builtin is not None and isinstance(builtin, Operator):
                precedence = builtin.precedence
            else:
                precedence = 670
        return Real(precedence)
Пример #27
0
        def convert_unit(leaves, target):

            mag = leaves[0]
            unit = leaves[1].get_string_value()
            quantity = Q_(mag, unit)
            converted_quantity = quantity.to(target)

            q_mag = converted_quantity.magnitude.evaluate(
                evaluation).get_float_value()

            # Displaying the magnitude in Integer form if the convert rate is an Integer
            if q_mag - int(q_mag) > 0:
                return Expression("Quantity", Real(q_mag), target)
            else:
                return Expression("Quantity", Integer(q_mag), target)
Пример #28
0
class SystemTimeZone(Predefined):
    """
    <dl>
      <dt>'$SystemTimeZone'
      <dd> gives the current time zone for the computer system on which Mathics is being run.
    </dl>

    >> $SystemTimeZone
     = ...
    """

    name = "$SystemTimeZone"
    value = Real(-time.timezone / 3600.0)

    def evaluate(self, evaluation):
        return self.value
Пример #29
0
    def apply(self, image, evaluation, options):
        'Threshold[image_Image, OptionsPattern[Threshold]]'
        pixels = image.grayscale().pixels

        method = self.get_option(options, 'Method', evaluation)
        method_name = method.get_string_value() if isinstance(
            method, String) else method.to_python()
        if method_name == 'Cluster':
            threshold = skimage.filters.threshold_otsu(pixels)
        elif method_name == 'Median':
            threshold = numpy.median(pixels)
        elif method_name == 'Mean':
            threshold = numpy.mean(pixels)
        else:
            return evaluation.message('Threshold', 'illegalmethod', method)

        return Real(threshold)
Пример #30
0
    def apply_pair(self, text1, i1, text2, i2, evaluation, options):
        'WordSimilarity[{text1_String, i1_}, {text2_String, i2_}, OptionsPattern[%(name)s]]'
        doc1 = self._nlp(text1.get_string_value(), evaluation, options)
        if doc1:
            if text2.get_string_value() == text1.get_string_value():
                doc2 = doc1
            else:
                doc2 = self._nlp(text2.get_string_value(), evaluation, options)
            if doc2:
                if i1.get_head_name() == 'System`List' and i2.get_head_name(
                ) == 'System`List':
                    if len(i1.leaves) != len(i2.leaves):
                        evaluation.message('TextSimilarity', 'idxfmt')
                        return
                    if any(not all(isinstance(i, Integer) for i in l.leaves)
                           for l in (i1, i2)):
                        evaluation.message('TextSimilarity', 'idxfmt')
                        return
                    indices1 = [i.get_int_value() for i in i1.leaves]
                    indices2 = [i.get_int_value() for i in i2.leaves]
                    multiple = True
                elif isinstance(i1, Integer) and isinstance(i2, Integer):
                    indices1 = [i1.get_int_value()]
                    indices2 = [i2.get_int_value()]
                    multiple = False
                else:
                    evaluation.message('TextSimilarity', 'idxfmt')
                    return

                for index1, index2 in zip(indices1, indices2):
                    for i, pos, doc in zip((index1, index2), (1, 2),
                                           (doc1, doc2)):
                        if i < 1 or i > len(doc):
                            evaluation.message('TextSimilarity', 'txtidx', i,
                                               pos, len(doc))
                            return

                result = [
                    Real(doc1[j1 - 1].similarity(doc2[j2 - 1]))
                    for j1, j2 in zip(indices1, indices2)
                ]

                if multiple:
                    return Expression('List', *result)
                else:
                    return result[0]