Relationship between integers and their names - Prolog - numbers

I'm trying to explore the concepts of natural numbers, Peano numbers, arithmetic, etc. in Prolog. Right now I'm trying to create a predicate that will allow me to enter the name of any number and get it's numerical value (or vice versa). How would I go about this? My idea was that I would translate the numbers given and them add them together using the plus function (e.g. one hundred and forty-five: one, hundred = 100, and = 0, forty = 40, five = 5 -> 100 + 0 + 40 + 5 = 145.
Here's an example of some queries:
?- numnames(X, 375).
X = [three, hundred, and, seventy, five] ;
false.
?- numnames([seven], 7).
true ;
false.
Here are some of my exhaustive facts (I just picked some that would address a certain category):
numnames([],0).
numnames(and,0).
numnames([one],1).
numnames([ninety],90).
numnames([one, hundred], 100).
I'm just confused as to how to translate the numbers before the arithmetic, and also where/when do I stop making exhaustive facts and start making rules?
Thanks for the help.

This is a nice application for Prolog grammar rules or DCGs (basically syntactic sugar that hides some list manipulation and has a relatively straightforward translation to normal Prolog rules).
num_0_999(0) --> [zero].
num_0_999(N) --> num_1_99(N).
num_0_999(N) --> num_100_999(N).
num_1_99(N) --> num_1_9(N).
num_1_99(N) --> num_10_19(N).
num_1_99(N) --> decade(T), opt_1_9(U), {N is T+U}.
num_100_999(N) --> num_1_9(H), [hundred], opt_1_99(S), {N is 100*H+S}.
opt_1_9(0) --> [].
opt_1_9(N) --> num_1_9(N).
opt_1_99(0) --> [].
opt_1_99(N) --> [and], num_1_99(N).
num_1_9(1) --> [one]. num_1_9(2) --> [two]. num_1_9(3) --> [three].
num_1_9(4) --> [four]. num_1_9(5) --> [five]. num_1_9(6) --> [six].
num_1_9(7) --> [seven]. num_1_9(8) --> [eight]. num_1_9(9) --> [nine].
num_10_19(10) --> [ten]. num_10_19(11) --> [eleven].
num_10_19(12) --> [twelve]. num_10_19(13) --> [thirteen].
num_10_19(14) --> [fourteen]. num_10_19(15) --> [fifteen].
num_10_19(16) --> [sixteen]. num_10_19(17) --> [seventeen].
num_10_19(18) --> [eighteen]. num_10_19(19) --> [nineteen].
decade(20) --> [twenty]. decade(30) --> [thirty].
decade(40) --> [forty]. decade(50) --> [fifty].
decade(60) --> [sixty]. decade(70) --> [seventy].
decade(80) --> [eighty]. decade(90) --> [ninety].
This work both ways (and can enumerate all the numbers):
?- phrase(num_0_999(46), Name).
Name = [forty, six]
Yes (0.00s cpu, solution 1, maybe more)
?- phrase(num_0_999(N), [forty, six]).
N = 46
Yes (0.00s cpu, solution 1, maybe more)
[I had originally used a #=/2 constraint instead of is/2 to make the code work in both modes, but was reminded by #CapelliC's post that the same can be achieved in plain Prolog by moving the arithmetic to the end of the respective rules...]

I have an extravagant solution, which, nevertheless, could be practical for some situations.
Suppose the max number you plan to use is not too big, maybe a 1000 or 10000. And also you don't want to spend too much time creating Prolog program, don't want to deal with corner cases and are afraid of spelling errors (for example, because you are not a native English speaker, like me).
Then you can generate your Prolog program (list of facts) with another tool. Common Lisp has a standard tool to convert numbers to English words. Let's use it:
(defun generate-prolog (k)
(loop for n from 1 to k do
(format t "numnames([~a], ~a). ~%"
(substitute #\, #\Space
(remove #\,
(substitute #\Space #\- (format nil "~R" n)) ) ) n) ) )
(generate-prolog 1000)
Fragment of the Prolog program generated with CLISP (other Lisp implementations can use American spelling, without 'and'):
numnames([two,hundred,and,thirty,six], 236).
numnames([two,hundred,and,thirty,seven], 237).
numnames([two,hundred,and,thirty,eight], 238).
numnames([two,hundred,and,thirty,nine], 239).
numnames([two,hundred,and,forty], 240).
numnames([two,hundred,and,forty,one], 241).
numnames([two,hundred,and,forty,two], 242).
numnames([two,hundred,and,forty,three], 243).
numnames([two,hundred,and,forty,four], 244).
numnames([two,hundred,and,forty,five], 245).
numnames([two,hundred,and,forty,six], 246).
numnames([two,hundred,and,forty,seven], 247).
numnames([two,hundred,and,forty,eight], 248).
numnames([two,hundred,and,forty,nine], 249).
numnames([two,hundred,and,fifty], 250).

I will report a well thought DCG solution proposed by Ken Johnson. Full code is here, with a small modification to make it usable (I tested in SWI-Prolog). I amended rules like ten_to_nine{*filter*}(13) --> [thir{*filter*}]. that sincerely I don't know how to handle.
:- module(dcg_numerals, [number//1]).
% Grammar for numbers, e.g.
% phrase(number(I),[two,hundred,and,fifty,six]).
% An astonishing characteristic of this code is that it's
% fully bidirectional. The expression
% phrase(number(256),Words)
% will instantiate Words = [two,hundred,and,fifty,six].
% What's more,
% phrase(number(I),Words)
% will eventually instantiate I and Words to all the numbers it knows.
%
% Ken Johnson 17-9-87
number(I) --> '1_to_999'(I).
number(I) --> '1000_to_999999'(I).
'1_to_999'(I) --> '1_to_99'(I).
'1_to_999'(I) --> '100_to_999'(I).
% Compound number with thousands
'1000_to_999999'(I) --> thousands(I).
'1000_to_999999'(I) --> thousands(K),'100_to_999'(Htu),
{
I is K + Htu
}.
'1000_to_999999'(I) --> thousands(K),[and],'1_to_99'(Tu),
{
I is K + Tu
}.
% Thousands
thousands(I) --> '1_to_999'(K), [thousand],
{
I is K * 1000
}.
% Compound number with hundreds, tens and units
'100_to_999'(C) --> one_to_nine(H),[hundred],
{
C is 100 * H
}.
'100_to_999'(C) --> one_to_nine(H),[hundred],[and],'1_to_99'(Tu),
{
C is (100 * H) + Tu
}.
% Complete number: a single word 1-9 or 10-19
'1_to_99'(I) --> one_to_nine(I).
% '1_to_99'(I) --> ten_to_nine{*filter*}(I).
'1_to_99'(I) --> ten_to_nine(I).
'1_to_99'(I) --> multiple_of_ten(I).
'1_to_99'(I) --> '20_to_99'(I).
% Compound number with tens and units
'20_to_99'(I) --> multiple_of_ten(T), one_to_nine(U),
{
I is T + U
}.
% Single words (terminal nodes)
one_to_nine(1) --> [one].
one_to_nine(2) --> [two].
one_to_nine(3) --> [three].
one_to_nine(4) --> [four].
one_to_nine(5) --> [five].
one_to_nine(6) --> [six].
one_to_nine(7) --> [seven].
one_to_nine(8) --> [eight].
one_to_nine(9) --> [nine].
/*
ten_to_nine{*filter*}(10) --> [ten].
ten_to_nine{*filter*}(11) --> [eleven].
ten_to_nine{*filter*}(12) --> [twelve].
ten_to_nine{*filter*}(13) --> [thir{*filter*}].
ten_to_nine{*filter*}(14) --> [four{*filter*}].
ten_to_nine{*filter*}(15) --> [fif{*filter*}].
ten_to_nine{*filter*}(16) --> [six{*filter*}].
ten_to_nine{*filter*}(17) --> [seven{*filter*}].
ten_to_nine{*filter*}(18) --> [eigh{*filter*}].
ten_to_nine{*filter*}(19) --> [nine{*filter*}].
*/
ten_to_nine(10) --> [ten].
ten_to_nine(11) --> [eleven].
ten_to_nine(12) --> [twelve].
ten_to_nine(13) --> [thirteen].
ten_to_nine(14) --> [fourteen].
ten_to_nine(15) --> [fifteen].
ten_to_nine(16) --> [sixteen].
ten_to_nine(17) --> [seventeen].
ten_to_nine(18) --> [eighteen].
ten_to_nine(19) --> [nineteen].
multiple_of_ten(20) --> [twenty].
multiple_of_ten(30) --> [thirty].
multiple_of_ten(40) --> [forty].
multiple_of_ten(50) --> [fifty].
multiple_of_ten(60) --> [sixty].
multiple_of_ten(70) --> [seventy].
multiple_of_ten(80) --> [eighty].
multiple_of_ten(90) --> [ninety].

Related

Encoding Spotify URI to Spotify Codes

Spotify Codes are little barcodes that allow you to share songs, artists, users, playlists, etc.
They encode information in the different heights of the "bars". There are 8 discrete heights that the 23 bars can be, which means 8^23 different possible barcodes.
Spotify generates barcodes based on their URI schema. This URI spotify:playlist:37i9dQZF1DXcBWIGoYBM5M gets mapped to this barcode:
The URI has a lot more information (62^22) in it than the code. How would you map the URI to the barcode? It seems like you can't simply encode the URI directly. For more background, see my "answer" to this question: https://stackoverflow.com/a/62120952/10703868
The patent explains the general process, this is what I have found.
This is a more recent patent
When using the Spotify code generator the website makes a request to https://scannables.scdn.co/uri/plain/[format]/[background-color-in-hex]/[code-color-in-text]/[size]/[spotify-URI].
Using Burp Suite, when scanning a code through Spotify the app sends a request to Spotify's API: https://spclient.wg.spotify.com/scannable-id/id/[CODE]?format=json where [CODE] is the media reference that you were looking for. This request can be made through python but only with the [TOKEN] that was generated through the app as this is the only way to get the correct scope. The app token expires in about half an hour.
import requests
head={
"X-Client-Id": "58bd3c95768941ea9eb4350aaa033eb3",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"App-Platform": "iOS",
"Accept": "*/*",
"User-Agent": "Spotify/8.5.68 iOS/13.4 (iPhone9,3)",
"Accept-Language": "en",
"Authorization": "Bearer [TOKEN]",
"Spotify-App-Version": "8.5.68"}
response = requests.get('https://spclient.wg.spotify.com:443/scannable-id/id/26560102031?format=json', headers=head)
print(response)
print(response.json())
Which returns:
<Response [200]>
{'target': 'spotify:playlist:37i9dQZF1DXcBWIGoYBM5M'}
So 26560102031 is the media reference for your playlist.
The patent states that the code is first detected and then possibly converted into 63 bits using a Gray table. For example 361354354471425226605 is encoded into 010 101 001 010 111 110 010 111 110 110 100 001 110 011 111 011 011 101 101 000 111.
However the code sent to the API is 6875667268, I'm unsure how the media reference is generated but this is the number used in the lookup table.
The reference contains the integers 0-9 compared to the gray table of 0-7 implying that an algorithm using normal binary has been used. The patent talks about using a convolutional code and then the Viterbi algorithm for error correction, so this may be the output from that. Something that is impossible to recreate whithout the states I believe. However I'd be interested if you can interpret the patent any better.
This media reference is 10 digits however others have 11 or 12.
Here are two more examples of the raw distances, the gray table binary and then the media reference:
1.
022673352171662032460
000 011 011 101 100 010 010 111 011 001 100 001 101 101 011 000 010 011 110 101 000
67775490487
2.
574146602473467556050
111 100 110 001 110 101 101 000 011 110 100 010 110 101 100 111 111 101 000 111 000
57639171874
edit:
Some extra info:
There are some posts online describing how you can encode any text such as spotify:playlist:HelloWorld into a code however this no longer works.
I also discovered through the proxy that you can use the domain to fetch the album art of a track above the code. This suggests a closer integration of Spotify's API and this scannables url than previously thought. As it not only stores the URIs and their codes but can also validate URIs and return updated album art.
https://scannables.scdn.co/uri/800/spotify%3Atrack%3A0J8oh5MAMyUPRIgflnjwmB
Your suspicion was correct - they're using a lookup table. For all of the fun technical details, the relevant patent is available here: https://data.epo.org/publication-server/rest/v1.0/publication-dates/20190220/patents/EP3444755NWA1/document.pdf
Very interesting discussion. Always been attracted to barcodes so I had to take a look. I did some analysis of the barcodes alone (didn't access the API for the media refs) and think I have the basic encoding process figured out. However, based on the two examples above, I'm not convinced I have the mapping from media ref to 37-bit vector correct (i.e. it works in case 2 but not case 1). At any rate, if you have a few more pairs, that last part should be simple to work out. Let me know.
For those who want to figure this out, don't read the spoilers below!
It turns out that the basic process outlined in the patent is correct, but lacking in details. I'll summarize below using the example above. I actually analyzed this in reverse which is why I think the code description is basically correct except for step (1), i.e. I generated 45 barcodes and all of them matched had this code.
1. Map the media reference as integer to 37 bit vector.
Something like write number in base 2, with lowest significant bit
on the left and zero-padding on right if necessary.
57639171874 -> 0100010011101111111100011101011010110
2. Calculate CRC-8-CCITT, i.e. generator x^8 + x^2 + x + 1
The following steps are needed to calculate the 8 CRC bits:
Pad with 3 bits on the right:
01000100 11101111 11110001 11010110 10110000
Reverse bytes:
00100010 11110111 10001111 01101011 00001101
Calculate CRC as normal (highest order degree on the left):
-> 11001100
Reverse CRC:
-> 00110011
Invert check:
-> 11001100
Finally append to step 1 result:
01000100 11101111 11110001 11010110 10110110 01100
3. Convolutionally encode the 45 bits using the common generator
polynomials (1011011, 1111001) in binary with puncture pattern
110110 (or 101, 110 on each stream). The result of step 2 is
encoded using tail-biting, meaning we begin the shift register
in the state of the last 6 bits of the 45 long input vector.
Prepend stream with last 6 bits of data:
001100 01000100 11101111 11110001 11010110 10110110 01100
Encode using first generator:
(a) 100011100111110100110011110100000010001001011
Encode using 2nd generator:
(b) 110011100010110110110100101101011100110011011
Interleave bits (abab...):
11010000111111000010111011110011010011110001...
1010111001110001000101011000010110000111001111
Puncture every third bit:
111000111100101111101110111001011100110000100100011100110011
4. Permute data by choosing indices 0, 7, 14, 21, 28, 35, 42, 49,
56, 3, 10..., i.e. incrementing 7 modulo 60. (Note: unpermute by
incrementing 43 mod 60).
The encoded sequence after permuting is
111100110001110101101000011110010110101100111111101000111000
5. The final step is to map back to bar lengths 0 to 7 using the
gray map (000,001,011,010,110,111,101,100). This gives the 20 bar
encoding. As noted before, add three bars: short one on each end
and a long one in the middle.
UPDATE: I've added a barcode (levels) decoder (assuming no errors) and an alternate encoder that follows the description above rather than the equivalent linear algebra method. Hopefully that is a bit more clear.
UPDATE 2: Got rid of most of the hard-coded arrays to illustrate how they are generated.
The linear algebra method defines the linear transformation (spotify_generator) and mask to map the 37 bit input into the 60 bit convolutionally encoded data. The mask is result of the 8-bit inverted CRC being convolutionally encoded. The spotify_generator is a 37x60 matrix that implements the product of generators for the CRC (a 37x45 matrix) and convolutional codes (a 45x60 matrix). You can create the generator matrix from an encoding function by applying the function to each row of an appropriate size generator matrix. For example, a CRC function that add 8 bits to each 37 bit data vector applied to each row of a 37x37 identity matrix.
import numpy as np
import crccheck
# Utils for conversion between int, array of binary
# and array of bytes (as ints)
def int_to_bin(num, length, endian):
if endian == 'l':
return [num >> i & 1 for i in range(0, length)]
elif endian == 'b':
return [num >> i & 1 for i in range(length-1, -1, -1)]
def bin_to_int(bin,length):
return int("".join([str(bin[i]) for i in range(length-1,-1,-1)]),2)
def bin_to_bytes(bin, length):
b = bin[0:length] + [0] * (-length % 8)
return [(b[i]<<7) + (b[i+1]<<6) + (b[i+2]<<5) + (b[i+3]<<4) +
(b[i+4]<<3) + (b[i+5]<<2) + (b[i+6]<<1) + b[i+7] for i in range(0,len(b),8)]
# Return the circular right shift of an array by 'n' positions
def shift_right(arr, n):
return arr[-n % len(arr):len(arr):] + arr[0:-n % len(arr)]
gray_code = [0,1,3,2,7,6,4,5]
gray_code_inv = [[0,0,0],[0,0,1],[0,1,1],[0,1,0],
[1,1,0],[1,1,1],[1,0,1],[1,0,0]]
# CRC using Rocksoft model:
# NOTE: this is not quite any of their predefined CRC's
# 8: number of check bits (degree of poly)
# 0x7: representation of poly without high term (x^8+x^2+x+1)
# 0x0: initial fill of register
# True: byte reverse data
# True: byte reverse check
# 0xff: Mask check (i.e. invert)
spotify_crc = crccheck.crc.Crc(8, 0x7, 0x0, True, True, 0xff)
def calc_spotify_crc(bin37):
bytes = bin_to_bytes(bin37, 37)
return int_to_bin(spotify_crc.calc(bytes), 8, 'b')
def check_spotify_crc(bin45):
data = bin_to_bytes(bin45,37)
return spotify_crc.calc(data) == bin_to_bytes(bin45[37:], 8)[0]
# Simple convolutional encoder
def encode_cc(dat):
gen1 = [1,0,1,1,0,1,1]
gen2 = [1,1,1,1,0,0,1]
punct = [1,1,0]
dat_pad = dat[-6:] + dat # 6 bits are needed to initialize
# register for tail-biting
stream1 = np.convolve(dat_pad, gen1, mode='valid') % 2
stream2 = np.convolve(dat_pad, gen2, mode='valid') % 2
enc = [val for pair in zip(stream1, stream2) for val in pair]
return [enc[i] for i in range(len(enc)) if punct[i % 3]]
# To create a generator matrix for a code, we encode each row
# of the identity matrix. Note that the CRC is not quite linear
# because of the check mask so we apply the lamda function to
# invert it. Given a 37 bit media reference we can encode by
# ref * spotify_generator + spotify_mask (mod 2)
_i37 = np.identity(37, dtype=bool)
crc_generator = [_i37[r].tolist() +
list(map(lambda x : 1-x, calc_spotify_crc(_i37[r].tolist())))
for r in range(37)]
spotify_generator = 1*np.array([encode_cc(crc_generator[r]) for r in range(37)], dtype=bool)
del _i37
spotify_mask = 1*np.array(encode_cc(37*[0] + 8*[1]), dtype=bool)
# The following matrix is used to "invert" the convolutional code.
# In particular, we choose a 45 vector basis for the columns of the
# generator matrix (by deleting those in positions equal to 2 mod 4)
# and then inverting the matrix. By selecting the corresponding 45
# elements of the convolutionally encoded vector and multiplying
# on the right by this matrix, we get back to the unencoded data,
# assuming there are no errors.
# Note: numpy does not invert binary matrices, i.e. GF(2), so we
# hard code the following 3 row vectors to generate the matrix.
conv_gen = [[0,1,0,1,1,1,1,0,1,1,0,0,0,1]+31*[0],
[1,0,1,0,1,0,1,0,0,0,1,1,1] + 32*[0],
[0,0,1,0,1,1,1,1,1,1,0,0,1] + 32*[0] ]
conv_generator_inv = 1*np.array([shift_right(conv_gen[(s-27) % 3],s) for s in range(27,72)], dtype=bool)
# Given an integer media reference, returns list of 20 barcode levels
def spotify_bar_code(ref):
bin37 = np.array([int_to_bin(ref, 37, 'l')], dtype=bool)
enc = (np.add(1*np.dot(bin37, spotify_generator), spotify_mask) % 2).flatten()
perm = [enc[7*i % 60] for i in range(60)]
return [gray_code[4*perm[i]+2*perm[i+1]+perm[i+2]] for i in range(0,len(perm),3)]
# Equivalent function but using CRC and CC encoders.
def spotify_bar_code2(ref):
bin37 = int_to_bin(ref, 37, 'l')
enc_crc = bin37 + calc_spotify_crc(bin37)
enc_cc = encode_cc(enc_crc)
perm = [enc_cc[7*i % 60] for i in range(60)]
return [gray_code[4*perm[i]+2*perm[i+1]+perm[i+2]] for i in range(0,len(perm),3)]
# Given 20 (clean) barcode levels, returns media reference
def spotify_bar_decode(levels):
level_bits = np.array([gray_code_inv[levels[i]] for i in range(20)], dtype=bool).flatten()
conv_bits = [level_bits[43*i % 60] for i in range(60)]
cols = [i for i in range(60) if i % 4 != 2] # columns to invert
conv_bits45 = np.array([conv_bits[c] for c in cols], dtype=bool)
bin45 = (1*np.dot(conv_bits45, conv_generator_inv) % 2).tolist()
if check_spotify_crc(bin45):
return bin_to_int(bin45, 37)
else:
print('Error in levels; Use real decoder!!!')
return -1
And example:
>>> levels = [5,7,4,1,4,6,6,0,2,4,3,4,6,7,5,5,6,0,5,0]
>>> spotify_bar_decode(levels)
57639171874
>>> spotify_barcode(57639171874)
[5, 7, 4, 1, 4, 6, 6, 0, 2, 4, 3, 4, 6, 7, 5, 5, 6, 0, 5, 0]

How can I used Event-Based Temporal Logic in MATLAB/Simulink Stateflow?

I'm looking for a way to use event-based temporal logic in Simulink Stateflow.
Example: [State_1] --> [after(3,sec) && e] --> [State_2]
Scenario:
0 sec: State_1 is active
2 sec: e is true
5 sec: State_2 is active (only after 3s of e)
Expection: [State_1] --> (after 3s of e) --> [State_2]
Result: [State_1] --> (after 3s of State_1) --> [State_2]
Is there a solution for that? I did not found one in official MathWorks documentation (MathWorks - Control Chart Execution Using Temporal Logic)
Thank you
This is how I did it:
[State_1] --> [ e] --> [State_1_copy]--> (after 3s) --> [State_2]
combined with:
[State_1] <-- [ ~e] <-- [State_1_copy]
Entry and left action of state 1 may need to be changed depending on cases.

Fitting custom functions to data

I have a series of data, for example:
0.767838478
0.702426493
0.733858228
0.703275979
0.651456058
0.62427187
0.742353261
0.646359026
0.695630431
0.659101665
0.598786652
0.592840135
0.59199059
which I know fits best to an equation of the form:
y=ae^(b*x)+c
How can I fit the custom function to this data?
Similar question had been already asked on LibreOffice forum without a proper answer. I would appreciate if you could help me know how to do this. Preferably answers applying to any custom function rather than workarounds to this specific case.
There are multiple possible solutions for this. But one approach would be the following:
For determining the aand b in the trend line function y = a*e^(b*x) there are solutions using native Calc functions (LINEST, EXP, LN).
So we could the y = a*e^(b*x)+c taking as y-c= a*e^(b*x) and so if we are knowing c, the solution for y = a*e^(b*x) could be taken too. How to know c? One approach is described in Exponential Curve Fitting. There approximation of b, a and then c are made.
I have the main part of the delphi code from Exponential Curve Fitting : source listing translated to StarBasic for Calc. The part of the fine tuning of c is not translated until now. To-Do for you as professional and enthusiast programmers.
Example:
Data:
x y
0 0.767838478
1 0.702426493
2 0.733858228
3 0.703275979
4 0.651456058
5 0.62427187
6 0.742353261
7 0.646359026
8 0.695630431
9 0.659101665
10 0.598786652
11 0.592840135
12 0.59199059
Formulas:
B17: =EXP(INDEX(LINEST(LN($B$2:$B$14),$A$2:$A$14),1,2))
C17: =INDEX(LINEST(LN($B$2:$B$14),$A$2:$A$14),1,1)
y = a*e^(b*x) is also the function used for the chart's trend line calculation.
B19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,1)
C19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,2)
D19: =INDEX(TRENDEXPPLUSC($B$2:$B$14,$A$2:$A$14),1,3)
Code:
function trendExpPlusC(rangey as variant, rangex as variant) as variant
'get values from ranges
redim x(ubound(rangex)-1) as double
redim y(ubound(rangex)-1) as double
for i = lbound(x) to ubound(x)
x(i) = rangex(i+1,1)
y(i) = rangey(i+1,1)
next
'make helper arrays
redim dx(ubound(x)-1) as double
redim dy(ubound(x)-1) as double
redim dxyx(ubound(x)-1) as double
redim dxyy(ubound(x)-1) as double
for i = lbound(x) to ubound(x)-1
dx(i) = x(i+1) - x(i)
dy(i) = y(i+1) - y(i)
dxyx(i) = (x(i+1) + x(i))/2
dxyy(i) = dy(i) / dx(i)
next
'approximate b
s = 0
errcnt = 0
for i = lbound(dxyx) to ubound(dxyx)-1
on error goto errorhandler
s = s + log(abs(dxyy(i+1) / dxyy(i))) / (dxyx(i+1) - dxyx(i))
on error goto 0
next
b = s / (ubound(dxyx) - errcnt)
'approximate a
s = 0
errcnt = 0
for i = lbound(dx) to ubound(dx)
on error goto errorhandler
s = s + dy(i) / (exp(b * x(i+1)) - exp(b * x(i)))
on error goto 0
next
a = s / (ubound(dx) + 1 - errcnt)
'approximate c
s = 0
errcnt = 0
for i = lbound(x) to ubound(x)
on error goto errorhandler
s = s + y(i) - a * exp(b * x(i))
on error goto 0
next
c = s / (ubound(x) + 1 - errcnt)
'make y for (y - c) = a*e^(b*x)
for i = lbound(x) to ubound(x)
y(i) = log(abs(y(i) - c))
next
'get a and b from LINEST for (y - c) = a*e^(b*x)
oFunctionAccess = createUnoService( "com.sun.star.sheet.FunctionAccess" )
args = array(array(y), array(x))
ab = oFunctionAccess.CallFunction("LINEST", args)
if a < 0 then a = -exp(ab(0)(1)) else a = exp(ab(0)(1))
b = ab(0)(0)
trendExpPlusC = array(a, b, c)
exit function
errorhandler:
errcnt = errcnt + 1
resume next
end function
The formula y = beax is the exponential regression equation for LibreOffice chart trend lines.
LibreOffice exports all settings
All the settings of LibreOffice, all in the LibreOffice folder.
C:\Users\a←When installing the operating system, the name
entered.\AppData←File Manager ~ "Hidden project" to open, the AppData
folder will be displayed.\Roaming\LibreOffice
Back up the LibreOffice folder, when reinstalling, put the LibreOffice folder in its original place.
Note:
1. If the installation is preview edition, because the name of preview edition is LibreOfficeDev, so the LibreOfficeDev folder will be
displayed.
2. Formal edition can be installed together with preview edition, if both formal edition and preview edition are installed, LibreOffice
folder and LibreOfficeDev folder will be displayed.
3. To clear all settings, just delete the LibreOffice folder, then open the program, a new LibreOffice folder will be created.
LibreOffice exports a single toolbar I made
Common path
C:\Users\a←When installing the operating system, the name
entered.\AppData←File Manager ~ "Hidden project" to open, the AppData
folder will be
displayed.\Roaming\LibreOffice\4\user\config\soffice.cfg\modules\Please
connect the branch path of the individual software below.
Branch path
\modules\StartModule\toolbar\The "Start" toolbar I made is placed here.
\modules\swriter\toolbar\The "writer" toolbar I made is placed here.
\modules\scalc\toolbar\The "calc" toolbar I made is placed here.
\modules\simpress\toolbar\The "impress" toolbar I made is placed here.
\modules\sdraw\toolbar\The "draw" toolbar I made is placed here.
\modules\smath\toolbar\The "math" toolbar I made is placed here.
\modules\dbapp\toolbar\The "base" toolbar I made is placed here.
Backup file, when reinstalling, put the file in the original place.
Note:
Because of the toolbar that I made myself, default file name, will automatically use Numbering, so to open the file, can know the name of
the toolbar.
The front file name "custom_toolbar_" cannot be changed, change will cause error, behind's file name can be changed. For example:
custom_toolbar_c01611ed.xml→custom_toolbar_AAA.xml.
Do well of toolbar, can be copied to other places to use. For example: In the "writer" Do well of toolbar, can be copied to "calc"
places to use.
LibreOffice self-made symbol toolbar
Step 1 Start "Recording Macros function" Tools\Options\Advanced\Enable macro recording(Tick), in the
"Tools\Macros", the "Record Macro" option will appear.
Step 2 Recording Macros Tools\Macros\Record Macro→Recording action (click "Ω" to enter symbol→select symbol→Insert)→Stop
Recording→The name Macros stored in "Module1" is Main→Modify Main
name→Save.
Step 3 Add item new toolbar Tools\Customize\Toolbar→Add→Enter a name (example: symbol)→OK, the new toolbar will appear in the top
left.
Step 4 Will Macros Add item new toolbar Tools\Customize\Toolbar\Category\Macros\My
Macros\Standard\Module1\Main→Click "Main"→Add item→Modify→Rename (can
be named with symbol)→OK→OK.

Prolog - Summing numbers

I am new in prolog. I have found breadth first search program in the internet which is search for routes between cities. I want to extend the program to store and calculate distances. But I can't figure out how to do it.
The original code:
move(loc(omaha), loc(chicago)).
move(loc(omaha), loc(denver)).
move(loc(chicago), loc(denver)).
move(loc(chicago), loc(los_angeles)).
move(loc(chicago), loc(omaha)).
move(loc(denver), loc(los_angeles)).
move(loc(denver), loc(omaha)).
move(loc(los_angeles), loc(chicago)).
move(loc(los_angeles), loc(denver)).
bfs(State, Goal, Path) :-
bfs_help([[State]], Goal, RevPath), reverse(RevPath, Path).
bfs_help([[Goal|Path]|_], Goal, [Goal|Path]).
bfs_help([Path|RestPaths], Goal, SolnPath) :-
extend(Path, NewPaths),
append(RestPaths, NewPaths, TotalPaths),
bfs_help(TotalPaths, Goal, SolnPath).
extend([State|Path], NewPaths) :-
bagof([NextState,State|Path],
(move(State, NextState), not(member(NextState, [State|Path]))),
NewPaths), !.
extend(_, []).
Output:
1 ?- bfs(loc(omaha), loc(chicago), X).
X = [loc(omaha), loc(chicago)] ;
X = [loc(omaha), loc(denver), loc(los_angeles), loc(chicago)] ;
false.
I have tried this:
bfs(A,B,Path,D) :-
bfs(A,B,Path),
path_distance(Path,D).
path_distance([_], 0).
path_distance([A,B|Cs], S1) :-
move(A,B,D),
path_distance(Cs,S2),
S1 is S2+D.
bfs(A,B, Path) :-
bfs_help([[A]], B, RevPath), reverse(RevPath, Path).
bfs_help([[Goal|Path]|_], Goal, [Goal|Path]).
bfs_help([Path|RestPaths], Goal, SolnPath) :-
extend(Path, NewPaths),
append(RestPaths, NewPaths, TotalPaths),
bfs_help(TotalPaths, Goal, SolnPath).
extend([State|Path], NewPaths) :-
bagof([NextState,State|Path],
(move(State, NextState,_), not(member(NextState, [State|Path]))),
NewPaths), !.
extend(_, []).
Output:
5 ?- bfs(loc(omaha), loc(chicago), X,D).
false.
What i want:
1 ?- bfs(loc(omaha), loc(chicago), X, D).
X = [loc(omaha), loc(chicago)] ;
D = 1
X = [loc(omaha), loc(denver), loc(los_angeles), loc(chicago)] ;
D = 6
false.
Please anyone help me to solve this problem!
Sorry for my english.
It seems cheapest to define a relation path_distance/2. That is not the most elegant way,
but it should serve your purpose:
bfs(A,B,Path,D) :-
bfs(A,B,Path),
path_distance(Path,D).
path_distance([_], 0).
path_distance([A,B|Cs], S1) :-
move(A,B,D),
path_distance([B|Cs],S2),
S1 is S2+D.
You might also reconsider bfs/3 a bit. The query
?- bfs(A,B, Path).
Gives rather odd results.
Both move/2 and move/3 are now used. Thus:
move(A,B) :-
move(A,B,_).
move(loc(omaha), loc(chicago),1).
move(loc(omaha), loc(denver),2).
move(loc(chicago), loc(denver),1).
move(loc(chicago), loc(los_angeles),2).
move(loc(chicago), loc(omaha),1).
move(loc(denver), loc(los_angeles),2).
move(loc(denver), loc(omaha),1).
move(loc(los_angeles), loc(chicago),2).
move(loc(los_angeles), loc(denver),3).

emacs minor mode to expand latex

when i take notes, i like to write in "ascii math".
e.g. definition of continuous
all eps > 0, exist del > 0 . |f(x)-f(y)| < eps . |x-y| < del
i would like this to automatically inline unicode, as i type
Ɐ ε > 0, ∃ δ > 0 . |f(x)-f(y)| < ε . |x-y| < δ
1) does this exist, in a minor mode and independent of any latex major mode?
2) how do i substitute "tokens" in emacs. e.g. the regex "\W+all\W+" => "Ɐ" (since writing " all " is easier than "\forall")?