Explore all Latex open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Latex

KaTeX

v0.15.3

penrose

v1.3.0

handcalcs

handcalcs v1.4.0

bookdown

bookdown 0.26

arxiv-latex-cleaner

Release v0.1.25

Popular Libraries in Latex

KaTeX

by KaTeX doticonjavascriptdoticon

star image 15047 doticonMIT

Fast math typesetting for the web.

gollum

by gollum doticonrubydoticon

star image 12377 doticonMIT

A simple, Git-powered wiki with a sweet API and local frontend.

ReLaXed

by RelaxedJS doticonjavascriptdoticon

star image 11616 doticonISC

Create PDF documents using web technologies

editor.md

by pandao doticonjavascriptdoticon

star image 11266 doticonMIT

The open source embeddable online markdown editor (component).

overleaf

by overleaf doticonjavascriptdoticon

star image 9317 doticonAGPL-3.0

A web-based collaborative LaTeX editor

LaTeX-Workshop

by James-Yu doticontypescriptdoticon

star image 8290 doticonMIT

Boost LaTeX typesetting efficiency with preview, compile, autocomplete, colorize, and more.

emoji-cheat-sheet

by ikatyang doticonjavascriptdoticon

star image 6948 doticonMIT

A markdown version emoji cheat sheet

penrose

by penrose doticontypescriptdoticon

star image 5350 doticonMIT

Create beautiful diagrams just by typing mathematical notation in plain text.

tufte-css

by edwardtufte doticonhtmldoticon

star image 4923 doticonMIT

Style your webpage like Edward Tufte’s handouts.

Trending New libraries in Latex

handcalcs

by connorferster doticoncssdoticon

star image 3266 doticonApache-2.0

Python library for converting Python calculations into rendered latex.

latex-css

by vincentdoerig doticonhtmldoticon

star image 2249 doticonMIT

LaTeX.css is a CSS library that makes your website look like a LaTeX document

hedgehog-lab

by Hedgehog-Computing doticontypescriptdoticon

star image 1898 doticonApache-2.0

Run, compile and execute JavaScript for Scientific Computing and Data Visualization TOTALLY TOTALLY TOTALLY in your BROWSER! An open source scientific computing environment for JavaScript TOTALLY in your browser, matrix operations with GPU acceleration, TeX support, data visualization and symbolic computation.

latexify_py

by google doticonpythondoticon

star image 1747 doticonApache-2.0

Generates LaTeX math description from Python functions.

LaTeX-OCR

by lukas-blecher doticonpythondoticon

star image 1255 doticonMIT

pix2tex: Using a ViT to convert images of equations into LaTeX code.

doks

by h-enk doticonhtmldoticon

star image 918 doticonMIT

Hugo theme helping you build modern documentation websites.

image-to-latex

by kingyiusuen doticonpythondoticon

star image 671 doticonMIT

Convert images of LaTex math equations into LaTex code.

muboard

by susam doticonjavascriptdoticon

star image 508 doticonMIT

Self-rendering and distributable mathematics chalkboards

Mark-Mind

by MarkMindLtd doticonjavascriptdoticon

star image 461 doticonMIT

MarkMind — a mind map and outliner editor for Windows, Mac, Linux, andriod and ios ,it support markdown in node.

Top Authors in Latex

1

wikimedia

11 Libraries

star icon69

2

mathjax

9 Libraries

star icon2602

3

fannheyward

8 Libraries

star icon240

4

yihui

7 Libraries

star icon2308

5

chdemko

6 Libraries

star icon56

6

nschloe

6 Libraries

star icon2559

7

latex-lsp

5 Libraries

star icon774

8

johnjosephhorton

5 Libraries

star icon62

9

rstudio

5 Libraries

star icon6508

10

asciidoctor

5 Libraries

star icon518

1

11 Libraries

star icon69

2

9 Libraries

star icon2602

3

8 Libraries

star icon240

4

7 Libraries

star icon2308

5

6 Libraries

star icon56

6

6 Libraries

star icon2559

7

5 Libraries

star icon774

8

5 Libraries

star icon62

9

5 Libraries

star icon6508

10

5 Libraries

star icon518

Trending Kits in Latex

No Trending Kits are available at this moment for Latex

Trending Discussions on Latex

Textmate latex compilation : pb with python version after macOS update Monterey 12.3

Latex math text in PIL ImageDraw text()

Kth smallest number algorithm doing extra work?

biber wants to load libcrypt.so.1 but it is missing

LaTeX in plot titles using a loop

Is there a way to resolve repeated server error problem in LaTex (Overleaf)?

How do I type accented characters in ASCII-encoded Rd files?

Implementation of the Metropolis-Hasting algorithm for solving gaussian integrals

Linearize nested for loops

Scientific formats, subscripts and superscripts in RMarkdown table (docx output)

QUESTION

Textmate latex compilation : pb with python version after macOS update Monterey 12.3

Asked 2022-Mar-22 at 10:19

I use textmate for make pdf file in latex. After the update of macOS Monterey version 12.3, the minimal version of python (/usr/bin/python) has disappeared : the compilation don't work now. I try to change in the textmate's files /usr/bin/python by /usr/bin/python3 (I have only this python folder) but that always don't work.

the error say me ti change the compilation command which is this :

1 #!/usr/bin/env ruby18
2# coding: utf-8
3
4require ENV["TM_SUPPORT_PATH"] + "/lib/tm/process"
5require ENV["TM_SUPPORT_PATH"] + "/lib/tm/htmloutput"
6require ENV["TM_SUPPORT_PATH"] + "/lib/tm/save_current_document"
7
8# To enable the typesetting of unsaved documents, you must change the “Save” setting of
9# this command to “Current File” and add the variable TM_LATEX_AUTOSAVE to TextMate's
10# Shell Variables preferences. Be warned that your document must be encoded as UTF-8 if
11# you exercise this option — becauseTextMate.save_current_document cannot know the file 
12# encoding you prefer.
13
14TextMate.save_current_document unless ENV["TM_LATEX_AUTOSAVE"].nil?
15
16texmate = ENV["TM_BUNDLE_SUPPORT"] + "/bin/texmate.py"
17engine_version = TextMate::Process.run(texmate, "version")
18TextMate::HTMLOutput.show(:title => "Typesetting “#{ENV["TM_DISPLAYNAME"] || File.basename(ENV["TM_FILEPATH"])}”…", :sub_title => engine_version) do |io|
19  TextMate::Process.run(texmate, 'latex', :interactive_input => false) do |line|
20    io << line
21  end
22end
23::Process.exit($?.exitstatus || 0) # exitstatus is nil if our process is prematurely terminated (SIGINT)
24

Thank you very much for your help. PS : The compilation work with texshop, I don't think it is a latex problem

ANSWER

Answered 2022-Mar-18 at 07:00

I just found the following page: https://www.heise.de/news/macOS-12-3-Apple-wirft-Python-raus-6341999.html which told me that Apple does not support Python (and some other script languages like for instance Perl) any further. The last version they supported was Python 2.7. Developers should install (and care for) Python 3 by themselves. The Python page told exactly the same thing:

https://docs.python-guide.org/starting/install3/osx/

Source https://stackoverflow.com/questions/71511514

QUESTION

Latex math text in PIL ImageDraw text()

Asked 2022-Mar-10 at 06:08

I'm trying to annotate a few figures I created in python. So, I'm generating an image containing the specified text (using PIL ImageDraw) and concatenating it with the image. Now, I want to include a math notation into the text. Is there a way to write text in latex math when creating the image of text? This answer suggests a work-around by using unicode text, but I would prefer writing the text in latex directly.

MWE:

1from PIL import ImageFont, Image, ImageDraw
2from matplotlib import pyplot
3
4
5def get_annotation(image_shape: tuple, title: str, font_size: int = 50):
6    frame_height, frame_width = image_shape[:2]
7    times_font = ImageFont.truetype('times-new-roman.ttf', font_size)
8    text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255))
9    drawer = ImageDraw.Draw(text_image)
10    w, h = drawer.textsize(title, font=times_font)
11    drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font,
12                align='center')
13    annotation = numpy.array(text_image)
14    return annotation
15
16if __name__ == '__main__':
17    anno = get_annotation((100, 300), 'frame $f_n$')
18    pyplot.imshow(anno)
19    pyplot.show()
20

I tried passing frame $f_n$ to title parameter, but dollars got printed in the text image.

PS: times-new-roman.ttf can be obtained here

ANSWER

Answered 2022-Mar-10 at 06:08

I found an alternative with sympy here

1from PIL import ImageFont, Image, ImageDraw
2from matplotlib import pyplot
3
4
5def get_annotation(image_shape: tuple, title: str, font_size: int = 50):
6    frame_height, frame_width = image_shape[:2]
7    times_font = ImageFont.truetype('times-new-roman.ttf', font_size)
8    text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255))
9    drawer = ImageDraw.Draw(text_image)
10    w, h = drawer.textsize(title, font=times_font)
11    drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font,
12                align='center')
13    annotation = numpy.array(text_image)
14    return annotation
15
16if __name__ == '__main__':
17    anno = get_annotation((100, 300), 'frame $f_n$')
18    pyplot.imshow(anno)
19    pyplot.show()
20import sympy
21
22sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)
23

Source https://stackoverflow.com/questions/71376207

QUESTION

Kth smallest number algorithm doing extra work?

Asked 2022-Feb-27 at 08:40

So I'm preparing for a technical interview, and one of my practice questions is the Kth smallest number. I know that I can do a sort for O(n * log(n)) time and use a heap for O(n * log(k)). However I also know I can partition it (similar to quicksort) for an average case of O(n).

The actual calculated average time complexity should be:

\sum_{i = 0}^{log_{2}(n) - 1} \tfrac{n}{2^{i}}-1 = 2n - 2 - log_{2}(n)

I've double checked this math using WolframAlpha, and it agrees.

So I've coded my solution, and then I calculated the actual average time complexity on random data sets. For small values of n, it's pretty close. For example n=5 might give me an actual of around 6.2 when I expect around 5.7. This slightly more error is consistent.

This only gets worse as I increase the value of n. For example, for n=5000, I get around 15,000 for my actual average time complexity, when it should be slightly less than 10,000.

So basically, my question is where are these extra iterations coming from? Is my code wrong, or is it my math? My code is below:

1import java.util.Arrays;
2import java.util.Random;
3
4public class Solution {
5    static long tc = 0;
6    
7    static void swap(int[] arr, int i, int j) {
8        int temp = arr[i];
9        arr[i] = arr[j];
10        arr[j] = temp;
11    }
12
13    static int kMin(int[] arr, int k) {
14        arr = arr.clone();
15        int pivot = pivot(arr);
16        if(pivot > k) {
17            return kMin(Arrays.copyOfRange(arr, 0, pivot), k);
18        } else if(pivot < k) {
19            return kMin(Arrays.copyOfRange(arr, pivot + 1, arr.length), k - pivot - 1);
20        }
21        return arr[k];
22    }
23
24    static int pivot(int[] arr) {
25        Random rand = new Random();
26        int pivot = rand.nextInt(arr.length);
27    
28        swap(arr, pivot, arr.length - 1);
29    
30        int i = 0;
31        for(int j = 0; j < arr.length - 1; j++) {
32            tc++;
33            if(arr[j] < arr[arr.length - 1]) {
34                swap(arr, i, j);
35                i++;
36            }
37        }
38        swap(arr, i, arr.length - 1);
39        return i;
40    }
41
42    public static void main(String args[]) {
43        int iterations = 10000;
44        int n = 5000;
45        for(int j = 0; j < iterations; j++) {
46            Random rd = new Random(); 
47            int[] arr = new int[n];
48            for (int i = 0; i < arr.length; i++) {
49                arr[i] = rd.nextInt();
50            }
51            int k = rd.nextInt(arr.length - 1);
52            kMin(arr, k);
53        }
54        System.out.println("Actual: " + tc / (double)iterations);
55        
56        double expected = 2.0 * n - 2.0 - (Math.log(n) / Math.log(2));
57        System.out.println("Expected: " + expected);
58    }
59    
60
61}
62

ANSWER

Answered 2022-Feb-27 at 08:40

As you and others have pointed out in the comments, your calculation assumed that the array was split in half on each iteration by the random pivot, which is incorrect. This uneven splitting has a significant impact: when the element you're trying to select is the actual median, for instance, the expected size of the array after one random pivot choice is 75% of the original, since you'll always choose the larger of the two arrays.

For an accurate estimate of the expected comparisons for each value of n and k, David Eppstein published an accessible analysis here and derives this formula:

eqn

This is a very close estimate for your values, even though this assumes no duplicates in the array.

Calculating the expected number of comparisons for k from 1 to n-1, as you do, gives ~7.499 * 10^7 total comparisons when n=5000, or almost exactly 15,000 comparisons per call of Quickselect as you observed.

ans

Source https://stackoverflow.com/questions/71280653

QUESTION

biber wants to load libcrypt.so.1 but it is missing

Asked 2022-Feb-21 at 10:53

I am Arch GNU/Linux user who usually manages almost every package with pacman; I manage TeX and LaTeX-related things with tlmgr. I installed tlmgr from source.

I am writing paper. I would like to use bibliography.

When I tried latexmk -pdflua main.ltx:

1Rc files read:
2  latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6      'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber  "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16  biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19
libcrypt.so* on my environment
1Rc files read:
2  latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6      'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber  "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16  biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28
What I tried else

I uninstalled and re-installed biber on tlmgr but did not work.

1Rc files read:
2  latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6      'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber  "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16  biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28# ln -s /usr/lib/libcrypt.so /usr/lib/libcrypt.so.1
29$ latexmkrc -pdflua main.ltx
30Rc files read:
31  latexmkrc
32Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
33Latexmk: applying rule 'biber main'...
34Rule 'biber main': The following rules & subrules became out-of-date:
35      'biber main'
36------------
37Run number 1 of rule 'biber main'
38------------
39------------
40Running 'biber  "main.bcf"'
41------------
42/tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber: /usr/lib/libcrypt.so.1: version `GLIBC_2.2.5' not found (required by /tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber)
43Latexmk: Errors, so I did not complete making targets
44Collected error summary (may duplicate other messages):
45  biber main: Could not open biber log file for 'main'
46Latexmk: Use the -f option to force complete processing,
47 unless error was exceeding maximum runs, or warnings treated as errors.
48
File source

latexmkrc:

1Rc files read:
2  latexmkrc
3Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
4Latexmk: applying rule 'biber main'...
5Rule 'biber main': The following rules & subrules became out-of-date:
6      'biber main'
7------------
8Run number 1 of rule 'biber main'
9------------
10------------
11Running 'biber  "main.bcf"'
12------------
13biber: error while loading shared libraries: libcrypt.so.1: cannot open shared object file: No such file or directory
14Latexmk: Errors, so I did not complete making targets
15Collected error summary (may duplicate other messages):
16  biber main: Could not open biber log file for 'main'
17Latexmk: Use the -f option to force complete processing,
18 unless error was exceeding maximum runs, or warnings treated as errors.
19$ pacman -Qo /usr/lib/libcrypt*
20/usr/lib/libcrypto.so is owned by openssl 1.1.1.m-1
21/usr/lib/libcrypto.so.1.1 is owned by openssl 1.1.1.m-1
22/usr/lib/libcryptsetup.so is owned by cryptsetup 2.4.3-2
23/usr/lib/libcryptsetup.so.12 is owned by cryptsetup 2.4.3-2
24/usr/lib/libcryptsetup.so.12.7.0 is owned by cryptsetup 2.4.3-2
25/usr/lib/libcrypt.so is owned by libxcrypt 4.4.28-1
26/usr/lib/libcrypt.so.2 is owned by libxcrypt 4.4.28-1
27/usr/lib/libcrypt.so.2.0.0 is owned by libxcrypt 4.4.28-1
28# ln -s /usr/lib/libcrypt.so /usr/lib/libcrypt.so.1
29$ latexmkrc -pdflua main.ltx
30Rc files read:
31  latexmkrc
32Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
33Latexmk: applying rule 'biber main'...
34Rule 'biber main': The following rules & subrules became out-of-date:
35      'biber main'
36------------
37Run number 1 of rule 'biber main'
38------------
39------------
40Running 'biber  "main.bcf"'
41------------
42/tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber: /usr/lib/libcrypt.so.1: version `GLIBC_2.2.5' not found (required by /tmp/par-716861/cache-0e6aa298f0c2e7a775de99938825b2d56bd2027f/biber)
43Latexmk: Errors, so I did not complete making targets
44Collected error summary (may duplicate other messages):
45  biber main: Could not open biber log file for 'main'
46Latexmk: Use the -f option to force complete processing,
47 unless error was exceeding maximum runs, or warnings treated as errors.
48$latex='lualatex %O -synctex=1 -interaction=nonstopmode %S';
49#$bibtex='upbibtex %O %B';
50$bibtex='biber %O %B';
51$makeindex='upmendex %O -o %D %S';
52$pdf_mode=3;
53

ANSWER

Answered 2022-Feb-21 at 10:53

Install libxcrypt-compat from the AUR, as suggest in this answer.

This made my biber from TeX Live 2020 work again. The interesting question is if newer TeX distributions will require this AUR package.

Source https://stackoverflow.com/questions/71171446

QUESTION

LaTeX in plot titles using a loop

Asked 2022-Feb-19 at 18:02

I just learned how to insert (a limited number of) LaTeX expressions into my plot titles with expression(<LaTeX code>). How can I generate plots containing LaTeX in their titles using a loop? For example, say I have:

1par(mfrow = c(2,2))
2
3x &lt;- seq(1,10,0.1)
4y &lt;- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8

This produces the desired output: enter image description here

How can I achieve the same output, but by replacing the last two lines with a loop? I tried

1par(mfrow = c(2,2))
2
3x &lt;- seq(1,10,0.1)
4y &lt;- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8par(mfrow = c(2,2))
9for (i in 1:2){
10    plot(x, y, main = expression(sigma[i]))
11}
12

but the i was not interpreted as a variable: enter image description here

Any solutions for this?

ANSWER

Answered 2022-Feb-19 at 17:04

We can use bquote instead of expression. This allows partial unquoting, meaning you can substitute the value of i inside the expression by wrapping it like this: .(i)

1par(mfrow = c(2,2))
2
3x &lt;- seq(1,10,0.1)
4y &lt;- sin(x)
5
6plot(x, y, main = expression(sigma[1]))
7plot(x, y, main = expression(sigma[2]))
8par(mfrow = c(2,2))
9for (i in 1:2){
10    plot(x, y, main = expression(sigma[i]))
11}
12par(mfrow = c(2,2))
13
14x &lt;- seq(1,10,0.1)
15y &lt;- sin(x)
16
17for(i in 1:4) plot(x, y, main = bquote(paste(&quot;My plot for &quot;, sigma[.(i)], &quot; :&quot;)))
18

Created on 2022-02-19 by the reprex package (v2.0.1)

Source https://stackoverflow.com/questions/71186976

QUESTION

Is there a way to resolve repeated server error problem in LaTex (Overleaf)?

Asked 2022-Feb-13 at 12:12

I ran into this error while trying to compile my overleaf latex;

"Server Error Sorry, something went wrong and your project could not be compiled. Please try again in a few moments".

Your response will be helpful. Thanks

enter image description here

ANSWER

Answered 2022-Feb-13 at 08:47

This problem may arise as a result of the internet connection. The simple way to resolve this problem is to reload the Overleaf editor by refreshing your browser.

Source https://stackoverflow.com/questions/71099109

QUESTION

How do I type accented characters in ASCII-encoded Rd files?

Asked 2022-Feb-08 at 13:38

Can LaTeX escapes for accents be used in Rd files? I tried the standard \'e and many variants (\'{e}, {\'e}, \\'e, \\'{e}, {\\'e}, etc.), but none is rendered as an accented character in the PDF or HTML output.

I want my References section (i.e. \references{}) to be rendered with accented characters, but I do not want to type non-ASCII characters in my Rd files. Is there good/recommended practice? Should I simply replace non-ASCII characters with their ASCII equivalents (é → e, ø → o)?

To be clear, I know it is possible to type accented characters (e.g., é) directly in UTF-8-encoded files, but I would prefer to keep ASCII-encoded files.

This question is not about

or variants.

Minimal test package

Package structure

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7

test/man/one.Rd

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14

test/R/one.R

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15

test/DESCRIPTION

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody &lt;no@body.org&gt;
20Description: Test.
21License: GPL-3
22

Build, check, and install with:

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody &lt;no@body.org&gt;
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25

ANSWER

Answered 2022-Feb-07 at 16:21

Using math mode it works. Not sure 100% if this is what you are looking for.

Here are some examples:

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody &lt;no@body.org&gt;
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25  \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33

PDF output:

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody &lt;no@body.org&gt;
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25  \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33’{e} {’e} \‘e \’{e} {\’e}
34é
35è
3637

Update:

1test
2test/man
3test/man/one.Rd
4test/R
5test/R/one.R
6test/DESCRIPTION
7\name{one}
8\alias{one}
9\title{Get One}
10\description{Accents are not rendered: \'e \'{e} {\'e} \\'e \\'{e} {\\'e}}
11\usage{
12one()
13}
14one &lt;- function() 1
15Package: test
16Version: 0.1
17Title: Test
18Author: Nobody
19Maintainer: Nobody &lt;no@body.org&gt;
20Description: Test.
21License: GPL-3
22$ R CMD build test
23$ R CMD check test_0.1.tar.gz
24$ R CMD INSTALL test_0.1.tar.gz
25  \'{e} {\'e} \\'e \\'{e} {\\'e}
26
27$\acute{e}$
28
29$\grave{e}$
30
31$\tilde{e}$
32
33’{e} {’e} \‘e \’{e} {\’e}
34é
35è
3637\newcommand\latexcode[1]{#1}
38
39\latexcode{\'{a}}
40
41Thoma\latexcode{\'{s}}
42

That works Thomas !

Source https://stackoverflow.com/questions/71021330

QUESTION

Implementation of the Metropolis-Hasting algorithm for solving gaussian integrals

Asked 2022-Feb-02 at 20:28

I am currently having issue with the implementation of the Metropolis-Hastings algorithm.

I am trying to use the algorithm to calculate integrals of the form

formula

In using this algorithm, we can obtain a long chain of configurations ( in this case, each configuration is just a single numbers) such that in the tail-end of the chain the probability of having a particular configuration follows (or rather tends to) a gaussian distribution.

My code seems to be messing up with obtaining the said gaussian distributions. There is a strange dependence on the transition probablity (the probablity of picking a new candidate configuration depending on the previous configuration in the chain). However, if this transition probability is symmetric, there should be no dependence on this function at all (it only affects speed at which phase space [space of potential configurations] is explored and how quickly the chain converges to the desired distribution)!

In my case I am using a normal distribution transition function (which satisfies the need to be symmetric), with width d. For each d I use I do indeed get a gaussian distribution however the standard deviation, sigma, depends on my choice of d. The resulting gaussian should have a sigma of roughly 0.701 but I find that the value I actually get depends on the parameter d, when it shouldn't.

I am not sure where the error in this code is, any help would be greatly appreciated!

1import numpy as np
2import matplotlib.pyplot as plt
3from scipy.stats import norm
4
5
6'''
7We want to get an exponential decay integral approx using importance sampling.
8We will try to integrate x^2exp(-x^2) over the real line.
9Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that 
10the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
11
12Once configs  = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by 
13Q_N = 1/N sum_(configs) x^2
14lim (N-&gt; inf) Q_N -&gt; I
15'''
16
17'''
18Implementing metropolis-hasting algorithm
19'''
20
21#Setting up the initial config for our chain, generating first 2 to generate numpy array
22x_0 = np.random.uniform(-20,-10,2)
23
24#Defining function that generates the next N steps in the chain, given a starting config x
25#Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
26#Success and failures implemented to see roughly the success rate of each step
27def next_steps(x,N):
28    i = 0
29    Success = 0
30    Failures = 0
31    Data = np.array(x)
32    d = 1.5                       #Spread of (normal) transition function
33    while i &lt; N:
34        r = np.random.uniform(0,1)
35        delta = np.random.normal(0,d)
36        x_old = Data[-1]
37        x_new = x_old + delta
38        hasting_ratio = np.exp(-(x_new**2-x_old**2) )
39        if hasting_ratio &gt; r:
40            i = i+1
41            Data = np.append(Data,x_new)
42            Success = Success +1
43        else:
44            Failures = Failures + 1
45    print(Success)
46    print(Failures)
47    return Data
48
49#Number of steps in the chain
50N_iteration   = 50000
51
52#Generating the data
53Data = next_steps(x_0,N_iteration)
54
55#Plotting data to see convergence of chain to gaussian distribution
56plt.plot(Data)
57plt.show()
58
59#Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
60Data = Data[-40000:]
61(mu, sigma) = norm.fit(Data)
62print(sigma)
63
64
65#Plotting a histogram to visually see if guassian
66plt.hist(Data, bins = 300)
67plt.show()
68

ANSWER

Answered 2022-Feb-02 at 20:28

You need to save x even when it doesn't change. Otherwise the center values are under-counted, and more so as d increases, which increases the variance.

1import numpy as np
2import matplotlib.pyplot as plt
3from scipy.stats import norm
4
5
6'''
7We want to get an exponential decay integral approx using importance sampling.
8We will try to integrate x^2exp(-x^2) over the real line.
9Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that 
10the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
11
12Once configs  = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by 
13Q_N = 1/N sum_(configs) x^2
14lim (N-&gt; inf) Q_N -&gt; I
15'''
16
17'''
18Implementing metropolis-hasting algorithm
19'''
20
21#Setting up the initial config for our chain, generating first 2 to generate numpy array
22x_0 = np.random.uniform(-20,-10,2)
23
24#Defining function that generates the next N steps in the chain, given a starting config x
25#Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
26#Success and failures implemented to see roughly the success rate of each step
27def next_steps(x,N):
28    i = 0
29    Success = 0
30    Failures = 0
31    Data = np.array(x)
32    d = 1.5                       #Spread of (normal) transition function
33    while i &lt; N:
34        r = np.random.uniform(0,1)
35        delta = np.random.normal(0,d)
36        x_old = Data[-1]
37        x_new = x_old + delta
38        hasting_ratio = np.exp(-(x_new**2-x_old**2) )
39        if hasting_ratio &gt; r:
40            i = i+1
41            Data = np.append(Data,x_new)
42            Success = Success +1
43        else:
44            Failures = Failures + 1
45    print(Success)
46    print(Failures)
47    return Data
48
49#Number of steps in the chain
50N_iteration   = 50000
51
52#Generating the data
53Data = next_steps(x_0,N_iteration)
54
55#Plotting data to see convergence of chain to gaussian distribution
56plt.plot(Data)
57plt.show()
58
59#Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
60Data = Data[-40000:]
61(mu, sigma) = norm.fit(Data)
62print(sigma)
63
64
65#Plotting a histogram to visually see if guassian
66plt.hist(Data, bins = 300)
67plt.show()
68import numpy as np
69from scipy.stats import norm
70
71
72&quot;&quot;&quot;
73We want to get an exponential decay integral approx using importance sampling.
74We will try to integrate x^2exp(-x^2) over the real line.
75Metropolis-hasting alg will generate configuartions (in this case, single numbers) such that 
76the probablity of a given configuration x^a ~ p(x^a) for p(x) propto exp(-x^2).
77
78Once configs  = {x^a} generated, the apporximation, Q_N, of the integral, I, will be given by 
79Q_N = 1/N sum_(configs) x^2
80lim (N-&gt; inf) Q_N -&gt; I
81&quot;&quot;&quot;
82
83&quot;&quot;&quot;
84Implementing metropolis-hasting algorithm
85&quot;&quot;&quot;
86
87# Setting up the initial config for our chain
88x_0 = np.random.uniform(-20, -10)
89
90# Defining function that generates the next N steps in the chain, given a starting config x
91# Works by iteratively taking the last element in the chain, generating a new candidate configuration from it and accepting/rejecting according to the algorithm
92# Success and failures implemented to see roughly the success rate of each step
93def next_steps(x, N):
94    Success = 0
95    Failures = 0
96    Data = np.empty((N,))
97    d = 1.5  # Spread of (normal) transition function
98    for i in range(N):
99        r = np.random.uniform(0, 1)
100        delta = np.random.normal(0, d)
101        x_new = x + delta
102        hasting_ratio = np.exp(-(x_new ** 2 - x ** 2))
103        if hasting_ratio &gt; r:
104            x = x_new
105            Success = Success + 1
106        else:
107            Failures = Failures + 1
108        Data[i] = x
109    print(Success)
110    print(Failures)
111    return Data
112
113
114# Number of steps in the chain
115N_iteration = 50000
116
117# Generating the data
118Data = next_steps(x_0, N_iteration)
119
120# Obtaining tail end data and obtaining the standard deviation of resulting gaussian distribution
121Data = Data[-40000:]
122(mu, sigma) = norm.fit(Data)
123print(sigma)
124

Source https://stackoverflow.com/questions/70958350

QUESTION

Linearize nested for loops

Asked 2022-Feb-01 at 08:27

I'm working on some heavy algorithm, and now I'm trying to make it multithreaded. It has a loop with 2 nested loops:

1for (int i = 0; i &lt; n; ++i) {
2    for (int j = i + 1; j &lt; n; ++j) {
3        for (int k = j + 1; k &lt; n; ++k) {
4            function(i, j, k);
5        }
6    }
7}
8

I know, that the number of function calls will be equal to

But I have one last problem: I don't know how to calculate i, j and k based on b (0 <= b < binom(n, 3))

1for (int i = 0; i &lt; n; ++i) {
2    for (int j = i + 1; j &lt; n; ++j) {
3        for (int k = j + 1; k &lt; n; ++k) {
4            function(i, j, k);
5        }
6    }
7}
8for (int b = start; b &lt; end; ++b) {
9    // how to calculate i, j, k?
10}
11

How can I calculate these values?

EDIT: My main idea is to call function like this from different threads:

1for (int i = 0; i &lt; n; ++i) {
2    for (int j = i + 1; j &lt; n; ++j) {
3        for (int k = j + 1; k &lt; n; ++k) {
4            function(i, j, k);
5        }
6    }
7}
8for (int b = start; b &lt; end; ++b) {
9    // how to calculate i, j, k?
10}
11void calculate(int start, int end) {
12    for (int b = start; b &lt; end; ++b) {
13        int i = ...;
14        int j = ...;
15        int k = ...;
16        function(i, j, k);
17    }
18}
19
20int total = binom(n, 3);
21
22// thread A:
23calculate(0, total / 2);
24
25// thread B:
26calculate(total / 2, total);
27

ANSWER

Answered 2021-Dec-20 at 09:25

A third attempt:

I've taken your code, and at last got it to run properly (in python):

1for (int i = 0; i &lt; n; ++i) {
2    for (int j = i + 1; j &lt; n; ++j) {
3        for (int k = j + 1; k &lt; n; ++k) {
4            function(i, j, k);
5        }
6    }
7}
8for (int b = start; b &lt; end; ++b) {
9    // how to calculate i, j, k?
10}
11void calculate(int start, int end) {
12    for (int b = start; b &lt; end; ++b) {
13        int i = ...;
14        int j = ...;
15        int k = ...;
16        function(i, j, k);
17    }
18}
19
20int total = binom(n, 3);
21
22// thread A:
23calculate(0, total / 2);
24
25// thread B:
26calculate(total / 2, total);
27def get_k(n):
28    total = 0
29    for i in range(3, n):
30        for j in range(i + 1, n):
31            for k in range(j + 1, n):
32                total += 1
33            
34    V = total // 2 # for 2 threads
35    V_tmp = 0          
36    for i in range(3, n):
37        if(V_tmp &gt; V):
38            return i
39        for j in range(i + 1, n):
40            for k in range(j + 1, n):
41                V_tmp += 1
42
43def pseudo_thread(start, end, n):
44    counter = 0
45
46    for i in range(start, end):
47        for j in range(i + 1, n):
48            for k in range(j + 1, n):
49                counter += 1
50    print(counter)
51
52
53n = 145
54k = get_k(n)
55
56pseudo_thread(3, k, n)
57pseudo_thread(k, n, n)
58

This should finally give you a relatively good split. Even with n=145, we get 239260 and 227920 for our counter values. It's obviously not an elegant solution, and also not perfect, but it gives you the right answer without much reference to detailed mathematics.

Source https://stackoverflow.com/questions/70413446

QUESTION

Scientific formats, subscripts and superscripts in RMarkdown table (docx output)

Asked 2022-Jan-31 at 22:52

Let's say I have the following rmd:

1---
2title: &quot;Table won't work&quot;
3author: &quot;Exhausted student&quot;
4date: &quot;2022/01/28&quot;
5output: 
6  bookdown::word_document2
7---
8
9```{r table, echo=F, warning=F, message=F}
10library(tidyverse)
11a &lt;- tibble(
12  constants = c(&quot;c&quot;, &quot;NA&quot;, &quot;h&quot;, &quot;e&quot;, &quot;H2O&quot;),
13  values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
14)
15
16knitr::kable(a, digits = 35)
17```
18

which produces this table in Word.

The Problem

I need the scientific format to use superscripts and multiply sign (i.e. 2.998 × 108), and some cells requires subscript (e.g. NA and H2O).

The final table should look like this. How can I do that?

What I've tried/would never try
  1. huxtable package and its markdown() function: I managed to format some contents as H~2~O, then enable markdown across table by huxtable(a) %>% `markdown<-`(TRUE). Which did not recognize the syntax, and apparently would not work in forseeable future according to the author.
  2. flextable and as_sub(): Produces right format. I pass the lables to flextable::compose(), where the labels were something like as_paragraph(list_values = list("H", as_sub("2"), "O"). The code is obviously too lengthy; plus i have to manipulate cells one-by-one. Technically still doable, but I do have tables with 100+ cells needed formatting.
  3. Output first, format in Word later: Again, needed manipulation one-by-one. Would be an option if it would work everything out automatically.
  4. Convincing the school bureaucrats to accept html/pdf/latex as output: this is forever an impossible option.
  5. Format outside word then export formatted table as image: strictly forbidden in the reports.

Edit: the table works now! Great thanks to Maël's answer, but please check my own findings to see my final result:

well-formatted table

ANSWER

Answered 2022-Jan-31 at 22:52

Your code should look like this:

1---
2title: &quot;Table won't work&quot;
3author: &quot;Exhausted student&quot;
4date: &quot;2022/01/28&quot;
5output: 
6  bookdown::word_document2
7---
8
9```{r table, echo=F, warning=F, message=F}
10library(tidyverse)
11a &lt;- tibble(
12  constants = c(&quot;c&quot;, &quot;NA&quot;, &quot;h&quot;, &quot;e&quot;, &quot;H2O&quot;),
13  values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
14)
15
16knitr::kable(a, digits = 35)
17```
18```
19{r table, echo=F, warning=F, message=F}
20library(tidyverse)
21a &lt;- tibble(
22  constants = c(&quot;c&quot;, &quot;NA&quot;, &quot;h&quot;, &quot;e&quot;, &quot;$H_2O$&quot;),
23  values = c(&quot;$2.998 * {10^{8}}$&quot;, &quot;$6.022 * {10^{-23}}$&quot;, &quot;$6.626 * {10^{-34}}$&quot;, &quot;$-1.602 * {10 ^{-19}}$&quot;, &quot;$1.802 * {10^{1}}$&quot;)
24)
25
26knitr::kable(format = &quot;html&quot;, a, digits = 35)
27```
28

Which will give you the output like this:

enter image description here

Source https://stackoverflow.com/questions/70890569

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Latex

Tutorials and Learning Resources are not available at this moment for Latex

Share this Page

share link

Get latest updates on Latex