Implementing functions that include name and symbol - symbolic-math

I need to define in Sage some functions with attributes that define
the name of the function
its mathematical/physical symbol
the definition of the function
(and those in combination)
and methods that return
those attributes in LaTeX format
both symbolic and with parameters input and then also
the result of the function on those parameters
An example is something like
>>> somefunction.name
\text{some function}
>>> somefunction.symbol
\mathrm{SF}
>>> somefunction.definition
\mathrm{SF} = 3x + y
>>> somefunction(4, 5)
17
>>> somefunction(4, 5).symbol
\mathrm{SF}\left(4, 5\right)
>>> anotherfunction.name
\text{another function}
>>> anotherfunction.symbol
\mathrm{AF}
>>> anotherfunction.definition
\mathrm{AF} = 2z
>>> anotherfunction('SF')
2(3x + y)
I suppose the way of implementing it is by defining a new class that inherits from the function Class. And perhaps the method names should have _latex appended.
Any ideas?
Thanks in advance,
Chris

You definitely don't want to just use function if you are planning something more interesting. See if the tips for implementing new symbolic functions fits your needs (though this may be overkill). Yes, you definitely want something with a latex attribute/method.

Related

Is there a way to constrain music21's chord detection to non-slash chords?

I'm working on a script that takes as input a sequence of MIDI notes and outputs a chord symbol for use in Impro-Visor, an open-source jazz improvisation helper. In order to take advantage of Impro-Visor's large vocabulary of chords I've been trying to add to music21's chord vocabulary--music21 itself will handle the MIDI pitches and the interpretation of most common chords--using the harmony.addNewChordSymbol method, but the system doesn't offer the new chords in its chord detection. For example, if I try this chord from the Harmony module's docs:
>>>harmony.addNewChordSymbol('BethChord', '1,3,-6,#9', ['MH', 'beth'])
>>>c = chord.Chord(['C3','D#3','E3','A-3'])
>>>print(harmony.chordSymbolFromChord(c))
'A-+/CaddD#'
Whereas I would hope in this case to get: 'Cbeth'
Music21 consistently suggests slash chords like the above rather than whatever chord I've tried to add to the vocabulary, presumably because the chord type to the left of the slash--'+', in this case--comes earlier in the OrderedDict in harmony.py. Is there any way to make the chord-detection prefer a custom chord type over these slash chords (which I don't have any way of handling)?
I found that just telling music21 you meant for "C" to be the root does the trick. (Otherwise, it will try to stack in thirds and treat "Ab" as the root.) Call .root() like this:
>>> harmony.addNewChordSymbol('BethChord', '1,3,-6,#9', ['MH', 'beth'])
>>> c = chord.Chord(['C3','D#3','E3','A-3'])
>>> c.root(c.bass())
>>> harmony.chordSymbolFromChord(c)
<music21.harmony.ChordSymbol CMH>

How to get a type from a TypeVar?

Supose that I have:
T = TypeVar('T', bound='Client')
Now, I want a function that gets the type T and returns 'Client', or, yet better a class Client.
How I can get it in Python 3.9?
Thanks.
You can do so via typing_inspect.get_bound from the typing_inspect package. It offers cross-version support for runtime inspection of type annotations:
>>> class Foo: pass
>>> T = TypeVar("T", bound=Foo)
>>> typing_inspect.get_bound(T)
__main__.Foo
>>> T = TypeVar("T", bound="Foo")
>>> typing_inspect.get_bound(T)
ForwardRef('Foo')
When bound is set to a string, the returned value is a "forward reference". I don't think there's currently a public API to evaluate that to a concrete class. There is a private API that you could use like this:
>>> ref = typing_inspect.get_bound(T)
>>> ref._evaluate(globals(), globals(), set())
__main__.Foo

Scala: array.toList vs array.to[List]

I am wondering what is the difference between .toList vs .to[List] in arrays. I made this test in the spark-shell and there is no difference in the result, but I don't know what is better to use. Any comments?
scala> val l = Array(1, 2, 3).toList
l: List[Int] = List(1, 2, 3)
scala> val l = Array(1, 2, 3).to[List]
l: List[Int] = List(1, 2, 3)
Adding to Luis' comment, the to[List] is (as Luis mentioned) actually using a factory parameter to construct the list. However, the linked source is only valid from Scala 2.13+, after the collections overhaul. The syntax you use wouldn't work in Scala 2.13, instead you would have to write .to(List), explicitly passing the factory argument. In previous Scala versions, the method looked like this. The CanBuildFrom is essentially a factory passed as an implicit parameter.
The reason this method exists is that it is generic beyond collections in the standard library (and you don't have to define every single possible transformation as a separate method). You can use another collections library (e.g. Breeze), and either construct a factory or use an included one, and use the to(factory) method. You can also use it in generic functions where you take the factory as a parameter and just pass it on to the conversion method, for example something like:
def mapAndConvert[A, B, C](list: List[A], f: A => B, factory: Factory[B, C]): C[B] =
list.map(f).to(factory)
In this example I don't need to know what collection C is, yet I can still return one with ease.

Python PeeWee IntegerField - Default value of unix timestamp

I would like to manage timestamps in my database using seconds since epoch using a PeeWee IntegerField rather than a DateTimeField. I know that the field definition can take a default value using a callable, but I would need to do something like:
timestamp = IntegerField(default=int(datetime.datetime.now().strftime('%s')))
Which I suppose is incorrect since the default value should not actually invoke the callable.
I also tried wrapping this in a function and passing that function as a callable:
def get_timestamp():
return int(datetime.datetime.now().strftime('%s'))
timestamp = IntegerField(default=get_timestamp)
However this did not work either.
Is there a way to accomplish this, or do I have to retro-fit my data to use DateTimeFields instead?
I see you mentioned that you tried wrapping your function call, I'm surprised that didn't work for you, because it appears to work fine for me:
>>> from datetime import datetime
>>> from peewee import *
>>> db = SqliteDatabase(':memory:')
>>> def get_ts():
... return int(datetime.now().strftime('%s'))
>>> get_ts()
1448471382
>>> class TestModel(Model):
... ts = IntegerField(default=get_ts)
... class Meta:
... database = db
>>> TestModel.create_table()
>>> tm = TestModel.create()
>>> tm.ts
1448471421
>>> ts_from_db = TestModel.get(TestModel.id == tm.id)
>>> ts_from_db.ts
1448471421
The reason you need to wrap it is because the default param takes a callable, and if you pass just the result of a function call, it interprets it as just another static value.

If I have a direct reference to a google app engine Property object, how do I get() or set() upon it?

Assume I have a Model class called Bird and a instance of Bird called pigeon. I know I can get all the Properties of Pigeon (or bird) using
properties = pigeon.properties() #Note, Bird.properties() would also work
This returns me a dictionary where the keys are strings that match the name I gave said properties in birds, and the value are actual Property objects. My question is, how do I get or set the value using said property objects. I wish to do this because I want to allow a client to dynamically specify as strings:
1) the key to a Model object
2) a property of said Model object
3) and a value that the afformentioned Property of said Model object might take on
So clearly, I need to first get the Model object, then determine whether said Property exist, and finally get or set it somehow? Is this possible? Thank you.
I played around with App Engine Console, which is great for testing and experimenting. It looks to me like you want to use __set__, with the first argument being your model instance, and the second being the new value. Next you need to put() the instance as usual.
Here is the console session to make it clearer. (Have I mentioned how App Engine Console is awesome?)
>>> from google.appengine.ext import db
>>> class Bird(db.Model):
... name = db.StringProperty()
... can_fly = db.BooleanProperty()
...
>>> def summarize():
... for name in ('Pesto', 'Bobby'):
... count = Bird.all().filter('name =', name).count()
... print 'I found %d birds named %s' % (count, name)
...
>>> summarize()
I found 0 birds named Pesto
I found 0 birds named Bobby
>>> pigeon = Bird(name='Pesto', can_fly=True)
>>> pigeon.put()
datastore_types.Key.from_path('Bird', 41015L, _app=u'con')
>>> summarize()
I found 1 birds named Pesto
I found 0 birds named Bobby
>>> props = pigeon.properties()
>>> props
{'can_fly': <google.appengine.ext.db.BooleanProperty object at 0x46ddd1cc3ddb2268>, 'name': <google.appengine.ext.db.StringProperty object at 0x46ddd1cc3ddb2fe8>}
>>> prop = props['name']
>>> prop
<google.appengine.ext.db.StringProperty object at 0x46ddd1cc3ddb2a68>
>>> prop.__set__(pigeon, 'Bobby')
>>> pigeon.name
'Bobby'
>>> pigeon.put()
datastore_types.Key.from_path('Bird', 41015L, _app=u'con')
>>> summarize()
I found 0 birds named Pesto
I found 1 birds named Bobby
>>> bobby = Bird.all().filter('name =', 'Bobby').fetch(1)[0]
>>> bobby.name
u'Bobby'
If you try the online console demo yourself, be sure to delete my old instances first, as we all share the same data store.

Resources