## Getting geo-tagged information from photos for blogging

| categories: | tags: | View Comments

I am kind of late to this game, but recently I turned on location services for the camera on my phone. That means the location of the photo is stored in the photo, and we can use that to create urls to the photo location in a map for example. While traveling, I thought this would be a good application for org-mode to add functionality to documents with photos in them, e.g. to be able to click on them to see where they are from, or to automate creation of html pages with links to maps, etc. In this post I explore some ways to achieve those ideas. What I would like is a custom org link that shows me a thumbnail of the image, and which exports to show the image in an html file with a link to a pin on Google maps.

So, let's dig in. Imagemagick provides an identify command that can extract the information stored in the images. Here we consider just the GPS information. I some pictures on a recent vacation, and one is unimaginatively named IMG_1759.JPG. Let's see where it was taken.

identify -verbose IMG_1759.JPG | grep GPS

 exif:GPSAltitude: 14426/387 exif:GPSAltitudeRef: 0 exif:GPSDateStamp: 2018:06:30 exif:GPSDestBearing: 11767/80 exif:GPSDestBearingRef: T exif:GPSImgDirection: 11767/80 exif:GPSImgDirectionRef: T exif:GPSInfo: 1632 exif:GPSLatitude: 22/1, 11/1, 614/100 exif:GPSLatitudeRef: N exif:GPSLongitude: 159/1, 40/1, 4512/100 exif:GPSLongitudeRef: W exif:GPSSpeed: 401/100 exif:GPSSpeedRef: K exif:GPSTimeStamp: 3/1, 44/1, 3900/100

The interpretation here is that I took that photo at latitude 22° 11' 6.14" N, and longitude 159° 40' 45.12" W. Evidently I was moving at 4.01 in some unit; I can confirm that I was at least moving, I was on a ship when I took that picture, and it was moving.

According to this you can make a url to a Google maps pin in satellite picture mode that looks like this: http://maps.google.com/maps?q=22 11 6.14N,159 40 45.12W&t=k. It doesn't seem possible to set the zoom in this url (at least setting the zoom doesn't do anything, and I didn't feel like trying all the other variations that are reported to sometimes work). I guess that is ok for now, it adds some suspense that you have to zoom out to see where the image is in some cases.

We need a little function to take an image file and generate that link. We have to do some algebra on the latitude and longitude which are stored as integers with a division operator. I am going to pipe this through an old unix utility called bc mostly because it is simple, and I won't have to parse it much. bc is a little archaic, you have to set the scale first, which tells it how many decimal places to output. The degrees and minutes are integers, so we will have to deal with that later.

echo "scale=2; 614/100" | bc

6.14



Here is our function. I filter out the lines with GPS in them into an a-list. Then, I grab out the specific quantities I want and construct the url. There is a little hackery since it appears the degrees and minutes should be integers in the url formulation used here, so I convert them to numbers and then take the floor. The function is a little longer than I thought, but it isn't too bad I guess. It is a little repetitious, but not enough to justify refactoring.

(defun iphoto-map-url (fname)
(let* ((gps-lines (-keep (lambda (line)
(when (s-contains? "GPS" line) (s-trim line)))
(process-lines "identify" "-verbose" fname)))
(gps-alist (mapcar (lambda (s) (s-split ": " s t))  gps-lines))
(latitude (mapcar
(lambda (s)
(s-trim (shell-command-to-string
(format "echo \"scale=2;%s\" | bc" s))))
(s-split "," (cadr (assoc "exif:GPSLatitude" gps-alist)))))
(longitude (mapcar
(lambda (s)
(s-trim
(shell-command-to-string
(format "echo \"scale=2;%s\" | bc" s))))
(s-split "," (cadr (assoc "exif:GPSLongitude" gps-alist)))))
(s-format "http://maps.google.com/maps?q=$0$1 $2$3,$4$5 $6$7&t=k"
'elt
(list
(floor (string-to-number (nth 0 latitude)))
(floor (string-to-number (nth 1 latitude)))
(nth 2 latitude)
latitude-ref
(floor (string-to-number (nth 0 longitude)))
(floor (string-to-number (nth 1 longitude)))
(nth 2 longitude)
longitude-ref))))

iphoto-map-url



Here is the function in action, making the url.

(iphoto-map-url "IMG_1759.JPG")

http://maps.google.com/maps?q=22 11 6.14N,159 40 45.12W&t=k



It is kind of slow, but that is because the identify shell command is kind of slow when you run it with the -verbose tag. Now, I would like the following things to happen when I publish it to html:

1. I want the image wrapped in an img tag inside a figure environment.
2. I want the image to by hyperlinked to its location in Google maps.

In the org file, I want a thumbnail overlay on it, so I can see the image while writing, and I want it to toggle like other images. I use an iPhone to take the photos, so we will call it an iphoto link.

Here is the html export function I will use. It is a little hacky that I hard code the width in at 300 pixels, but I didn't feel like figuring out how to get it from an #+attr_html line right now. It probably requires a filter function where you have access to the actual org-elements. I put the url to the image location in a figure caption here.

(defun iphoto-export (path desc backend)
(cond
((eq 'html backend)
(format "<figure>
<img src=\"%s\" width=\"300\">
%s
</figure>"
path
(format "<figcaption>%s <a href=\"%s\">map</a></figcaption>"
(or desc "")
(iphoto-map-url path))))))

iphoto-export



Ok, the last detail I want is to put an image overlay on my new link so I can see it. I want this to work with org-toggle-inline-images so I can turn the images on and off like regular image links with C-c C-x C-v. This function creates overlays as needed, and ties into the org-inline-image-overlays so they get deleted on toggling. We have to advise the display function to redraw these, which we clumsily do by restarting the org font-lock machinery which will redraw the thumbnails from the activate-func property of the links. I also hard code the thumbnail width in this function, when it could be moved out to a variable or attribute.

(defun iphoto-thumbnails (start end imgfile bracketp)
(unless bracketp
(when (and
;; it is an image
(org-string-match-p (image-file-name-regexp) imgfile)
;; and it exists
(f-exists? imgfile)
;; and there is no overlay here.
(not (ov-at start)))
(setq img (create-image (expand-file-name imgfile)
'imagemagick nil :width 300
:background "lightgray"))
(setq ov (make-overlay start end))
(overlay-put ov 'display img)
(overlay-put ov 'face 'default)
(overlay-put ov 'org-image-overlay t)
(overlay-put ov 'modification-hooks
(list
(lambda (&rest args)
(org-display-inline-remove-overlay ,ov t ,start ,end))))
(push ov org-inline-image-overlays))))

(defun iphoto-redraw-thumbnails (&rest args)
(org-restart-font-lock))

;; this redisplays these thumbnails on image toggling


Next, we define the link with a follow, export, tooltip and activate-func (which puts the overlay on).

(org-link-set-parameters
"iphoto"
:follow (lambda (path) (browse-url (iphoto-map-url path)))
:export 'iphoto-export
:help-echo "Click me to see where this photo is on a map."
:activate-func 'iphoto-thumbnails)


So finally, here is the mysterious image.

Now, in org-mode, I see the image in an overlay, and I can toggle it on and off. If I click on the image, it opens a browser to Google maps with a pin at the spot I took it. When I export it, it wraps the image in a <figure> tag, and puts a url in the caption to the map. If you click on it, and zoom out, you will see this is a picture of the Nāpali Coast on Kauai in Hawaii, and I was in fact out at sea when I took the picture. It was spectacular. Here is another one. This one is a little more obvious with the zoom. Here, I was on land. Since this link is bracketed, it does not show the overlay however in the org-file.

Overall, this was easier than I expected. It might be faster to outsource reading the exif data to some dedicate library, perhaps in python that would return everything you want in an easy to parse json data structure. The speed of computing the url is only annoying when you export or click on the links though.

I didn't build in any error handling, e.g. if you do this on a photo with no GPS data it will probably not handle it gracefully. I also haven't tested this on any other images, e.g. south of the equator, from other cameras, etc. I assume this exif data is pretty standard, but it is a wild world out there… It would still be nice to find a way to get a string representing the nearest known location somehow, that would help the caption be more useful.

There is one little footnote to speak of, and that is I had to do a little hackery to get this to work with my blog machinery. You can see what it is in the org-source, I buried it in a noexport subheading, because it isn't that interesting in the grand scheme of things. It was just necessary because I export these org-files to blogofile, which then builds the html pages, instead of just exporting them. The images have to be copied to a source directory, and paths changed in the html to point to them. See, boring stuff. Otherwise, the code above should be fine for regular org and html files! Now, my vacation is over so it is time to get back to work.

org-mode source

Org-mode version = 9.1.13

## f-strings in emacs-lisp

| categories: | tags: | View Comments

I am a big fan of f-strings in Python 3. They let you put variable names and expressions in a string template that get expanded to create new strings. Here is a simple example of using those:

username = 'John Kitchin'
somevar = 5**0.5

John Kitchin                  2.24



String formatting in emacs-lisp is by comparison not as fun and easy. Out of the box we have:

(let ((username "John Kitchin")
(somevar (sqrt 5)))

John Kitchin                  2.24



That is still three lines of code, but it is ugly and hard to read like the old python code:

print('%-30s%1.2f' % (username, somevar))

John Kitchin                  2.24



My experience has shown that this gets harder to figure out as the strings get larger, and f-strings are easier to read.

The wonderful 's library provides some salvation for emacs-lisp, if you don't want the format fields. You can refer to variables in a lexical environment like this.

(let ((username "John Kitchin")
(somevar (sqrt 5)))
(s-lex-format "${username}${somevar}"))

John Kitchin2.23606797749979



Today, I decided to do something about this, and wrote this little macro. It is a variation on s-lex-format that introduces a slightly new syntax. You can now add an optional format field separated from the variable name by a space.

(defmacro f-string (fmt)
"Like s-format' but with format fields in it.
FMT is a string to be expanded against the current lexical
environment. It is like what is used in s-lex-format', but has
an expanded syntax to allow format-strings. For example:
${user-full-name 20s} will be expanded to the current value of the variable user-full-name' in a field 20 characters wide. (let ((f (sqrt 5))) (f-string \"${f 1.2f}\"))
will render as: 2.24
This function is inspired by the f-strings in Python 3.6, which I
enjoy using a lot.
"
(let* ((matches (s-match-strings-all"${\$$?3:\\(?1:[^} ]+\$$ *\$$?2:[^}]*\$$\\)}" fmt)) (agetter (cl-loop for (m0 m1 m2 m3) in matches collect (cons ,m3 (format (format "%%%s" (if (string= ,m2 "") (if s-lex-value-as-lisp "S" "s") ,m2)) (symbol-value (intern ,m1))))))) (s-format ,fmt 'aget (list ,@agetter))))  f-string  Here it is in action. (let ((username "John Kitchin") (somevar (sqrt 5))) (f-string "${username -30s}${somevar 1.2f}"))  John Kitchin 2.24  It still lacks some of the capability of f-strings in python, e.g. in Python, arguments inside the template to be expanded get evaluated. The solution used above is too simple for that, since it just used a regexp and is limited to the value of variables in the lexical environment. print(f'{5**0.5:1.3f}')  2.236  Nevertheless, this simple solution matches what I do most of the time anyway, so I still consider it an improvement! Copyright (C) 2018 by John Kitchin. See the License for information about copying. org-mode source Org-mode version = 9.1.13 Read and Post Comments ## Making it easier to extend the export of org-mode links with generic functions | categories: | tags: | View Comments I am a big fan of org-mode links. Lately, I have had a need to modify how some links are exported, e.g. defining new exports for different backends, or fine-tuning a particular backend. This can be difficult, depending on how the link was set up. Here is a typical setup I am used to using, where the different options for the backends are handled in a conditional statement in a single function. I will just use a link that just serves to illustrate the issues here. These links are just sytactic sugar for markup, they don't do anything else. We start with an example that just converts text to italic text for different backends like html or latex. (defun italic-link-export (path desc backend) (cond ((eq 'html backend) (format "<em>%s</em>" path)) ((eq 'latex backend) (format "\\textit{%s}" path)) ;; fall-through case for everything else (t path))) (org-link-set-parameters "italic" :export 'italic-link-export)   :export italic-link-export (org-export-string-as "italic:text" 'html t)  <p> <em>text</em></p>  (org-export-string-as "italic:text" 'latex t)  \textit{text}  This falls through though to the default case. (require 'ox-md) (org-export-string-as "italic:text" 'md t)   # Table of Contents text  The point I want to make here is that this is not easy to extend as a user. You have to either modify the italic-link-export function, advise it, or monkey-patch it. None of these are especially nice. I could define italic-link-export in a way that it retrieves the function to use from an alist or hash-table using the backend, but then you have to do two things to modify the behavior: define a backend specific function and register it in the lookup variable. It is also possible to just look up a function by a derived symbol, e.g. using fboundp, and then using funcall to execute it. This looks something like this: ;; a user definable function for exporting to latex (defun italic-link-export-latex (path desc backend) (format "\\textit{%s}" path)) ;; generic export function that looks up functions or defaults to (defun italic-link-exporter (path desc backend) "Run italic-link-export-BACKEND' if it exists, or return path." (let ((func (intern-soft (format "italic-link-export-%s" backend)))) (if (fboundp func) (funcall func path desc backend) path)))  This has some indirection, but allows you to just define new functions to add new export backends, or replace single backend exports. It isn't bad, but there is room for improvement. In this comment in org-ref, I saw a new opportunity to address this issue using generic functions in elisp! The idea is to define a generic function that handles the general export case, and then define additional functions for each specific backend based on the signature of the export function. I will switch to bold markup for this. (cl-defgeneric bold-link-export (path desc backend) "Generic function to export a bold link." path) ;; this one runs when the backend is equal to html (cl-defmethod bold-link-export ((path t) (desc t) (backend (eql html))) (format "<b>%s</b>" path)) ;; this one runs when the backend is equal to latex (cl-defmethod bold-link-export ((path t) (desc t) (backend (eql latex))) (format "\\textit{%s}" path)) (org-link-set-parameters "bold" :export 'bold-link-export)   :export bold-link-export Here it is in action: (org-export-string-as "some bold:text" 'html t)  <p> some <b>text</b></p>  (org-export-string-as "some bold:text" 'latex t)  This uses the generic function. (require 'ox-md) (org-export-string-as "some bold:text" 'md t)   # Table of Contents some text  The syntax for defining the generic function is pretty similar to a regular function. The specific methods are a little different since they have to provide the specific "signature" that triggers each method. Here we only differentiate on the type of the backend. It is nice these are all separate functions though. It makes it trivial to add new ones, and less intrusive to replace in my opinion. Generic functions have many other potential applications to replace functions that use lots of conditions to control flow, with a fall-through option at the end. You can learn more about them here: https://www.gnu.org/software/emacs/manual/html_node/elisp/Generic-Functions.html. There is a lot more to them than I have illustrated here. Copyright (C) 2018 by John Kitchin. See the License for information about copying. org-mode source Org-mode version = 9.1.13 Read and Post Comments ## Overloading mathematical operators in elisp | categories: | tags: | View Comments ## Table of Contents In Python I am used to some simple idioms like this: print([1, 2, 3] * 2) print("ab" * 3)  [1, 2, 3, 1, 2, 3] ababab There is even such fanciness as defining operators for objects, as long as they have the appropriate dunder methods defined: class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "Point ({}, {})".format(self.x, self.y) def __mul__(self, a): return Point(self.x * a, self.y * a) def __rmul__(self, a): return Point(self.x * a, self.y * a) p = Point(1, 1) print(p * 2) print(3 * p)  Point (2, 2) Point (3, 3) Out of the box, these things are not possible in elisp. Operators like * in elisp only take numbers or markers. We have a few options to change this. The worst option is to simply redefine these functions. That is bad because it is not reversible. We could define new functions that have the behavior we want, but then we lose the semantic meaning of "*" that we were aiming for. A better option is to advise these functions. This is reversible, because you can later unadvise them. Today we look at some strategies to do this. We will use "around" advise because it will let us bypass the original intent of the function when we want to, or use it when we do. First, we create a function that will be the advice and add it to the * function. This first draft won't actually change the behavior of *; if all the args are numbers or markers it will simply use the original function as before. (require 'dash) (defun *--*-around (orig-fun &rest args) "if every arg is a number do *, else do something else." (cond ((-every? (lambda (x) (or (numberp x) (markerp x))) args) (apply orig-fun args)))) (advice-add '* :around #'*--*-around)  Let's just confirm (* 1 2 3)  6  Now, we can start modifying our function to handle some other cases. Let's do the list and string first. The * function is variadic, but in these cases it makes sense to limit to two arguments. We need two cases for each type since we can write (* 2 list) or (* list 2). We also should create a fall-through case that raises an error to alert us we can't multiply things. (defun *--*-around (orig-fun &rest args) "if every arg is a number do *, else do something else." (cond ;; The original behavior ((-every? (lambda (x) (or (numberp x) (markerp x))) args) (apply orig-fun args)) ;; create repeated copies of list ((and (listp (first args)) (integerp (second args)) (= 2 (length args))) (loop for i from 0 below (second args) append (copy-list (first args)))) ((and (integerp (first args)) (listp (second args)) (= 2 (length args))) (loop for i from 0 below (first args) append (copy-list (second args)))) ;; Make repeated string ((and (stringp (first args)) (integerp (second args)) (= 2 (length args))) (loop for i from 0 below (second args) concat (first args))) ((and (integerp (first args)) (stringp (second args)) (= 2 (length args))) (loop for i from 0 below (first args) concat (second args))) (t (error "You cannot * %s" args))))  *--*-around  Here is the new advice in action. (list (* '(a b) 2) (* 2 '(c d)) (* 2 "ab") (* "cd" 2))   (a b a b) (c d c d) abab cdcd That captures the spirit of overloading * for lists and strings. What about that object example? We have to make some assumptions here. Python looks for an uses a dunder mul method. We will assume a double dash method (–mul–) in a similar spirit. We have to modify the advice one final time. We just add a condition to check if one of the arguments is an eieio-object, and then call the –mul– function on the arguments. (defun *--*-around (orig-fun &rest args) "if every arg is a number do *, else do something else." (cond ;; The original behavior ((-every? (lambda (x) (or (numberp x) (markerp x))) args) (apply orig-fun args)) ;; create repeated copies of list ((and (listp (first args)) (integerp (second args)) (= 2 (length args))) (loop for i from 0 below (second args) append (copy-list (first args)))) ((and (integerp (first args)) (listp (second args)) (= 2 (length args))) (loop for i from 0 below (first args) append (copy-list (second args)))) ;; Make repeated string ((and (stringp (first args)) (integerp (second args)) (= 2 (length args))) (loop for i from 0 below (second args) concat (first args))) ((and (integerp (first args)) (stringp (second args)) (= 2 (length args))) (loop for i from 0 below (first args) concat (second args))) ;; Handle object ((or (and (eieio-object-p (first args)) (numberp (second args))) (and (numberp (first args)) (eieio-object-p (second args)))) (apply '--mul-- args)) (t (error "You cannot * %s" args))))  *--*-around  Now, we can define a class and the –mul– function and show that our overloaded * function works. Note we can define two signatures of –mul– so it is not necessary to define an –rmul– in this case as it was with Python (although we still create two functions in the end). (require 'eieio) (defclass Point () ((x :initarg :x) (y :initarg :y))) (cl-defmethod --mul-- ((p Point) a) (Point :x (* (oref p :x) a) :y (* (oref p :y) a))) (cl-defmethod --mul-- (a (p Point)) (Point :x (* (oref p :x) a) :y (* (oref p :y) a))) (cl-defmethod --str-- ((p Point)) (format "Point (%s, %s)" (oref p :x) (oref p :y))) (let ((P (Point :x 1 :y 1))) (list (--str-- (* P 2)) (--str-- (* 3 P))))   Point (2, 2) Point (3, 3) That is pretty awesome. Before going on, here is how you remove the advice: (advice-remove '* '*--*-around)  This example has been pretty instructive. You have to handle overloading for all the intrinsic types. We did lists and strings here; you might also consider vectors. For objects, it looks like we can at least try using a generic method like –mul–. One detail I neglected to consider here is that * is natively variadic. For these special cases, we did not implement variadic versions. This isn't a feature of Python which uses infix notation, so every call is with two arguments. In some cases it might make sense to support variadic args, but that seems like a generally challenging thing to do. While (* "a" 2 3) might be expected to create a string of "aaaaaa", (* "a" 2 '(3)) doesn't make sense at all. It would be straightforward to extend this to other operators like '+ to concatenate strings, lists and vectors, or '- to remove chars or elements, including extensions to objects using double-dash functions like –add–, –subtract–, etc. Another nice idea might be to advise print to use –str– on objects. On the surface this looks useful so far. Python defines a lot of dunder methods that cover all kinds of scenarios including logical comparisons, bit shifting, mod, incrementing operators, casting, comparisons, right/left operations, indexing and assignment, length and others. That would be a lot of advices. This approach is moderately tedious to expand though; you have to keep adding conditional cases. An alternative to the big conditional statement used in the advice might be the use of a generic function. With this approach we define a generic function that just does multiplication by default. Then we define specific cases with specific signatures that are used for lists, strings, objects, etc. That is basically all our conditional above was doing, matching signatures and executing a chunk of code accordingly. Here is our default case that does the original behavior. We still use advice to apply the function. (cl-defgeneric generic-multiply (orig-fun &rest args) "Generic multiply for when no specific case exists." (apply orig-fun args)) (defun *--*-around-generic (orig-fun &rest args) (apply 'generic-multiply orig-fun args)) (advice-add '* :around #'*--*-around-generic)  That should just work as usual for regular multiplication. (* 1 2 3 4)  24  Sure enough it does. Now, we can define a specific method for a string. We need a specialized method for each signature, e.g. pre and post multiplication. (cl-defmethod generic-multiply ((orig-fun subr) (s string) (n integer)) (loop for i from 0 below n concat s)) (cl-defmethod generic-multiply ((orig-fun subr) (n integer) (s string)) (loop for i from 0 below n concat s)) (list (* "Ac" 2) (* 2 "Ad"))   AcAc AdAd That works fine, and we did not have to modify our original advice function at all! Next the list: (cl-defmethod generic-multiply ((orig-fun subr) (L list) (n integer)) (loop for i from 0 below n append (copy-list L))) (cl-defmethod generic-multiply ((orig-fun subr) (n integer) (L list)) (loop for i from 0 below n append (copy-list L))) (list (* '(1 2) 2) (* 2 '(3 4)))   1 2 1 2 3 4 3 4 That also works fine. Last, our class example. This should work on all objects I think (unless there is some way to make classes that do not inherit the default superclass). (cl-defmethod generic-multiply ((orig-fun subr) (n integer) (obj eieio-default-superclass)) (--mul-- n obj)) (cl-defmethod generic-multiply ((orig-fun subr) (obj eieio-default-superclass) (n integer)) (--mul-- n obj)) (let ((P (Point :x 1 :y 1))) (list (--str-- (* P 2)) (--str-- (* 3 P))))   Point (2, 2) Point (3, 3) This is a much better approach to extending the multiplication operator! If I continue this path in the future I would probably take this one. This could be useful to make elisp more like some more popular contemporary languages like Python, as well as to add linear algebra like notation or mathematical operations on objects in elisp. It kind of feels like these operations ought to be generic functions to start with to make this kind of overloading easier from the beginning. Functions like "*" are currently defined in the C source code though, maybe for performance reasons. It is not obvious what the consequences of making them generic might be. ## 1 Addendum Christopher Wellons pointed out an important limitation of advice: they don't work on byte-compiled functions. Let's see what he means. Here is a simple function that will just multiply a Point object by an integer: (defun to-be-bytten (p1 n) (* p1 n))  to-be-bytten  Here it is in action, and here it works fine. (to-be-bytten (Point :x 1 :y 1) 2)  [eieio-class-tag--Point 2 2]  Now, let's byte-compile that function and try it again: (byte-compile 'to-be-bytten) (condition-case err (to-be-bytten (Point :x 1 :y 1) 2) ((error r) (message "Doh! Christopher was right. It did not work...\n%s" err)))  Doh! Christopher was right. It did not work... (wrong-type-argument number-or-marker-p [eieio-class-tag--Point 1 1])  So the advice is pretty limited since most of the functions in Emacs core are likely to be byte-compiled, and it might mean you have to redefine * completely, or define some new function that looks like it. Too bad, the advice was pretty easy! Copyright (C) 2017 by John Kitchin. See the License for information about copying. org-mode source Org-mode version = 9.0.7 Read and Post Comments ## Linear algebra in Emacs using MKL and dynamic modules | categories: | tags: | View Comments ## Table of Contents In a previous post I integrated some linear algebra into Emacs using the GNU Scientific library and a dynamic module. In this post, I use a similar approach that uses the Intel MKL library in conjunction with some helper elisp functions to mimic the array broadcasting features in Numpy. I thought this might be easier and lead to at least a complementary set of functionalities. Note: I had to follow the directions here to disable some security feature on my Mac so that it would use the MKL libraries. Thanks Apple. It is convenient to use vectors for the representation of arrays in Emacs because there are nice functions in the emacs-module.h for accessing vector properties. Also vectors sound closer to an array than a list. So what about array broadcasting, e.g. the way numpy lets you multiply a 2d array with a 1d array? If you multiply two arrays with size (m1, n1) * (m2, n2), it is required that the number of columns in the first array (n1) be equal to the number of rows in the second one (m2), and the resulting size of the array product will be (m1, n2). What should happen though when we have 1d array? This is neither a row or column vector itself, but we can treat as either one if we choose too. For example the vector [1 2 3] can be thought of as an array with the shape (1, 3), e.g. a single row with three columns, or (3, 1), i.e. three rows in a single column. We will build this capability into the module for convenience. I still find it moderately tedious to write c functions that take emacs arguments, transform them to c arguments, do some c computations, and convert the results back to emacs values. So, we only implement one c function for this that multiplies two 2d arrays together using the cblas_dgemm routine in the MKL library. Then, we will create a complementary elisp library that will provide some additional functionality to get the shapes of vector arrays, dimensions, and allow us to multiply 1d and 2d vectors together the same way Numpy does array broadcasting. The dynamic module code is listed in The module code. The elisp code is listed in Elisp helper functions. In the following sections we just demonstrate how to use the results. ## 1 Convenience functions to get array properties I found it convenient to do array shape and dimension analysis in elisp before sending arrays to the dynamic module. The shape of an array is just the number of elements in each dimension. Here we look at a 2× 3 array. (vector-shape [[1 2 3] [3 4 5]])  [2 3]  You see it returns a vector showing two rows and three columns. There are two convenience commands to get the number of rows (vector-nrows) and columns (vector-ncols). Here is one of them. (vector-ncols [[1 2 3] [3 4 5]])  3  ## 2 Matrix multiplication The main problem we want to calculate is the matrix multiplication $$A\cdotB$$ where $$A$$ and $$B$$ are either 1d vectors or 2d arrays. Here we examine several representative cases of matrix multiplication. ### 2.1 1d * 1d This is a simple dot-product that is actually calculated in elisp. $$[1 1 1] \cdot [2 2 2] = 6$$ (matrix-multiply [1 1 1] [2 2 2])  6.0  Note we get a float. That is because we initialize the sum with 0.0 to be consistent with all the other cases which are done with floats. dgemm is a double routine in MKL, which means it should return floats. Internally in the module, we cast all numbers as doubles for the multiplication. ### 2.2 2d * 1d This is a matrix multiplication that is typically like $$A b$$ where $$b$$ is a column vector. We return a 1d array as a result, rather than a 2d array of nrows and 1 column. $\left[\begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array}\right] \left [ \begin{array}{c} 1 \\ 1 \end{array}\right] = \left[\begin{array}{c}3\\7\end{array}\right]$ (let ((A [[1 2] [3 4]]) (b [1 1])) (matrix-multiply A b))  [3.0 7.0]  ### 2.3 1d * 2d This case is $$b A$$ where $$b$$ is a row vector. For example: $\left[\begin{array}{cc}1 & 1\end{array}\right] \left[\begin{array}{cc} 1 & 2\\ 3 & 4\end{array}\right] = \left[\begin{array}{cc} 4 & 6 \end{array}\right ]$ (matrix-multiply [1 1] [[1 2] [3 4]])  [4.0 6.0]  As with the previous case, we return a 1d vector result rather than a 2d array with 1 row and ncolumns. ### 2.4 2d * 2d Finally we have the case of $$A B$$. The number of columns in A must be the same as the number of rows in B, and the result has a size that is the number of rows in A and the number of columns in B. Here is one example: $\left[\begin{array}{cc} 0 & 1\\ 0 & 0\end{array}\right] \left[\begin{array}{cc} 0 & 0\\ 1 & 0\end{array}\right] = \left[\begin{array}{cc} 1 & 0\\ 0 & 0\end{array}\right]$ (matrix-multiply [[0 1] [0 0]] [[0 0] [1 0]])  [[1.0 0.0] [0.0 0.0]]  This example is adapted from here. The correct answer is at the bottom of that page, and shown here. $\left[\begin{array}{cccc} 1 & 2 & -2 & 0 \\ -3 & 4 & 7 & 2 \\ 6 & 0 & 3 & 1\end{array}\right] \left[\begin{array}{cc} -1 & 3 \\ 0 & 9 \\ 1 & -11 \\ 4 & -5 \end{array}\right] = \left[\begin{array}{cc} -3 & 43 \\ 18 & -60 \\ 4 & -5\end{array}\right]$ For readability we use temporary variables here, and pretty-print the result. (let ((A [[1 2 -2 0] [-3 4 7 2] [6 0 3 1]]) (B [[-1 3] [0 9] [1 -11] [4 -5]])) (pp (matrix-multiply A B)))  [[-3.0 43.0] [18.0 -60.0] [1.0 -20.0]]  So, all these example work as we expect. The elisp function for matrix-multiply does a lot of work for you to make these cases work, including error checking for dimensional consistency. ## 3 Summary thoughts It was not any easier to write this dynamic module than the previous one I used with the Gnu Scientific Library. The approach and code are remarkably similar. In one way the GSL was easier to use; it worked out of the box, whereas I had to fiddle with a security option in my OS to get it to run MKL! My Anaconda Python distribution must get around that somehow since it ships with an MKL compiled Numpy and scipy. The idea of using elisp for analysis of the inputs and making sure they are correct is a good one and helps prevent segfaults. Of course it is a good idea to write defensive c-code to avoid that too. Overall, this is another good example of expanding the capabilities of Emacs with a dynamic module. ## 4 The module code The c-code is loosely adapted from https://software.intel.com/en-us/node/529735. We do not implement the full dgemm behavior which is able to calculate $$C = \alpha A * B + \beta*C$$. We set α=1, and β=0 in this example. We should do some dimension checking here, but it is easier to do it in emacs in a helper function. As long as you use the helper function there should not be an issue, but it is possible to segfault Emacs if you use the module function incorrectly. #include "emacs-module.h" #include "emacs-module-helpers.h" #include <mkl.h> int plugin_is_GPL_compatible; emacs_value Fmkl_dgemm (emacs_env *env, ptrdiff_t nargs, emacs_value args[], void *data) { double *A, *B, *C; int m, n, k, i, j; double alpha = 1.0; double beta = 0.0; // These will be 2d vectors emacs_value M0 = args[0]; // array 1 - A (m x k) emacs_value M1 = args[1]; // array 2 - B (k x n) // I need to get the number of rows and columns of each one. m = env->vec_size(env, M0); k = 0; // We assume that we have a 2d array. emacs_value el1 = env->vec_get (env, M0, 0); k = env->vec_size(env, el1); // Now we know A has dimensions (m, k) emacs_value el2 = env->vec_get (env, M1, 0); n = env->vec_size(env, el2); // Now we know M1 had dimensions (k, n) // Now we have to build up arrays. // We are looking at a * b = c A = (double *)mkl_malloc( m*k*sizeof( double ), 64 ); B = (double *)mkl_malloc( k*n*sizeof( double ), 64 ); C = (double *)mkl_malloc( m*n*sizeof( double ), 64 ); if (A == NULL || B == NULL || C == NULL) { printf( "\n ERROR: Can't allocate memory for matrices. Aborting... \n\n"); mkl_free(A); mkl_free(B); mkl_free(C); return 1; } //populate A emacs_value row, ij; for (int i = 0; i < m; i++) { row = env->vec_get(env, M0, i); for (int j = 0; j < k; j++) { // get M0[i, j] ij = env->vec_get(env, row, j); A[k * i + j] = extract_double(env, ij); } } // populate B for (int i = 0; i < k; i++) { row = env->vec_get(env, M1, i); for (int j = 0; j < n; j++) { // get M0[i, j] ij = env->vec_get(env, row, j); B[n * i + j] = extract_double(env, ij); } } // initialize C. The solution will have dimensions of (rows1, cols2). for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { C[n * i + j] = 0.0; } } // the multiplication is done here. cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, k, B, n, beta, C, n); // now we build up the vector to return emacs_value vector = env->intern(env, "vector"); emacs_value *array = malloc(sizeof(emacs_value) * m); emacs_value *row1; emacs_value vec; for (int i = 0; i < m; i++) { row1 = malloc(sizeof(emacs_value) * n); for (int j = 0; j < n; j++) { row1[j] = env->make_float(env, C[j + i * n]); } vec = env->funcall(env, vector, n, row1); array[i] = vec; free(row1); } emacs_value result = env->funcall(env, vector, m, array); free(array); return result; } int emacs_module_init(struct emacs_runtime *ert) { emacs_env *env = ert->get_environment(ert); DEFUN("mkl-dgemm", Fmkl_dgemm, 2, 2, "(mkl-dgemm A B)\n"\ "Multiply the matrices A and B. A and B must both be 2d vectors.\n" \ "Returns the product as a vector.", NULL); provide(env, "mkl"); return 0; }  To build this we have to run org-babel-tangle to generate the mkl.c file, and then run this shell block to compile it. sh /opt/intel/mkl/bin/mklvars.sh intel64 gcc -Wall -m64 -I${MKLROOT}/include -fPIC -c mkl.c
gcc -shared -L${MKLROOT}/lib -Wl,-rpath,${MKLROOT}/lib -lmkl_rt -lpthread -lm -ldl -L. -lemacs-module-helpers -o mkl.so mkl.o


## 5 Elisp helper functions

We will often want to know the shape of our arrays. The shape is how many elements there are in each dimension. Here we define a recursive function that gets the shape of arbitrarily nested vectors and returns a vector of the shape. We define some helper functions to get the number of dimensions, elements, rows and columns.

The main function is a helper elisp function that multiplies two arrays. The function analyzes the shapes and transforms 1d vectors into the right 2d shape to multiply them together, and then returns the shape that makes sense. The c-code is not very robust to mistakes in the array dimensions. It tends to make emacs segfault if you get it wrong. So we try to avoid that if possible.

We have four cases to consider for multiplication:

2d * 2d
(assert (= m1 n2)) return (n1, m2)
1d * 2d
1d is a row vector (1, n1) (assert (= n1 m2)) return vector with n2 elements
2d * 1d
1d is a column vector (m2, 1) (assert (= n1 m2)) return vector with m2 elements
1d * 1d
(assert (= (length m1) (length m2)) return a scalar

Here is the

(add-to-list 'load-path (expand-file-name "."))
(require 'mkl)
(require 'cl)
(require 'seq)

(defun vector-shape (vec)
"Return a vector of the shape of VEC."
(let ((shape (vector (length vec))))
(if (vectorp (aref vec 0))
(vconcat shape (vector-shape (aref vec 0)))
shape)))

(defun vector-ndims (vec)
"Returns the number of dimensions in VEC."
(length (vector-shape vec)))

(defun vector-numel (vec)
"Returns the number of elements in VEC."
(if (> (length vec) 0)
(seq-reduce '* (vector-shape vec) 1)
0))

(defun vector-nrows (vec)
"Return the number of rows in VEC."
(aref (vector-shape vec) 0))

(defun vector-ncols (vec)
"Return the number of columns in VEC."
(aref (vector-shape vec) 1))

(defun matrix-multiply (A B)
"Return A * B in the matrix multiply sense."
(cond
;; 1d * 1d i.e. a dot-product
((and (= 1 (vector-ndims A))
(= 1 (vector-ndims B))
(= (length A) (length B)))
;; this is easy to compute so we don't use dgemm.
(seq-reduce '+ (mapcar* (lambda (a b) (* a b)) A B) 0.0))

;; 2d * 1d (m1, n1) * (n2, 1)
((and (= 2 (vector-ndims A))
(= 1 (vector-ndims B))
;; ncols-A = len-B
(= (vector-ncols A) (length B)))
;; transform B into a 2d column vector
(let* ((B2d (apply 'vector (mapcar 'vector B)))
(result  (mkl-dgemm A B2d)))
;; Now call (dgemm A B2d) -> (m2, 1) column vector
;; and convert it back to a 1d result
(cl-map 'vector (lambda (v) (aref v 0)) result)))

;; 1d * 2d (1, n1) * (m2, n2) len-A = nrows-B
((and (= 1 (vector-ndims A))
(= 2 (vector-ndims B))
(= (length A) (vector-nrows B)))
;; transform B into a 2d row vector
(let* ((A2d (vector A))
(result  (mkl-dgemm A2d B)))
;; should be a 2d row vector
(aref result 0)))

;; 2d * 2d (m1, n1) * (m2, n2) rows-A = ncols-B
((and (= 2 (vector-ndims A))
(= 2 (vector-ndims B))
(= (vector-ncols A)
(vector-nrows B)))
;; call (dgemm A B) and return result
(mkl-dgemm A B))
(t
;; Error checking, getting here means none of the cases above were caught.
;; something is probably wrong.
(cond
((or (> (vector-ndims A) 2)
(> (vector-ndims B) 2))
(error "One of your arrays has more than 2 dimensions. Only 1 or 2d arrays are supported"))
((and (= 1 (vector-ndims A))
(= 1 (vector-ndims B))
(not (= (length A) (length B))))
(error "A and B must be the same length.
len(A) = %d
len(B) = %d" (length A) (length B)))
((and
(= (vector-ndims A) 2)
(= (vector-ndims B) 2)
(not (= (vector-nrows A) (vector-ncols B))))
(error "Your array shapes are not correct.
The number of rows in array A must equal the number of columns in array B.
There are %d rows in A and %d columns in B" (vector-nrows A) (vector-ncols B)))
((and
(= (vector-ndims A) 2)
(= (vector-ndims B) 1)
(not (= (vector-nrows A) (length B))))
(error "Your array shapes are not correct.
The number of rows in array A must equal the number of columns in array B.
There are %d rows in A and %d columns in B" (vector-nrows A) (length B)))
(t
(error "Unknown error"))))))

matrix-multiply

`