Commits

camlspotter committed 1663fdc

better interface

Comments (0)

Files changed (12)

     string
     tuple
     type
+    float
 
 %.idl: %.idl.in idlconvert.pl
     ./idlconvert.pl $< > $@
     
   open Autoapi
 
+  module KwdList : sig
+    val partition : (string * 'a) list -> 'a list * (string * 'a) list
+      (** if the assoc list into 'a's with "", and the others. Not tail recursive. *)
+  end = struct
+    let partition klst = List.fold_right (fun lv (lst, alst) -> match lv with
+      | ("", v) -> (v::lst, alst)
+      | _ -> (lst, lv::alst)) klst ([], [])
+  end
+
   module String = String
   module ByteArray = ByteArray
   module Number = Number
   module Dict = struct
     include Dict
     let new_proxy = DictProxy.new_
+    let from_list assoc =
+      let d = new_ () in
+      List.iter (fun (k,v) -> setItem d k v) assoc;
+      d
+    let from_string_list assoc =
+      let d = new_ () in
+      List.iter (fun (k,v) -> setItem d (String.fromString k) v) assoc;
+      d
   end
 
   module Index = Index
     include Object
 
     module X : sig
-      val call : [> _Callable ] t -> ?kwd:[> _Dict ] t -> [> _Object ] t list -> _Object t
+      val gen_call : [> _Callable ] t -> ?kwd:[> _Dict ] t -> [> _Object ] t list -> _Object t
 	(** Function call *)
-      val callObject : [> _Callable ] t -> [> _Object ] t list -> _Object t
+      val call : [> _Callable ] t -> [> _Object ] t list -> _Object t
 	(** Object method call *)
+      val kwd_call : [> _Callable ] t -> (string * [> _Object ] t) list -> _Object t
+        (** ML friendly generalized versino of call and callObject *)
+
       val obj : [> _Object ] t -> _Object t
 	(** Forget the type of the object *)
       val repr_string : [> _Object ] t -> string
       val str_string : [> _Object ] t -> string
 	(** obtain OCaml string of str *)
     end = struct
-      let call callable ?kwd list =
+      let gen_call callable ?kwd list =
 	_internal_call callable (Tuple.from_list list) kwd
-  
-      let callObject callable = function
+
+      let call callable = function
 	| [] -> _internal_callObject callable None
 	| list -> _internal_callObject callable (Some (Tuple.from_list list))
 
+      let kwd_call callable klist =
+        let lst, klst = KwdList.partition klist in
+        let kwd = if klst = [] then None else Some (Dict.from_string_list klst) in
+	_internal_call callable (Tuple.from_list lst) kwd 
+  
       let obj t : _Object t = unsafe_coerce t
 
       let repr_string t = String.asString (repr t)
     include Eval
 
     module X : sig
-      val callObject : [> _Callable ] t -> [> _Object ] t list -> _Object t
+      val call : [> _Callable ] t -> [> _Object ] t list -> _Object t
 	(** Function call *)
     end = struct
-      let callObject callable = function
+      let call callable = function
 	| [] -> _internal_callObject callable None
 	| list -> _internal_callObject callable (Some (Tuple.from_list list))
     end
     let _internal_call = Object._internal_call
     let _internal_callObject = Object._internal_callObject
     let call = Object.call
-    let callObject = Object.callObject
-    let evalCallObject = Eval.callObject
+    let kwd_call = Object.kwd_call
+    let eval = Eval.call
   end
 
   module Err = struct
     include X
   end
   
+  module Float = Float
+
   module Int = struct
     include Int
 
 module Err = Err
 module Int = Int
 module Class = Class
+module Float = Float
+
+module Tools : sig
+  val ( !:> ) : [> _Object ] t -> _Object t
+    (** Coercing an object to _Object t *)
+
+  val ( $. ) : [> _Object ] t -> string -> _Object t
+    (** Attribute access. Python's o.x *)
+
+  val ( $<> ) : [> _Dict ] t -> string -> _Object t
+    (** Dictionary access. Python's o[x] *)
+
+  val call : [> _Object ] t -> [> _Object ] t list -> _Object t
+
+  val kwd_call : [> _Object ] t -> (string * [> _Object ] t) list -> _Object t
+
+  val show_error : [> _Object ] t -> [> _Object ] t -> string
+  val prerr_error : [> _Object ] t -> [> _Object ] t -> unit
+    (** error printers *)
+    (* CR jfuruse: the first arguments are [> _Type ] t ? *)
+
+end = struct
+  (* Some useful tools available by open Api *)
+  let ( !:> ) o = (o :> _Object t)
+  let ( $. ) = Object.getAttrString (* Python's o.x *)
+  let ( $<> ) = Dict.getItemString (* Python's o[x] *)
+  let call o = Object.call (Callable.coerce o)
+  let kwd_call o = Object.kwd_call (Callable.coerce o)
+  let show_error typ detail = Printf.sprintf "%s: %s" (Py.String.asString (Object.str typ)) (Py.String.asString (Object.str detail))
+  let prerr_error typ detail = prerr_endline (show_error typ detail)
+end
+
+include Tools
 
 let _ = Base.initialize ()
     if( Is_block(v) ){
         return PyObject_val(Field(v, 0));
     } else {
-        printf("PyObject_opt_val: NULL\n");
+        // printf("PyObject_opt_val: NULL\n");
         return NULL;
     }
 }
 
 typedef [abstract] void FILE;
 
+// CR jfuruse: these inclusions must be automatic
 #include "err.idl"
 #include "object.idl"
 #include "base.idl"
 #include "dict.idl"
 #include "tuple.idl"
 #include "high.idl"
+#include "float.idl"
 

examples/matplotlib/OMakefile

+USE_OCAMLFIND=true
+
+OCAMLPACKS = opycaml
+
+OCAMLFLAGS += -annot -I .. -w A-26-31-10
+
+.DEFAULT: $(OCamlProgram finance_demo, finance_demo)
+
+.PHONY: clean
+clean:
+  rm -f $(filter-proper-targets $(ls R, .))

examples/matplotlib/OMakeroot

+########################################################################
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this file, to deal in the File without
+# restriction, including without limitation the rights to use,
+# copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the File, and to permit persons to whom the
+# File is furnished to do so, subject to the following condition:
+#
+# THE FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE FILE OR
+# THE USE OR OTHER DEALINGS IN THE FILE.
+
+########################################################################
+# The standard OMakeroot file.
+# You will not normally need to modify this file.
+# By default, your changes should be placed in the
+# OMakefile in this directory.
+#
+# If you decide to modify this file, note that it uses exactly
+# the same syntax as the OMakefile.
+#
+
+#
+# Include the standard installed configuration files.
+# Any of these can be deleted if you are not using them,
+# but you probably want to keep the Common file.
+#
+open build/C
+open build/OCaml
+open build/LaTeX
+
+#
+# The command-line variables are defined *after* the
+# standard configuration has been loaded.
+#
+DefineCommandVars()
+
+#
+# Include the OMakefile in this directory.
+#
+.SUBDIRS: .

examples/matplotlib/finance_demo.ml

+open Opycaml.Api
+
+let debug = Object.debug
+
+let import_module name = Module.getDict (Import.importModule name)
+
+let _ =
+  (* from pylab import * *)
+  let pylab = import_module "pylab" in
+
+  (* from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
+     DayLocator, MONDAY, timezone *)
+  let dates = import_module "matplotlib.dates" in
+
+  (* from matplotlib.finance import quotes_historical_yahoo, candlestick,\
+     plot_day_summary, candlestick2 *)
+  let finance = import_module "matplotlib.finance" in
+
+  (* import datetime *)
+  let datetime = import_module "datetime" in
+
+  let date = call (datetime $<> "date") in
+
+  (* date1 = datetime.date( 2004, 2, 1) *)
+  let date1 = date [ Int.fromLong 2004; Int.fromLong 2; Int.fromLong 1 ] in
+  debug date1 "date1";
+
+  let date2 = date [ Int.fromLong 2004; Int.fromLong 4; Int.fromLong 12 ] in
+  debug date2 "date2";
+
+  begin
+    try 
+      (* Intentionally calls date function w/o arguments *)
+      let date0 = date [] in
+      debug date0 "date0";
+      assert false
+    with
+    | Error (ty,detail) -> 
+        prerr_endline "Expected type error!";
+        debug ty "type";
+        debug detail "detail";
+  end;
+
+  let monday = dates $<> "MONDAY" in
+  debug monday "monday";
+
+  let dayLocator = dates $<> "DayLocator" in
+  debug dayLocator "DayLocator";
+
+  (* Class can be called as a function for New *)
+  let dayLocator_f = call (dates $<> "DayLocator") in
+
+  let alldays = dayLocator_f [] in
+  debug alldays "alldays";
+
+  let weekdayLocator = call (dates $<> "WeekdayLocator") in
+
+  let mondays = weekdayLocator [ monday ] in
+
+  let dateFormatter = call (dates $<> "DateFormatter") in
+
+  let weekFormatter = dateFormatter [ Py.String.fromString "%b %d" ] in
+  debug weekFormatter "weekFormatter";
+
+  let dayFormatter = dateFormatter [ Py.String.fromString "%d" ] in
+  debug dayFormatter "dayFormatter";
+
+  let quotes_historical_yahoo = call (finance $<> "quotes_historical_yahoo") in
+  debug (finance $<> "quotes_historical_yahoo") "quotes_historical_yahoo";
+ 
+  let quotes = 
+    try
+      quotes_historical_yahoo [ !:> (Py.String.fromString "INTC");
+                                date1;
+                                date2 ]
+    with
+    | Error (ty,detail) -> prerr_error ty detail; raise Exit
+  in
+
+  debug quotes "quotes";
+
+  let fig = call (pylab $<> "figure") [] in
+  debug fig "fig";
+
+  (* CR jfuruse: warnings for unit cases. lousy... *)
+  kwd_call (fig $. "subplots_adjust") [ "bottom", Float.fromDouble 0.2];
+  let ax = call (fig $. "add_subplot") [ Int.fromLong 111 ] in
+  debug ax "ax";
+
+  call (ax $. "xaxis" $. "set_major_locator") [ mondays ];
+  call (ax $. "xaxis" $. "set_minor_locator") [ alldays ];
+  call (ax $. "xaxis" $. "set_major_formatter") [ weekFormatter ];
+  (* call (ax $. "xaxis" $. "set_minor_formatter") [ dayFormatter ]; *)
+
+  (* #plot_day_summary(ax, quotes, ticksize=3) *)
+  kwd_call (finance $<> "candlestick") [ "", ax; "", quotes; "width", !:> (Float.fromDouble 0.6) ];
+
+  call (ax $. "xaxis_date") [];
+  call (ax $. "autoscale_view") [];
+  
+  kwd_call (pylab $<> "setp")
+    [ "", call (call (pylab $<> "gca") [] $. "get_xticklabels") []; 
+      "rotation", !:> (Int.fromLong 45); 
+      "horizontalalignment", !:> (Py.String.fromString "right") ];
+
+  call (pylab $<> "show") [];
+
+  ()
   let lowercase = Dict.getItemString dict "lowercase" in
   let capitalize = Dict.getItemString dict "capitalize" in
 
-  let res = Object.callObject (Callable.coerce capitalize) [lowercase] in
+  let res = Object.call (Callable.coerce capitalize) [lowercase] in
 
   (* String class is not accessible by String but Py.String, in order
      to avoid the name space collision with String in OCaml standard

examples/testoo.ml

   let lowercase = dict#getItemString "lowercase" in
   let capitalize = dict#getItemString "capitalize" in
 
-  let res = Object.callObject (Callable.coerce capitalize) [lowercase] in
+  let res = Object.call (Callable.coerce capitalize) [lowercase] in
 
   prerr_endline (OPy.String.coerce res)#asString;
 
     for $k (keys %mod){
 	print_module($k);
     }
-    # a dummy module to indicate the end of the file
-    print "module Unicode = struct end\n";
-    print "module List = struct end\n";
-    print "module Slice = struct end\n";
-    print "module Float = struct end\n";
-    print "module Long = struct end\n";
 }
 
 
 .DEFAULT: $(OCamlProgram from_string_iteration, from_string_iteration)
 .DEFAULT: $(OCamlProgram set_closure_string, set_closure_string)
+
+clean:
+  rm -f $(filter-proper-targets $(ls R, .))
     let stat = Gc.stat () in
     Format.eprintf "live_words: %d / maj-cor: %d@." stat.Gc.live_words stat.Gc.major_collections
 end
+
+module Option = struct
+  let map f = function
+    | None -> None
+    | Some v -> Some (f v)
+end