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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// Copyright 2018 Stefan Kroboth
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

#![recursion_limit = "512"]

extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use syn::*;

#[proc_macro_derive(ArgminSolver)]
pub fn argminsolver(input: TokenStream) -> TokenStream {
    // parse the input tokens into a syntax tree
    let input: DeriveInput = syn::parse(input).unwrap();

    let name = &input.ident;
    let gen = &input.generics.clone();
    let whe = &input.generics.where_clause;
    let attrs = input.attrs.clone();

    let brackets: &[_] = &['(', ')'];
    let quotes: &[_] = &['"', '"'];
    let mut conditions: Vec<Expr> = vec![];
    let mut logs_str: Vec<String> = vec![];
    let mut logs_expr: Vec<Expr> = vec![];
    let mut solver_name = name.to_string();
    let mut tts;
    for attr in attrs.iter() {
        tts = &attr.tts;
        let path = &attr.path;
        let path = &quote!(#path).to_string();
        if path == "solver" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            solver_name = attr.to_string();
        }
        if path == "stop" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            let stuff: Vec<&str> = attr.split("=>").map(|x| x.trim()).collect();
            let stop_condition = stuff[0].trim_matches(quotes).to_string();
            let stop_reason = stuff[1].to_string();
            let bla = &format!(
                "
                if {condition} {{
                    self.base.set_termination_reason(TerminationReason::{reason});
                    return TerminationReason::{reason};
                }}
                ",
                condition = stop_condition,
                reason = stop_reason
            );
            conditions.push(syn::parse_str(bla).unwrap());
        }
        if path == "log" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            let stuff: Vec<&str> = attr.split("=>").map(|x| x.trim()).collect();
            let text = stuff[0].trim_matches(quotes).to_string();
            logs_str.push(text);
            let expr = stuff[1].trim_matches(quotes).to_string();
            logs_expr.push(syn::parse_str(&expr).unwrap());
        }
    }

    let expanded = quote! {
        impl #gen ArgminSolver for #name #gen #whe {
            fn run(&mut self) -> Result<ArgminResult<Self::Parameters>, Error> {
                let total_time = std::time::Instant::now();

                // do the inital logging
                let logs = make_kv!(#(#logs_str => #logs_expr;)*);
                self.base.log_info(#solver_name, &logs)?;

                use std::sync::atomic::{AtomicBool, Ordering};
                use std::sync::Arc;

                let running = Arc::new(AtomicBool::new(true));

                #[cfg(feature = "ctrlc")]
                {
                    // Set up the Ctrl-C handler
                    use ctrlc;
                    let r = running.clone();
                    ctrlc::set_handler(move || {
                        r.store(false, Ordering::SeqCst);
                    })?;
                }

                self.init()?;

                while running.load(Ordering::SeqCst) {
                    // check first if it has already terminated
                    // This should probably be solved better.
                    // First, check if it isn't already terminated. If it isn't, evaluate the
                    // stopping criteria. If `self.terminate()` is called without the checking
                    // whether it has terminated already, then it may overwrite a termination set
                    // within `next_iter()`!
                    if !self.base.terminated() {
                        self.terminate();
                    }
                    // Now check once more if the algorithm has terminated. If yes, then break.
                    if self.base.terminated() {
                        break;
                    }

                    // Start time measurement
                    let start = std::time::Instant::now();

                    // execute iteration
                    let mut data = self.next_iter()?;

                    // End time measurement
                    let duration = start.elapsed();

                    // Set new current parameter
                    self.base.set_cur_param(data.param())
                             .set_cur_cost(data.cost());

                    // check if parameters are the best so far
                    if data.cost() <= self.base.best_cost() {
                        self.base.set_best_param(data.param())
                                 .set_best_cost(data.cost());
                    }

                    // logging
                    let mut log = self.base.kv_for_iter();
                    if let Some(ref mut iter_log) = data.get_kv() {
                        iter_log.push("time", duration.as_secs() as f64 +
                                              duration.subsec_nanos() as f64 * 1e-9);
                        log.merge(&mut iter_log.clone());

                    }
                    self.base.log_iter(&log)?;

                    // Write to file or something
                    self.base.write(&self.base.cur_param())?;

                    // increment iteration number
                    self.base.increment_iter();
                }

                // in case it stopped prematurely and `termination_reason` is still `NotTerminated`,
                // someone must have pulled the handbrake
                if self.base.cur_iter() < self.base.max_iters() && !self.base.terminated() {
                    self.base.set_termination_reason(TerminationReason::Aborted);
                }

                self.base.set_total_time(total_time.elapsed());

                let kv = make_kv!(
                    "termination_reason" => self.base.termination_reason();
                    "total_time" => self.base.total_time().as_secs() as f64 +
                                    self.base.total_time().subsec_nanos() as f64 * 1e-9;
                );

                self.base.log_info(
                    &format!("Terminated: {reason}", reason = self.base.termination_reason_text(),),
                    &kv,
                )?;

                Ok(self.base.result())
            }

            fn run_fast(&mut self) -> Result<ArgminResult<Self::Parameters>, Error> {
                self.init()?;

                loop {
                    // check first if it has already terminated
                    if !self.base.terminated() {
                        self.terminate();
                    }
                    // Now check once more if the algorithm has terminated. If yes, then break.
                    if self.base.terminated() {
                        break;
                    }

                    let mut data = self.next_iter()?;

                    // increment iteration number
                    self.base.increment_iter();

                    // Set new current parameter
                    self.base.set_cur_param(data.param())
                             .set_cur_cost(data.cost());

                    // check if parameters are the best so far
                    if data.cost() < self.base.best_cost() {
                        self.base.set_best_param(data.param())
                                 .set_best_cost(data.cost());
                    }
                }


                let mut kv = ArgminKV::new();
                Ok(self.base.result())
            }

            fn apply(&mut self, param: &Self::Parameters) -> Result<Self::OperatorOutput, Error> {
                self.base.apply(param)
            }

            fn gradient(&mut self, param: &Self::Parameters) -> Result<Self::Parameters, Error> {
                self.base.gradient(param)
            }

            fn hessian(&mut self, param: &Self::Parameters) -> Result<Self::Hessian, Error> {
                self.base.hessian(param)
            }

            fn cur_param(&self) -> Self::Parameters {
                self.base.cur_param()
            }

            fn cur_grad(&self) -> Self::Parameters {
                self.base.cur_grad()
            }

            fn cur_hessian(&self) -> Self::Hessian {
                self.base.cur_hessian()
            }

            fn set_cur_param(&mut self, param: Self::Parameters) {
                self.base.set_cur_param(param);
            }

            fn set_cur_grad(&mut self, grad: Self::Parameters) {
                self.base.set_cur_grad(grad);
            }

            fn set_cur_hessian(&mut self, hessian: Self::Hessian) {
                self.base.set_cur_hessian(hessian);
            }

            fn set_best_param(&mut self, param: Self::Parameters) {
                self.base.set_best_param(param);
            }

            fn modify(&self, param: &Self::Parameters, factor: f64) -> Result<Self::Parameters, Error> {
                self.base.modify(param, factor)
            }

            fn result(&self) -> ArgminResult<Self::Parameters> {
                self.base.result()
            }

            fn set_max_iters(&mut self, iters: u64) {
                self.base.set_max_iters(iters);
            }

            fn max_iters(&self) ->  u64 {
                self.base.max_iters()
            }

            fn increment_iter(&mut self) {
                self.base.increment_iter();
            }

            fn cur_iter(&self) -> u64 {
                self.base.cur_iter()
            }

            fn cur_cost(&self) -> f64 {
                self.base.cur_cost()
            }

            fn set_cur_cost(&mut self, cost: f64) {
                self.base.set_cur_cost(cost);
            }

            fn best_cost(&self) -> f64 {
                self.base.best_cost()
            }

            fn set_best_cost(&mut self, cost: f64) {
                self.base.set_best_cost(cost);
            }

            fn set_target_cost(&mut self, cost: f64) {
                self.base.set_target_cost(cost);
            }

            fn increment_cost_func_count(&mut self) {
                self.base.increment_cost_func_count();
            }

            fn increase_cost_func_count(&mut self, count: u64) {
                self.base.increase_cost_func_count(count);
            }

            fn cost_func_count(&self) -> u64 {
                self.base.cost_func_count()
            }

            fn increment_grad_func_count(&mut self) {
                self.base.increment_grad_func_count();
            }

            fn increase_grad_func_count(&mut self, count: u64) {
                self.base.increase_grad_func_count(count);
            }

            fn grad_func_count(&self) -> u64 {
                self.base.grad_func_count()
            }

            fn increment_hessian_func_count(&mut self) {
                self.base.increment_hessian_func_count();
            }

            fn increase_hessian_func_count(&mut self, count: u64) {
                self.base.increase_hessian_func_count(count);
            }

            fn hessian_func_count(&self) -> u64 {
                self.base.hessian_func_count()
            }

            fn add_logger(&mut self, logger: Box<ArgminLog>) {
                self.base.add_logger(logger);
            }

            fn add_writer(&mut self, writer: Box<ArgminWrite<Param = Self::Parameters>>) {
                self.base.add_writer(writer);
            }

            fn set_termination_reason(&mut self, reason: TerminationReason) {
                self.base.set_termination_reason(reason);
            }

            fn terminate(&mut self) -> TerminationReason {
                if self.base.cur_iter() >= self.base.max_iters() {
                    self.set_termination_reason(TerminationReason::MaxItersReached);
                    return TerminationReason::MaxItersReached;
                }

                if self.base.cur_cost() <= self.base.target_cost() {
                    self.set_termination_reason(TerminationReason::TargetCostReached);
                    return TerminationReason::TargetCostReached;
                }

                #(#conditions)*
                self.set_termination_reason(TerminationReason::NotTerminated);
                TerminationReason::NotTerminated
            }

            fn base_reset(&mut self) {
                self.base.reset();
            }
        }
    };
    expanded.into()
}

#[proc_macro_derive(ArgminOperator)]
pub fn argminoperator(input: TokenStream) -> TokenStream {
    // parse the input tokens into a syntax tree
    let input: DeriveInput = syn::parse(input).unwrap();

    let name = &input.ident;
    let gen = &input.generics.clone();
    let whe = &input.generics.where_clause;
    let attrs = input.attrs.clone();

    let brackets: &[_] = &['(', ')'];
    // let quotes: &[_] = &['"', '"'];
    let mut parameters: Option<Type> = None;
    let mut output: Option<Type> = None;
    let mut hessian_type: Option<Type> = None;
    let mut cost_function: Option<Ident> = None;
    let mut gradient: Option<Item> = None;
    let mut hessian: Option<Item> = None;
    let mut modify: Option<Item> = None;
    let mut tts;
    for attr in attrs.iter() {
        tts = &attr.tts;
        let path = &attr.path;
        let path = &quote!(#path).to_string();
        if path == "parameters_type" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            parameters = Some(syn::parse_str(attr).unwrap());
        }
        if path == "output_type" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            output = Some(syn::parse_str(attr).unwrap());
        }
        if path == "hessian_type" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            hessian_type = Some(syn::parse_str(attr).unwrap());
        }
        if path == "cost_function" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            cost_function = Some(syn::parse_str(attr).unwrap());
        }
        if path == "gradient" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            let tmp = format!(
                "fn gradient(&self, x: &Self::Parameters) -> Result<Self::Parameters, Error> {{ 
                    Ok({}(x))
                 }}",
                attr
            );
            gradient = Some(syn::parse_str(&tmp).unwrap());
        }
        if path == "hessian" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            let tmp = format!(
                "fn hessian(&self, x: &Self::Parameters) -> Result<Self::Hessian, Error> {{ 
                    Ok({}(x))
                 }}",
                attr
            );
            hessian = Some(syn::parse_str(&tmp).unwrap());
        }
        if path == "modify" {
            let tts2 = quote!(#tts).to_string();
            let attr = tts2.trim_matches(brackets).trim();
            let tmp = format!(
                "fn modify(&self, x: &Self::Parameters, scale: f64) -> Result<Self::Parameters, Error> {{ 
                    Ok({}(x, scale))
                 }}",
                attr
            );
            modify = Some(syn::parse_str(&tmp).unwrap());
        }
    }

    let expanded = quote! {
        impl #gen ArgminOperator for #name #gen #whe {
            type Parameters = #parameters;
            type OperatorOutput = #output;
            type Hessian = #hessian_type;

            fn apply(&self, param: &Self::Parameters) ->  Result<Self::OperatorOutput, Error> {
                Ok(#cost_function(param))
            }

            #gradient

            #hessian

            #modify
        }
    };
    expanded.into()
}