1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use std::fmt::{Display, Error, Formatter};
use std::io::Write;

pub trait AsPythonLitteral {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result;
}

macro_rules! as_py_lit_impl {
    ($t: ty, $fmt_str: expr) => {
        impl AsPythonLitteral for $t {
            fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
                write!(f, $fmt_str, &self)
            }
        }
    };
}

as_py_lit_impl!(str, "\"\"\"{}\"\"\"");
as_py_lit_impl!(u8, "{}");
as_py_lit_impl!(u16, "{}");
as_py_lit_impl!(u32, "{}");
as_py_lit_impl!(u64, "{}");
as_py_lit_impl!(u128, "{}");
as_py_lit_impl!(usize, "{}");
as_py_lit_impl!(i8, "{}");
as_py_lit_impl!(i16, "{}");
as_py_lit_impl!(i32, "{}");
as_py_lit_impl!(i64, "{}");
as_py_lit_impl!(i128, "{}");
as_py_lit_impl!(isize, "{}");
as_py_lit_impl!(f32, "{:.6e}");
as_py_lit_impl!(f64, "{:.6e}");

impl<T: AsPythonLitteral> AsPythonLitteral for Vec<T> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "[")?;
        for x in self.iter() {
            write!(f, "{},", PythonLitteral(x))?;
        }
        write!(f, "]")
    }
}

#[derive(Copy, Clone, Debug)]
pub struct Indents(pub isize);

impl std::fmt::Display for Indents {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        for _ in 0..self.0 {
            write!(f, "\t")?;
        }
        Ok(())
    }
}

struct PythonLitteral<'l, T: AsPythonLitteral + ?Sized>(pub &'l T);
impl<'l, T: AsPythonLitteral + ?Sized> Display for PythonLitteral<'l, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        self.0.fmt(f)
    }
}

pub struct JoinGuard<T>(Option<std::thread::JoinHandle<T>>);

impl<T> JoinGuard<T> {
    pub fn new() -> Self {
        JoinGuard(None)
    }

    pub fn spawn<F: FnOnce() -> T>(f: F) -> Self
    where
        T: Send + 'static,
        F: Send + 'static,
    {
        JoinGuard(Some(std::thread::spawn(f)))
    }

    pub fn join(mut self) -> Result<T, Box<dyn std::any::Any + Send>>
    where
        T: std::any::Any + Send + 'static,
    {
        self.0.take().unwrap().join()
    }

    pub fn detach(mut self) -> Option<std::thread::JoinHandle<T>> {
        self.0.take()
    }
}

impl<T> Drop for JoinGuard<T> {
    fn drop(&mut self) {
        if let Some(handle) = self.0.take() {
            handle.join();
        }
    }
}

/// An instance of code generation unit.
/// It really is just a file with dedicated APIs to write Python into it.
/// Most importantly: it manages indentation for you.
pub struct PythonProgram {
    file: tempfile::NamedTempFile,
    indents: Indents,
}
impl PythonProgram {
    /// Creates a named temp file to store the generated python program
    pub fn new() -> PythonProgram {
        PythonProgram {
            file: tempfile::NamedTempFile::new().unwrap(),
            indents: Indents(0),
        }
    }

    /// Runs the program using python3
    pub fn run(&self) -> Result<std::process::Output, std::io::Error> {
        std::process::Command::new("python3")
            .arg(self.file.path())
            .output()
    }

    /// Spawns a thread to run the program using python3.
    /// The returned JoinGuard ensures that the program will be ran to completion.
    pub fn background_run(self) -> JoinGuard<Result<std::process::Output, std::io::Error>> {
        JoinGuard::spawn(move || self.run())
    }

    /// Ensures that the internal file has been flushed. Typically not necessary.
    pub fn flush(&mut self) -> &mut Self {
        self.file.flush().unwrap();
        self
    }

    /// Moves the indentation level by `n`. However, I recommend using the dedicated functions when possible/
    pub fn indent(&mut self, n: isize) -> &mut Self {
        if n >= 0 {
            self.indents.0 += n as isize
        } else {
            self.indents.0 -= n as isize
        }
        self
    }

    /// Removes one indentation level from the cursor.
    /// You should call this whenever you're done with a scope.
    pub fn end_block(&mut self) -> &mut Self {
        self.indent(-1)
    }

    /// Writes a line assigning `value` formatted as a python literal to `name`
    pub fn define_variable<T: AsPythonLitteral + ?Sized>(
        &mut self,
        name: &str,
        value: &T,
    ) -> &mut Self {
        writeln!(
            &mut self.file,
            "{}{} = {}",
            self.indents,
            name,
            PythonLitteral(value)
        )
        .unwrap();
        self
    }

    /// Writes an import statement for your `dependency`
    pub fn import(&mut self, dependency: &str) -> &mut Self {
        writeln!(&mut self.file, "{}import {}", self.indents, dependency).unwrap();
        self
    }

    /// Writes an import statement for your `dependency` as `rename`
    pub fn import_as(&mut self, dependency: &str, rename: &str) -> &mut Self {
        writeln!(
            &mut self.file,
            "{}import {} as {}",
            self.indents, dependency, rename
        )
        .unwrap();
        self
    }

    /// Writes whatever line you passed it, indented at the proper level.
    pub fn write_line(&mut self, line: &str) -> &mut Self {
        writeln!(&mut self.file, "{}{}", self.indents, line).unwrap();
        self
    }

    /// Writes an if, using your condition as a test, and increments indentation.
    pub fn r#if(&mut self, condition: &str) -> &mut Self {
        writeln!(&mut self.file, "{}if {}:", self.indents, condition).unwrap();
        self.indent(1)
    }
    /// Decrements indentation, writes an elif, using your condition as a test, and increments indentation.
    pub fn elif(&mut self, condition: &str) -> &mut Self {
        self.indent(-1);
        writeln!(&mut self.file, "{}elif {}:", self.indents, condition).unwrap();
        self.indent(1)
    }
    /// Decrements indentation, writes an else, using your condition as a test, and increments indentation.
    pub fn r#else(&mut self) -> &mut Self {
        self.indent(-1).write_line("else:").indent(1)
    }

    /// Writes "for `range`:", and increments indentation.
    pub fn r#for(&mut self, range: &str) -> &mut Self {
        writeln!(&mut self.file, "{}for {}:", self.indents, range).unwrap();
        self.indent(1)
    }

    /// Writes a while, using your condition as a test, and increments indentation.
    pub fn r#while(&mut self, condition: &str) -> &mut Self {
        writeln!(&mut self.file, "{}while {}:", self.indents, condition).unwrap();
        self.indent(1)
    }
}

impl Write for PythonProgram {
    fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> Result<(), std::io::Error> {
        self.file.flush()
    }
}

impl Display for PythonProgram {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        use std::io::BufRead;
        let read_file = std::fs::File::open(self.file.path()).unwrap();
        let reader = std::io::BufReader::new(read_file);
        for line in reader.lines() {
            writeln!(f, "{}", line.unwrap())?
        }
        Ok(())
    }
}

pub trait MatPlotLib {
    fn import_pyplot_as_plt(&mut self) -> &mut Self;
    fn plot_y<Y: AsPythonLitteral>(&mut self, y: &Y) -> &mut Self;
    fn plot_xy<X: AsPythonLitteral, Y: AsPythonLitteral>(&mut self, x: &X, y: &Y) -> &mut Self;
    fn plot_xyargs<X: AsPythonLitteral, Y: AsPythonLitteral>(
        &mut self,
        x: &X,
        y: &Y,
        args: &str,
    ) -> &mut Self;
    fn semilogy_y<Y: AsPythonLitteral>(&mut self, y: &Y) -> &mut Self;
    fn semilogy_xy<X: AsPythonLitteral, Y: AsPythonLitteral>(&mut self, x: &X, y: &Y) -> &mut Self;
    fn semilogy_xyargs<X: AsPythonLitteral, Y: AsPythonLitteral>(
        &mut self,
        x: &X,
        y: &Y,
        args: &str,
    ) -> &mut Self;
    fn show(&mut self) -> &mut Self;
}

impl MatPlotLib for PythonProgram {
    fn import_pyplot_as_plt(&mut self) -> &mut Self {
        self.import_as("matplotlib.pyplot", "plt")
    }

    fn plot_y<Y: AsPythonLitteral>(&mut self, y: &Y) -> &mut Self {
        self.write_line(&format!("plt.plot({})", PythonLitteral(y)))
    }

    fn plot_xy<X: AsPythonLitteral, Y: AsPythonLitteral>(&mut self, x: &X, y: &Y) -> &mut Self {
        self.write_line(&format!(
            "plt.plot({},{})",
            PythonLitteral(x),
            PythonLitteral(y)
        ))
    }

    fn plot_xyargs<X: AsPythonLitteral, Y: AsPythonLitteral>(
        &mut self,
        x: &X,
        y: &Y,
        args: &str,
    ) -> &mut Self {
        self.write_line(&format!(
            "plt.plot({},{},{})",
            PythonLitteral(x),
            PythonLitteral(y),
            args
        ))
    }

    fn semilogy_y<Y: AsPythonLitteral>(&mut self, y: &Y) -> &mut Self {
        self.write_line(&format!("plt.semilogy({})", PythonLitteral(y)))
    }

    fn semilogy_xy<X: AsPythonLitteral, Y: AsPythonLitteral>(&mut self, x: &X, y: &Y) -> &mut Self {
        self.write_line(&format!(
            "plt.semilogy({},{})",
            PythonLitteral(x),
            PythonLitteral(y)
        ))
    }

    fn semilogy_xyargs<X: AsPythonLitteral, Y: AsPythonLitteral>(
        &mut self,
        x: &X,
        y: &Y,
        args: &str,
    ) -> &mut Self {
        self.write_line(&format!(
            "plt.semilogy({},{},{})",
            PythonLitteral(x),
            PythonLitteral(y),
            args
        ))
    }

    fn show(&mut self) -> &mut Self {
        self.write_line("plt.show()")
    }
}

pub mod plots {
    use crate::{AsPythonLitteral, PythonLitteral, PythonProgram};
    use std::io::Write;

    pub fn plot_xyargs<X: AsPythonLitteral, Y: AsPythonLitteral>(
        x: &X,
        y: &Y,
        args: &str,
    ) -> Result<std::process::Output, std::io::Error> {
        let mut program = PythonProgram::new();
        program.import_as("matplotlib.pyplot", "plt");
        writeln!(
            &program.file,
            "plt.plot({}, {}, {})",
            PythonLitteral(x),
            PythonLitteral(y),
            PythonLitteral(args)
        );
        program.write_line("plt.show()").run()
    }

    pub fn plot_xy<X: AsPythonLitteral, Y: AsPythonLitteral>(
        x: &X,
        y: &Y,
    ) -> Result<std::process::Output, std::io::Error> {
        let mut program = PythonProgram::new();
        program.import_as("matplotlib.pyplot", "plt");
        writeln!(
            &program.file,
            "plt.plot({}, {})",
            PythonLitteral(x),
            PythonLitteral(y),
        );
        program.write_line("plt.show()").run()
    }

    pub fn plot_y<Y: AsPythonLitteral>(y: &Y) -> Result<std::process::Output, std::io::Error> {
        let mut program = PythonProgram::new();
        program.import_as("matplotlib.pyplot", "plt");
        writeln!(&program.file, "plt.plot({})", PythonLitteral(y));
        program.write_line("plt.show()").run()
    }
}

#[macro_export]
macro_rules! plot {
    ($y: expr) => {
        pycall::plots::plot_y($y)
    };
    ($x: expr, $y: expr) => {
        pycall::plots::plot_xy($x, $y)
    };
    ($x: expr, $y: expr, $args: expr) => {
        pycall::plots::plot_xyargs($x, $y, $args)
    };
}

#[test]
fn run() {
    let join = std::thread::spawn(|| quick_plot(&(-50..50).map(|x| (-x * x)).collect::<Vec<_>>()));
    let mut program = PythonProgram::new();
    program
        .write_line("import matplotlib.pyplot as plt")
        .define_variable(
            "hello",
            &(-50..50).map(|x| (x * x) as f64).collect::<Vec<_>>(),
        )
        .write_line("print(hello)")
        .write_line("plt.plot(hello)")
        .write_line("plt.show()");
    println!("program: {}\r\n{}", program.file.path().display(), &program);
    let output = program.run().unwrap();
    join.join();
}