Beispiel #1
0
    def __init__(self, obj, figsize=4, name=None):
        r"""
        Which is the specialized widget class name for viewing this object (if any)

        TESTS::

            sage: from sage_explorer._widgets import PlotWidget
            sage: w = PlotWidget(sin)
            sage: w.name
            'sin'
            sage: len(w.children)
            1
            sage: w = PlotWidget(list(cremona_curves(srange(35)))[0])
            sage: w.name
            'Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field'
            sage: x, y = var('x y')
            sage: g(x,y) = x**2 + y**2
            sage: w = PlotWidget(g)
            sage: w.name
            '(x, y) |--> x^2 + y^2'
        """
        super(PlotWidget, self).__init__()
        self.value = obj
        if not name:
            name = repr(obj)
        self.name = name
        svgfilename = path_join(SAGE_TMP, '%s.svg' % name)
        pngfilename = path_join('.', '%s.png' % name)
        if hasattr(obj,
                   'number_of_arguments') and obj.number_of_arguments() == 2:
            if type(figsize) == type(()):
                if len(figsize) == 2:
                    urange, vrange = figsize
                elif len(figsize) == 1:
                    urange, vrange = figsize, figsize
            elif str(figsize).isnumeric():
                urange = vrange = (-float(figsize) / 2, float(figsize) / 2)
            self.plot = plot3d(obj, urange, vrange)
        else:
            try:
                self.plot = plot(obj, figsize=figsize)
            except:
                try:
                    self.plot = obj.plot()
                except:
                    self.plot = plot(obj)
        try:
            self.plot.save(svgfilename)
            self.children = [HTML(open(svgfilename, 'rb').read())]
        except:
            self.plot.save(pngfilename)
            self.children = [
                HTML('<img title="' + self.name + ' Plot" src="' +
                     pngfilename + '">')
            ]
Beispiel #2
0
def EC_nf_plot(E,base_field_gen_name):
    K = E.base_field()
    n1 = K.signature()[0]
    if n1 == 0:
        return plot([])
    prec = 53
    maxprec = 10**6
    while prec < maxprec: # Try to base change to R. May fail if resulting curve is almost singular, so increase precision.
        try:
            SR = K.embeddings(RealField(prec))
            X = [E.base_extend(s) for s in SR]
            break
        except ArithmeticError:
            prec *= 2
    if prec >= maxprec:
        return text("Unable to plot",(1,1),fontsize="xx-large")
    X = [e.plot() for e in X]
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = ["blue","red","green","orange","brown"] # Preset colours, because rainbow tends to return too pale ones
    if n1 > len(cols):
        cols = rainbow(n1)
    return sum([EC_R_plot([SR[i](a) for a in E.ainvs()],xmin,xmax,ymin,ymax,cols[i],"$"+base_field_gen_name+" \mapsto$ "+str(SR[i].im_gens()[0].n(20))) for i in range(n1)])
def EC_nf_plot(K, ainvs, base_field_gen_name):
    try:
        n1 = K.signature()[0]
        if n1 == 0:
            return plot([])
        R=[]
        S=K.embeddings(RDF)
        for s in S:
            A=[s(c) for c in ainvs]
            R.append(EC_R_plot_zone(Rx([A[4],A[3],A[1],1]),Rx([A[2],A[0]]))) 
        xmin = min([r[0] for r in R])
        xmax = max([r[1] for r in R])
        ymin = min([r[2] for r in R])
        ymax = max([r[3] for r in R])
        cols = rainbow(n1) # Default choice of n colours
        # However, these tend to be too pale, so we preset them for small values of n
        if n1==1:
            cols=["blue"]
        elif n1==2:
            cols=["red","blue"]
        elif n1==3:
            cols=["red","limegreen","blue"]
        elif n1==4:
            cols = ["red", "orange", "forestgreen", "blue"]
        elif n1==5:
            cols = ["red", "orange", "forestgreen", "blue", "darkviolet"]
        elif n1==6:
            cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet"]
        elif n1==7:
            cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet", "fuchsia"]
        return sum([EC_R_plot([S[i](c) for c in ainvs], xmin, xmax, ymin, ymax, cols[i], "$" + base_field_gen_name + " \mapsto$ " + str(S[i].im_gens()[0].n(20))+"$\dots$") for i in range(n1)]) 
    except:
        return text("Unable to plot", (1, 1), fontsize=36)
Beispiel #4
0
def EC_nf_plot(K, ainvs, base_field_gen_name):
    try:
        n1 = K.signature()[0]
        if n1 == 0:
            return plot([])
        R=[]
        S=K.embeddings(RDF)
        for s in S:
            A=[s(c) for c in ainvs]
            R.append(EC_R_plot_zone(Rx([A[4],A[3],A[1],1]),Rx([A[2],A[0]]))) 
        xmin = min([r[0] for r in R])
        xmax = max([r[1] for r in R])
        ymin = min([r[2] for r in R])
        ymax = max([r[3] for r in R])
        cols = rainbow(n1) # Default choice of n colours
        # However, these tend to be too pale, so we preset them for small values of n
        if n1==1:
            cols=["blue"]
        elif n1==2:
            cols=["red","blue"]
        elif n1==3:
            cols=["red","limegreen","blue"]
        elif n1==4:
            cols = ["red", "orange", "forestgreen", "blue"]
        elif n1==5:
            cols = ["red", "orange", "forestgreen", "blue", "darkviolet"]
        elif n1==6:
            cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet"]
        elif n1==7:
            cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet", "fuchsia"]
        return sum([EC_R_plot([S[i](c) for c in ainvs], xmin, xmax, ymin, ymax, cols[i], "$" + base_field_gen_name + " \mapsto$ " + str(S[i].im_gens()[0].n(20))+"$\dots$") for i in range(n1)]) 
    except:
        return text("Unable to plot", (1, 1), fontsize=36)
Beispiel #5
0
def EC_nf_plot(E, base_field_gen_name):
    K = E.base_field()
    n1 = K.signature()[0]
    if n1 == 0:
        return plot([])
    prec = 53
    maxprec = 10 ** 6
    while prec < maxprec:  # Try to base change to R. May fail if resulting curve is almost singular, so increase precision.
        try:
            SR = K.embeddings(RealField(prec))
            X = [E.base_extend(s) for s in SR]
            break
        except ArithmeticError:
            prec *= 2
    if prec >= maxprec:
        return text("Unable to plot", (1, 1), fontsize="xx-large")
    X = [e.plot() for e in X]
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = ["blue", "red", "green", "orange", "brown"]  # Preset colours, because rainbow tends to return too pale ones
    if n1 > len(cols):
        cols = rainbow(n1)
    return sum([EC_R_plot([SR[i](a) for a in E.ainvs()], xmin, xmax, ymin, ymax, cols[i], "$" + base_field_gen_name + " \mapsto$ " + str(SR[i].im_gens()[0].n(20))) for i in range(n1)])
Beispiel #6
0
def guess_plot(obj, figsize=4):
    r"""
    Find the corresponding graphics object, if there is one.

    TESTS::

        sage: from sage_explorer import guess_plot
        sage: guess_plot(sin)
        Graphics object consisting of 1 graphics primitive
        sage: guess_plot(list(cremona_curves(srange(35)))[0])
        Graphics object consisting of 1 graphics primitive
        sage: x, y = var('x y')
        sage: g(x,y) = x**2 + y**2
        sage: guess_plot(g)
        Graphics3d Object
        sage: type(guess_plot(Partition([4,3])))
        ...
        <class 'NoneType'>
    """
    plt = None
    if hasattr(obj, 'number_of_arguments') and obj.number_of_arguments() == 2:
        if type(figsize) == type(()):
            if len(figsize) == 2:
                urange, vrange = figsize
            elif len(figsize) == 1:
                urange, vrange = figsize, figsize
        elif str(figsize).isnumeric():
            urange = vrange = (-float(figsize) / 2, float(figsize) / 2)
        try:
            plt = plot3d(obj, urange, vrange)
        except:
            pass
        return plt
    try:
        plt = plot(obj, figsize=figsize)
    except:
        try:
            plt = obj.plot()
        except:
            try:
                plt = plot(obj)
            except:
                pass
    if plt is not None and plt._objects:
        return plt
    else:
        return None
Beispiel #7
0
def plotit(k):
    k = int(k[0])
    # FIXME there could be a filename collission
    fn = tempfile.mktemp(suffix=".png")
    x = var('x')
    p = plot(sin(k * x))
    p.save(filename=fn)
    data = file(fn).read()
    os.remove(fn)
    return data
Beispiel #8
0
 def __init__(self, obj, figsize=4, name=None):
     super(PlotWidget, self).__init__()
     self.value = obj
     if not name:
         name = repr(obj)
     svgfilename = path_join(SAGE_TMP, '%s.svg' % name)
     self.plot = plot(obj, figsize=figsize)
     self.plot.save(svgfilename)
     self.name = name
     self.children = [HTML(open(svgfilename, 'rb').read())]
Beispiel #9
0
    def judgeFlight(self, flight, dbg=False):
        """Old version of flight fitness function."""
        #times, result = self._scene.evaluateCrafts([flight])

        # TODO define elsewhere
        bat_Wh_cap = 15.5 * 650

        times = pd.date_range(start='2020-11-28T08',
                              end='2020-11-30T08',
                              freq='120S',
                              tz='America/Detroit').to_series()
        poses = flight.toPoses(times)
        throughput = self._scene.posesToThroughput(flight, poses)
        solar = flight._craft.calcSolarPower(poses, 36, -84)
        battery = flight._craft.calcBatteryCharge(poses,
                                                  solar,
                                                  15.5 * 650,
                                                  constant_draw=109)

        #print('up to', poses.z.max())

        mSocStart = pd.to_datetime(times[0]) + pd.offsets.Hour(6)
        mSoc = battery[mSocStart:].min() / bat_Wh_cap * 100

        if dbg:
            # The ridiculous size is needed for Sage 9.0
            positions = (flight._trajectory.render() +
                         self._scene.render(size=20000))  #.scale(0.001)
        else:
            positions = None

        # # Mean flight power in watts
        meanFlightPower = flight.cycleEnergy / flight.cycleTime
        # # Minimum throughput of any user in kbps
        # thru = np.mean(result) / 1e3
        # # Roughly Mb/J
        # score = (thru / meanFlightPower).n()

        #meanFlightPower = poses.power.mean()
        thru = throughput.mean()[0]
        #score = thru / meanFlightPower / 1e3
        #score = thru * mSoc / 1e6
        score = mSoc

        if dbg:
            from sage.all import plot, var
            thruPlot = self._scene.plotResults(times, result) + plot(
                [thru], (var('x'), min(times), max(times)), ymin=0)
        else:
            thruPlot = None

        return score, thru, mSoc, flight.cycleTime, positions, thruPlot
Beispiel #10
0
def EC_nf_plot(E,base_field_gen_name):
    K = E.base_field()
    SR = K.embeddings(RR)
    n1 = len(SR)
    if n1 == 0:
        return plot([])
    X = [E.base_extend(s).plot() for s in SR]
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = rainbow(n1)
    return sum([EC_R_plot([SR[i](a) for a in E.ainvs()],xmin,xmax,ymin,ymax,cols[i],"$"+base_field_gen_name+" \mapsto$ "+str(SR[i].im_gens()[0].n(20))) for i in range(n1)])
Beispiel #11
0
def render_plotLfunction_from_db(db, dbTable, condition):
    data_location = os.path.expanduser(
        "~/data/lfunction_plots/{0}.db".format(db))

    if not os.path.exists(data_location):
        # We want to raise some exception so that the calling
        # function can catch it and fall back to normal plotting
        # when the database does not exist or doesn't have the
        # plot. This seems like a reasonable exception to raise.
        raise KeyError

    try:
        db = sqlite3.connect(data_location)
        with db:
            cur = db.cursor()
            query = "SELECT start,end,points FROM {0} WHERE {1} LIMIT 1".format(dbTable,
                                                                                condition)
            cur.execute(query)
            row = cur.fetchone()

        db.close()

        start,end,values = row
        values = numpy.frombuffer(values)
        step = (end - start)/values.size

        pairs = [ (start + x * step, values[x] )
                  for x in range(0, values.size, 1)]
        p = plot(spline(pairs), -30, 30, thickness = 0.4)
        styleLfunctionPlot(p, 8)

    except (sqlite3.OperationalError, TypeError):
        # An OperationalError will happen when the database exists for some reason
        # but it doesn't have the table. A TypeError will happen when there are no
        # results returned, in which case row will be None and unpacking the tuple
        # will fail. We turn both of these in KeyErrors, which can be caught by
        # the calling function to fallback to normal plotting.

        raise KeyError

    fn = tempfile.mktemp(suffix=".png")
    p.save(filename=fn, dpi = 100)
    data = file(fn).read()
    os.remove(fn)
    response = make_response(data)
    response.headers['Content-type'] = 'image/png'
    return response
Beispiel #12
0
def EC_nf_plot(E, base_field_gen_name):
    K = E.base_field()
    SR = K.embeddings(RR)
    n1 = len(SR)
    if n1 == 0:
        return plot([])
    X = [E.base_extend(s).plot() for s in SR]
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = rainbow(n1)
    return sum([
        EC_R_plot([SR[i](a) for a in E.ainvs()], xmin, xmax, ymin, ymax,
                  cols[i], "$" + base_field_gen_name + " \mapsto$ " +
                  str(SR[i].im_gens()[0].n(20))) for i in range(n1)
    ])
Beispiel #13
0
def EC_nf_plot(E, base_field_gen_name):
    K = E.base_field()
    n1 = K.signature()[0]
    if n1 == 0:
        return plot([])
    prec = 53
    maxprec = 10 ** 6
    while prec < maxprec:  # Try to base change to RR. May fail if resulting curve is almost singular, so increase precision.
        try:
            SR = K.embeddings(RealField(prec))
            X = [E.base_extend(s) for s in SR]
            break
        except ArithmeticError:
            prec *= 2
    if prec >= maxprec:
        return text("Unable to plot", (1, 1), fontsize=36)
    try:
        X = [e.plot() for e in X]
    except:
        return text("Unable to plot", (1, 1), fontsize=36)
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = rainbow(n1) # Default choice of n colours
    # Howver, these tend to be too pale, so we preset them for small values of n
    if n1==1:
        cols=["blue"]
    elif n1==2:
        cols=["red","blue"]
    elif n1==3:
        cols=["red","limegreen","blue"]
    elif n1==4:
        cols = ["red", "orange", "forestgreen", "blue"]
    elif n1==5:
        cols = ["red", "orange", "forestgreen", "blue", "darkviolet"] 
    elif n1==6:
        cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet"] 
    elif n1==7:
        cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet", "fuchsia"] 
    return sum([EC_R_plot([SR[i](a) for a in E.ainvs()], xmin, xmax, ymin, ymax, cols[i], "$" + base_field_gen_name + " \mapsto$ " + str(SR[i].im_gens()[0].n(20))+"$\dots$") for i in range(n1)])
Beispiel #14
0
def EC_R_plot(ainvs, xmin, xmax, ymin, ymax, colour, legend):
    x = var('x')
    y = var('y')
    c = (xmin + xmax) / 2
    d = (xmax - xmin)
    return implicit_plot(
        y**2 + ainvs[0] * x * y + ainvs[2] * y - x**3 - ainvs[1] * x**2 -
        ainvs[3] * x - ainvs[4], (x, xmin, xmax), (y, ymin, ymax),
        plot_points=500,
        aspect_ratio="automatic",
        color=colour
    ) + plot(
        0,
        xmin=c - 1e-5 * d,
        xmax=c + 1e-5 * d,
        ymin=ymin,
        ymax=ymax,
        aspect_ratio="automatic",
        color=colour,
        legend_label=legend
    )  # Add an extra plot outside the visible frame because implicit plots are buggy: their legend does not show (http://trac.sagemath.org/ticket/15903)
Beispiel #15
0
def EC_R_plot(ainvs, xmin, xmax, ymin, ymax, colour, legend):
    x = var("x")
    y = var("y")
    c = (xmin + xmax) / 2
    d = xmax - xmin
    return implicit_plot(
        y ** 2 + ainvs[0] * x * y + ainvs[2] * y - x ** 3 - ainvs[1] * x ** 2 - ainvs[3] * x - ainvs[4],
        (x, xmin, xmax),
        (y, ymin, ymax),
        plot_points=1000,
        aspect_ratio="automatic",
        color=colour,
    ) + plot(
        0,
        xmin=c - 1e-5 * d,
        xmax=c + 1e-5 * d,
        ymin=ymin,
        ymax=ymax,
        aspect_ratio="automatic",
        color=colour,
        legend_label=legend,
    )  # Add an extra plot outside the visible frame because implicit plots are buggy: their legend does not show (http://trac.sagemath.org/ticket/15903)
Beispiel #16
0
def EC_nf_plot(E, base_field_gen_name):
    K = E.base_field()
    n1 = K.signature()[0]
    if n1 == 0:
        return plot([])
    prec = 53
    maxprec = 10 ** 6
    while prec < maxprec:  # Try to base change to RR. May fail if resulting curve is almost singular, so increase precision.
        try:
            SR = K.embeddings(RealField(prec))
            X = [E.base_extend(s) for s in SR]
            break
        except ArithmeticError:
            prec *= 2
    if prec >= maxprec:
        return text("Unable to plot", (1, 1), fontsize="xx-large")
    X = [e.plot() for e in X]
    xmin = min([x.xmin() for x in X])
    xmax = max([x.xmax() for x in X])
    ymin = min([x.ymin() for x in X])
    ymax = max([x.ymax() for x in X])
    cols = rainbow(n1) # Default choice of n colours
    # Howver, these tend to be too pale, so we preset them for small values of n
    if n1==1:
        cols=["blue"]
    elif n1==2:
        cols=["red","blue"]
    elif n1==3:
        cols=["red","limegreen","blue"]
    elif n1==4:
        cols = ["red", "orange", "forestgreen", "blue"]
    elif n1==5:
        cols = ["red", "orange", "forestgreen", "blue", "darkviolet"] 
    elif n1==6:
        cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet"] 
    elif n1==7:
        cols = ["red", "darkorange", "gold", "forestgreen", "blue", "darkviolet", "fuchsia"] 
    return sum([EC_R_plot([SR[i](a) for a in E.ainvs()], xmin, xmax, ymin, ymax, cols[i], "$" + base_field_gen_name + " \mapsto$ " + str(SR[i].im_gens()[0].n(20))+"$\dots$") for i in range(n1)])