Custom Scale using music21's scale class to inherit "deriveAll" function - music21

I was wondering what the proper way of defining a custom scale would be to inhrert the attributes of 'scale' class?
Should I do include my class in the "music21/scale/init.py'"
class myAbastract(AbstractScale):
'''
A pseudo my-scale.
'''
def __init__(self):
super().__init__()
self.type = 'Abstract My Name'
self.octaveDuplicating = True
self.dominantDegree: int = -1
self.buildNetwork()
When I defined myScale in the main.py, it seems it doesn't inherit "deriveAll()" method/function.
pitchListStrs = 'a b` c d e f g a'.split()
pitchList = [pitch.Pitch(p) for p in pitchListStrs]
myScaleA = scale.ConcreteScale(pitches=pitchList)
[str(p) for p in myScaleA.getPitches('E-5', 'G-7')]
myScale = myScaleA.abstract
mySol =scale.ConcreteScale()
mySol.tonic = pitch.Pitch('D')
But then, deriveAll is not defined:
myScale.deriveAll(['E5', 'F5', 'G5', 'A5', 'B`5', 'C6', 'D6', 'E6'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'AbstractScale' object has no attribute 'deriveAll'
Any help would be greatly appreciated.

deriveAll is a routine defined on ConcreteScale instances. You attempted to call it on an instance of AbstractScale. Try calling it on your variable myScaleA, which is concrete.

Related

Tensorflow: convert PrefetchDataset to BatchDataset

Tensorflow: convert PrefetchDataset to BatchDataset
With latest Tensorflow version 2.3.1I am trying to follow basic text classification example at: https://www.tensorflow.org/tutorials/keras/text_classification. Instead of creating dataset from directory as example does, I am using a csv file:
SELECT_COLUMNS = ['SentimentText','Sentiment']
LABEL_COLUMN = 'Sentiment'
LABELS = [0, 1]
def get_dataset(file_path, **kwargs):
dataset = tf.data.experimental.make_csv_dataset(
file_path,
batch_size=3, # Artificially small to make examples easier to show.
label_name=LABEL_COLUMN,
na_value="?",
num_epochs=1,
ignore_errors=True,
**kwargs)
return dataset
all_data = get_dataset(data_path, select_columns=SELECT_COLUMNS)
As a result I get:
type(all_data)
tensorflow.python.data.ops.dataset_ops.PrefetchDataset
Example loads data from directory with:
batch_size = 32
seed = 42
raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(
'aclImdb/train',
batch_size=batch_size,
validation_split=0.2,
subset='training',
seed=seed)
And gets dataset of another type:
type(raw_train_ds)
tensorflow.python.data.ops.dataset_ops.BatchDataset
Now when I try to standardise and vectorise data with functions from example:
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ')
return tf.strings.regex_replace(stripped_html,
'[%s]' % re.escape(string.punctuation),
'')
max_features = 10000
sequence_length = 250
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=max_features,
output_mode='int',
output_sequence_length=sequence_length)
And apply them to my dataset I get error:
# Make a text-only dataset (without labels), then call adapt
train_text = all_data.map(lambda x, y: x)
vectorize_layer.adapt(train_text)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-20-1f1fc445912d> in <module>
1 # Make a text-only dataset (without labels), then call adapt
2 train_text = all_data.map(lambda x, y: x)
----> 3 vectorize_layer.adapt(train_text)
/opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/keras/layers/preprocessing/text_vectorization.py in adapt(self, data, reset_state)
378 shape = dataset_ops.get_legacy_output_shapes(data)
379 if not isinstance(shape, tensor_shape.TensorShape):
--> 380 raise ValueError("The dataset passed to 'adapt' must contain a single "
381 "tensor value.")
382 if shape.rank == 0:
ValueError: The dataset passed to 'adapt' must contain a single tensor value.
How to convert PrefetchDataset to BatchDataset ?
You could use tf.stack method to pack the features into a single array. The below function is from Custom training: walkthrough in Tensorflow.
def pack_features_vector(features, labels):
features = tf.stack(list(features.values()), axis=1)
return features, labels
all_data = get_dataset(data_path, select_columns=SELECT_COLUMNS)
train_dataset = all_data.map(pack_features_vector)
train_text = train_dataset.map(lambda x, y: x)
vectorize_layer.adapt(train_text)

'numpy.ndarray' object is not callable?

Running this script:
import time
import picamera
import picamera.array
import numpy as np
with picamera.PiCamera() as camera:
with picamera.array.PiBayerArray(camera) as stream:
camera.capture(stream, 'jpeg', bayer=True)
# Demosaic data and write to output (just use stream.array if you
# want to skip the demosaic step)
output = (stream.array() >> 2).astype(np.uint8)
with open('image.jpg', 'wb') as f:
output.tofile(f)
Gives the following error:
Traceback (most recent call last):
File "numpy_simple.py", line 11, in <module>
output = (stream.array() >> 2).astype(np.uint8)
TypeError: 'numpy.ndarray' object is not callable
While running:
output = (stream.demosaic() >> 2).astype(np.uint8)
with open('image.data', 'wb') as f:
output.tofile(f)
Does not give any error.
I'm a bit confused.
array is an attribute, not a method. You don't need to call it.
Use stream.array, not stream.array().
Source: PiArrayOutput, which is the base class for PiBayerArray.
Conversely, .demosaic() is an instance method, which is why you need to call it to get its return value.

Wagtail ChoiceBlock error

Can you help me to convert following code so that will work for choiceblock in wagtail
YEAR_CHOICES = []
for r in range(1999, (datetime.now().year+1)):
YEAR_CHOICES.append((r,r))
class Spieler(StructBlock):
jahrgang = ChoiceBlock(_('year'), max_length=4, choices=YEAR_CHOICES, default=datetime.now().year)
at the moment I have the following error
File "C:\Users\xakep\GitHub\treichle_cup\team_rooster\models.py", line 31, in <module>
class Spieler(StructBlock):
File "C:\Users\xakep\GitHub\treichle_cup\team_rooster\models.py", line 37, in Spieler
jahrgang = ChoiceBlock(_('year'), max_length=4, choices=YEAR_CHOICES, default=datetime.now().year)
TypeError: __init__() got multiple values for argument 'choices'
_('year') should be passed as label=_('year'):
jahrgang = ChoiceBlock(label=_('year'), max_length=4, choices=YEAR_CHOICES, default=datetime.now().year)
ChoiceBlock only accepts named arguments - if you leave out the name, it'll think that you're passing a choices value instead.

How do I create an abstract function that has a given derivative in Sage?

I want to have abstract $f$ function that has a given derivative. But, when I try to substitute it to D[0](f)(t), Sage says:
NameError: name 'D' is not defined
R.<t,u1,u2> = PolynomialRing(RR,3,'t' 'u1' 'u2')
tmp1 = r1*k1*u1-(r1/k1)*k1^2*u1^2-r1*b12/k1*k1*u1*k2*u2
f=function('f',t)
a=diff(f)
a.substitute_expression((D[0](f)(t))==tmp1)
tmp1.integral() won't do the job. I also can't substitute the integral, although it gives no warning.
%var u10, u20,r1,r2,k1,k2,b12,b21,t
u1=function('u1',t)
u2=function('u2',t)
tmp1 = r1*k1*u1-(r1/k1)*k1^2*u1^2-r1*b12/k1*k1*u1*k2*u2
tmp2 = r2*u2*k2-r2/k2*k2^2*u2^2-((r2*b21)/k2)*u1*u2*k1*k2
v1=integral(tmp1,t)
v2=integral(tmp2,t)
sep1=tmp1.substitute_expression(u1==v1,u2==v2)
sep2=tmp2.substitute_expression(u1==v1,u2==v2)
trial=diff(sep1,t)
trial.substitute_expression((integrate(-b12*k2*r1*u1(t)*u2(t) - k1*r1*u1(t)^2 + k1*r1*u1(t), t))==v1, (integrate(-b12*k2*r1*u1(t)*u2(t) - k1*r1*u1(t)^2 + k1*r1*u1(t), t))==v2)
Now let's go back to original version:
d1=diff(tmp1,t)
d1.substitute_function((D[0](u1)(t)),tmp1)
Error in lines 13-13
Traceback (most recent call last):
File "/projects/b501d31c-1f5d-48aa-bee3-73a2dcb30a39/.sagemathcloud/sage_server.py", line 733, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in <module>
NameError: name 'D' is not defined
I don't know if this is really what you are looking for. But it offers at least some semblance of it.
sage: def myfunc(self, *args, **kwds): return e^(args[0])^2
sage: foo = function('foo', nargs=1, tderivative_func=myfunc)
sage: foo(x)
foo(x)
sage: foo(x).diff(x)
e^(x^2)
sage: foo(x).diff(x,3)
4*x^2*e^(x^2) + 2*e^(x^2)
You'll need to read the documentation of function (gotten by typing function?) very carefully to use this well, especially the comment
Note that custom methods must be instance methods, i.e., expect the
instance of the symbolic function as the first argument.
The doc is quite subtle and could use some improvement.

Query or Expression for excluding certain values from DAL selection

I'm trying to exclude posts which have a tag named meta from my selection, by:
meta_id = db(db.tags.name == "meta").select().first().id
not_meta = ~db.posts.tags.contains(meta_id)
posts=db(db.posts).select(not_meta)
But those posts still show up in my selection.
What is the right way to write that expression?
My tables look like:
db.define_table('tags',
db.Field('name', 'string'),
db.Field('desc', 'text', default="")
)
db.define_table('posts',
db.Field('title', 'string'),
db.Field('message', 'text'),
db.Field('tags', 'list:reference tags'),
db.Field('time', 'datetime', default=datetime.utcnow())
)
I'm using Web2Py 1.99.7 on GAE with High Replication DataStore on Python 2.7.2
UPDATE:
I just tried posts=db(not_meta).select() as suggested by #Anthony, but it gives me a Ticket with the following Traceback:
Traceback (most recent call last):
File "E:\Programming\Python\web2py\gluon\restricted.py", line 205, in restricted
exec ccode in environment
File "E:/Programming/Python/web2py/applications/vote_up/controllers/default.py", line 391, in <module>
File "E:\Programming\Python\web2py\gluon\globals.py", line 173, in <lambda>
self._caller = lambda f: f()
File "E:/Programming/Python/web2py/applications/vote_up/controllers/default.py", line 8, in index
posts=db(not_meta).select()#orderby=settings.sel.posts, limitby=(0, settings.delta)
File "E:\Programming\Python\web2py\gluon\dal.py", line 7578, in select
return adapter.select(self.query,fields,attributes)
File "E:\Programming\Python\web2py\gluon\dal.py", line 3752, in select
(items, tablename, fields) = self.select_raw(query,fields,attributes)
File "E:\Programming\Python\web2py\gluon\dal.py", line 3709, in select_raw
filters = self.expand(query)
File "E:\Programming\Python\web2py\gluon\dal.py", line 3589, in expand
return expression.op(expression.first)
File "E:\Programming\Python\web2py\gluon\dal.py", line 3678, in NOT
raise SyntaxError, "Not suported %s" % first.op.__name__
SyntaxError: Not suported CONTAINS
UPDATE 2:
As ~ isn't currently working on GAE with Datastore, I'm using the following as a temporary work-around:
meta = db.posts.tags.contains(settings.meta_id)
all=db(db.posts).select()#, limitby=(0, settings.delta)
meta=db(meta).select()
posts = []
i = 0
for post in all:
if i==settings.delta: break
if post in meta: continue
else:
posts.append(post)
i += 1
#settings.delta is an long integer to be used with limitby
Try:
meta_id = db(db.tags.name == "meta").select().first().id
not_meta = ~db.posts.tags.contains(meta_id)
posts = db(not_meta).select()
First, your initial query returns a complete Row object, so you need to pull out just the "id" field. Second, not_meta is a Query object, so it goes inside db(not_meta) to create a Set object defining the set of records to select (the select() method takes a list of fields to return for each record, as well as a few other arguments, such as orderby, groupby, etc.).

Resources