Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #5820 > unrolled thread

Creating Objects

Started byGabriel Landi <gtlandi@gmail.com>
First post2011-10-23 10:33 +0000
Last post2011-10-25 10:24 +0000
Articles 5 — 4 participants

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  Creating Objects Gabriel Landi <gtlandi@gmail.com> - 2011-10-23 10:33 +0000
    Re: Creating Objects Armand Tamzarian <mike.honeychurch@gmail.com> - 2011-10-24 09:17 +0000
    Re: Creating Objects "Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com> - 2011-10-24 09:17 +0000
    Re: Creating Objects Gabriel Landi <gtlandi@gmail.com> - 2011-10-25 10:25 +0000
    Re: Creating Objects A Retey <awnl@gmx-topmail.de> - 2011-10-25 10:24 +0000

#5820 — Creating Objects

FromGabriel Landi <gtlandi@gmail.com>
Date2011-10-23 10:33 +0000
SubjectCreating Objects
Message-ID<j80qhd$afd$1@smc.vnet.net>
Dear MathGroup (and perhaps some Wolfram employees),

Does anyone know how to create Objects in Mathematica, such as those produced by LinearModelFit or NDSolve`ProcessEquations?
For instance, let data be a set of statistical data. Then data["Mean"] would give me the mean, data["Values"] would return me the original values, etc.

Here is an example from LinearModelFit:

	data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};
	lm = LinearModelFit[data, x, x];
	Save["Model.txt",lm];

The saved output is

lm = FittedModel[{"Linear", {0.18644067796610198, 0.6949152542372881},
      {{x}, {1, x}}, {0, 0}}, {{1., 1., 1., 1.}}, {{0, 1}, {1, 0}, {3, 2},
      {5, 4}}, {{1., 0.}, {1., 1.}, {1., 3.}, {1., 5.}},
     Function[Null, Internal`LocalizedBlock[{x}, #1], {HoldAll}]]

Which has, basically, only the data and the fitted parameters. Nonetheless, by doing lm["FitResiduals"] it computes the residuals for me.

In my impression, this is as close as one can get to object-oriented programming in Mathematica, and would be a quite useful feature to use.
I haven't found any documentation on this. Anyone knowns?

Sincerely,

Gabriel Landi

[toc] | [next] | [standalone]


#5835

FromArmand Tamzarian <mike.honeychurch@gmail.com>
Date2011-10-24 09:17 +0000
Message-ID<j83af4$k55$1@smc.vnet.net>
In reply to#5820
On Oct 23, 9:33 pm, Gabriel Landi <gtla...@gmail.com> wrote:
> Dear MathGroup (and perhaps some Wolfram employees),
>
> Does anyone know how to create Objects in Mathematica, such as those produced by LinearModelFit or NDSolve`ProcessEquations?
> For instance, let data be a set of statistical data. Then data["Mean"] would give me the mean, data["Values"] would return me the original values, etc.
>
> Here is an example from LinearModelFit:
>
>         data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};
>         lm = LinearModelFit[data, x, x];
>         Save["Model.txt",lm];
>
> The saved output is
>
> lm = FittedModel[{"Linear", {0.18644067796610198, 0.6949152542372881},
>       {{x}, {1, x}}, {0, 0}}, {{1., 1., 1., 1.}}, {{0, 1}, {1, 0}, {3, 2},
>       {5, 4}}, {{1., 0.}, {1., 1.}, {1., 3.}, {1., 5.}},
>      Function[Null, Internal`LocalizedBlock[{x}, #1], {HoldAll}]]
>
> Which has, basically, only the data and the fitted parameters. Nonetheless, by doing lm["FitResiduals"] it computes the residuals for me.
>
> In my impression, this is as close as one can get to object-oriented programming in Mathematica, and would be a quite useful feature to use.
> I haven't found any documentation on this. Anyone knowns?
>
> Sincerely,
>
> Gabriel Landi


Darren Glosemeyer provided some info on how to do this

http://groups.google.com/group/comp.soft-sys.math.mathematica/browse_thread/thread/96759ba9dbce4c/0827f0d03f5abbd9

Might be useful if this was part of a HowTo in the documentation.

Mike

[toc] | [prev] | [next] | [standalone]


#5836

From"Oleksandr Rasputinov" <oleksandr_rasputinov@hmamail.com>
Date2011-10-24 09:17 +0000
Message-ID<j83ag3$k5a$1@smc.vnet.net>
In reply to#5820
On Sun, 23 Oct 2011 11:33:17 +0100, Gabriel Landi <gtlandi@gmail.com>  
wrote:

> Dear MathGroup (and perhaps some Wolfram employees),
>
> Does anyone know how to create Objects in Mathematica, such as those  
> produced by LinearModelFit or NDSolve`ProcessEquations?
> For instance, let data be a set of statistical data. Then data["Mean"]  
> would give me the mean, data["Values"] would return me the original  
> values, etc.
>
> Here is an example from LinearModelFit:
>
> 	data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};
> 	lm = LinearModelFit[data, x, x];
> 	Save["Model.txt",lm];
>
> The saved output is
>
> lm = FittedModel[{"Linear", {0.18644067796610198, 0.6949152542372881},
>       {{x}, {1, x}}, {0, 0}}, {{1., 1., 1., 1.}}, {{0, 1}, {1, 0}, {3,  
> 2},
>       {5, 4}}, {{1., 0.}, {1., 1.}, {1., 3.}, {1., 5.}},
>      Function[Null, Internal`LocalizedBlock[{x}, #1], {HoldAll}]]
>
> Which has, basically, only the data and the fitted parameters.  
> Nonetheless, by doing lm["FitResiduals"] it computes the residuals for  
> me.
>
> In my impression, this is as close as one can get to object-oriented  
> programming in Mathematica, and would be a quite useful feature to use.
> I haven't found any documentation on this. Anyone knowns?
>
> Sincerely,
>
> Gabriel Landi
>

There isn't actually any special trick to this, as the "objects" are just  
ordinary expressions with OwnValues, UpValues, DownValues, SubValues, etc.  
implementing whatever functionality is required. You can create your  
object by assigning these values inside a Module, amongst other  
approaches. Here's a simple example of a FIFO queue object with named  
("tagged") sub-queues:

In[1] :=
TagQueue /: New[TagQueue] :=
   Module[{TagQueue},

(* Define the sequence numbers for the head and tail of each subqueue \
on the first attempt to access their values. This ensures that an \
enqueue/dequeue operation cannot fail due to the lack of these \
definitions and thus avoids the need for a test as to whether a \
subqueue has been initialized before it is used. *)
    TagQueue[tag_]["Head" | "Tail"] :=
     TagQueue[tag]["Head"] = TagQueue[tag]["Tail"] = 1;

(* A new element is enqueued as in a typical FIFO queue by \
incrementing the sequence number of the tail element of the \
corresponding subqueue. A DownValue is then defined for the new item \
using the sequence number of the tail element as it previously was. *)
    TagQueue /: Enqueue[TagQueue[tag_], expr_] :=
     TagQueue[tag, TagQueue[tag]["Tail"]++] := Unevaluated[expr];

(* Dequeuing an element from a subqueue removes the DownValue for the \
dequeued element and increments the sequence number of the head \
element to refer to the next item in the subqueue. *)
    With[{NonEmptyQ = #["Head"] < #["Tail"] &},
     TagQueue /: Dequeue[TagQueue[tag_]?NonEmptyQ] :=
      Block[{val = TagQueue[tag, TagQueue[tag]["Head"]]},
       TagQueue[tag, TagQueue[tag]["Head"]++] =.; val
       ]
     ];

(* If a subqueue is empty (as in default case) then attempts to \
dequeue from it return $Failed. *)
    TagQueue /: Dequeue@TagQueue[tag_] = $Failed;

(* Mechanism for determining the number of elements currently held in \
a given subqueue. *)
    TagQueue /: Length@TagQueue[tag_] :=
     TagQueue[tag]["Tail"] - TagQueue[tag]["Head"];

(* Return the TagQueue (with Temporary attribute due to Module). *)
    TagQueue
    ];

In[2] :=
(* Instantiating the object *)
q = New[TagQueue]

Out[2] =
TagQueue$772

In[3] :=
(* Calling some methods *)
Enqueue[q["items"], "item 1"]

In[4] :=
Dequeue@q["items"]

Out[4] =
"item 1"

In[5] :=
Enqueue[q["numbers"], #] & /@ Range[10];

In[6] :=
Length@q["numbers"]

Out[6] =
10

In[7] :=
Dequeue@q["numbers"]

Out[7] =
1

In[8] :=
Table[Dequeue@q["numbers"], {10}]

Out[8] =
{2, 3, 4, 5, 6, 7, 8, 9, 10, $Failed}

In[9] :=
(* Destroying the object *)
Remove@Evaluate[q]

For more information about object-oriented programming in Mathematica  
(defining classes, etc.), I would recommend Roman Maeder's books: either  
"The Mathematica Programmer", or chapter 14 of "Computer Science with  
Mathematica" (see http://www.mathconsult.ch/showroom/pubs/CSM/). You may  
also like to have a look at this page, where the Classes.m file used in  
these books is available for download along with a (brief) usage example:  
http://library.wolfram.com/infocenter/Articles/3243/.

[toc] | [prev] | [next] | [standalone]


#5858

FromGabriel Landi <gtlandi@gmail.com>
Date2011-10-25 10:25 +0000
Message-ID<j862ri$5us$1@smc.vnet.net>
In reply to#5820
Thank you for the feedback guys.
This was quite helpful.

Gabriel

On Oct 24, 2011, at 7:14 AM, Oleksandr Rasputinov wrote:

> On Sun, 23 Oct 2011 11:33:17 +0100, Gabriel Landi <gtlandi@gmail.com> 
> wrote:
>
>> Dear MathGroup (and perhaps some Wolfram employees),
>>
>> Does anyone know how to create Objects in Mathematica, such as those 
>> produced by LinearModelFit or NDSolve`ProcessEquations?
>> For instance, let data be a set of statistical data. Then data["Mean"] 
>> would give me the mean, data["Values"] would return me the original 
>> values, etc.
>>
>> Here is an example from LinearModelFit:
>>
>> 	data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};
>> 	lm = LinearModelFit[data, x, x];
>> 	Save["Model.txt",lm];
>>
>> The saved output is
>>
>> lm = FittedModel[{"Linear", {0.18644067796610198, 0.6949152542372881},
>>      {{x}, {1, x}}, {0, 0}}, {{1., 1., 1., 1.}}, {{0, 1}, {1, 0}, {3, 
>> 2},
>>      {5, 4}}, {{1., 0.}, {1., 1.}, {1., 3.}, {1., 5.}},
>>     Function[Null, Internal`LocalizedBlock[{x}, #1], {HoldAll}]]
>>
>> Which has, basically, only the data and the fitted parameters. 
>> Nonetheless, by doing lm["FitResiduals"] it computes the residuals for 
>> me.
>>
>> In my impression, this is as close as one can get to object-oriented 
>> programming in Mathematica, and would be a quite useful feature to use.
>> I haven't found any documentation on this. Anyone knowns?
>>
>> Sincerely,
>>
>> Gabriel Landi
>>
>
> There isn't actually any special trick to this, as the "objects" are just 
> ordinary expressions with OwnValues, UpValues, DownValues, SubValues, etc. 
> implementing whatever functionality is required. You can create your 
> object by assigning these values inside a Module, amongst other 
> approaches. Here's a simple example of a FIFO queue object with named 
> ("tagged") sub-queues:
>
> In[1] :=
> TagQueue /: New[TagQueue] :=
>   Module[{TagQueue},
>
> (* Define the sequence numbers for the head and tail of each subqueue \
> on the first attempt to access their values. This ensures that an \
> enqueue/dequeue operation cannot fail due to the lack of these \
> definitions and thus avoids the need for a test as to whether a \
> subqueue has been initialized before it is used. *)
>    TagQueue[tag_]["Head" | "Tail"] :=
>     TagQueue[tag]["Head"] = TagQueue[tag]["Tail"] = 1;
>
> (* A new element is enqueued as in a typical FIFO queue by \
> incrementing the sequence number of the tail element of the \
> corresponding subqueue. A DownValue is then defined for the new item \
> using the sequence number of the tail element as it previously was. *)
>    TagQueue /: Enqueue[TagQueue[tag_], expr_] :=
>     TagQueue[tag, TagQueue[tag]["Tail"]++] := Unevaluated[expr];
>
> (* Dequeuing an element from a subqueue removes the DownValue for the \
> dequeued element and increments the sequence number of the head \
> element to refer to the next item in the subqueue. *)
>    With[{NonEmptyQ = #["Head"] < #["Tail"] &},
>     TagQueue /: Dequeue[TagQueue[tag_]?NonEmptyQ] :=
>      Block[{val = TagQueue[tag, TagQueue[tag]["Head"]]},
>       TagQueue[tag, TagQueue[tag]["Head"]++] =.; val
>       ]
>     ];
>
> (* If a subqueue is empty (as in default case) then attempts to \
> dequeue from it return $Failed. *)
>    TagQueue /: Dequeue@TagQueue[tag_] = $Failed;
>
> (* Mechanism for determining the number of elements currently held in \
> a given subqueue. *)
>    TagQueue /: Length@TagQueue[tag_] :=
>     TagQueue[tag]["Tail"] - TagQueue[tag]["Head"];
>
> (* Return the TagQueue (with Temporary attribute due to Module). *)
>    TagQueue
>    ];
>
> In[2] :=
> (* Instantiating the object *)
> q = New[TagQueue]
>
> Out[2] =
> TagQueue$772
>
> In[3] :=
> (* Calling some methods *)
> Enqueue[q["items"], "item 1"]
>
> In[4] :=
> Dequeue@q["items"]
>
> Out[4] =
> "item 1"
>
> In[5] :=
> Enqueue[q["numbers"], #] & /@ Range[10];
>
> In[6] :=
> Length@q["numbers"]
>
> Out[6] =
> 10
>
> In[7] :=
> Dequeue@q["numbers"]
>
> Out[7] =
> 1
>
> In[8] :=
> Table[Dequeue@q["numbers"], {10}]
>
> Out[8] =
> {2, 3, 4, 5, 6, 7, 8, 9, 10, $Failed}
>
> In[9] :=
> (* Destroying the object *)
> Remove@Evaluate[q]
>
> For more information about object-oriented programming in Mathematica 
> (defining classes, etc.), I would recommend Roman Maeder's books: either 
> "The Mathematica Programmer", or chapter 14 of "Computer Science with 
> Mathematica" (see http://www.mathconsult.ch/showroom/pubs/CSM/). You may 
> also like to have a look at this page, where the Classes.m file used in 
> these books is available for download along with a (brief) usage example: 
> http://library.wolfram.com/infocenter/Articles/3243/.
>

[toc] | [prev] | [next] | [standalone]


#5865

FromA Retey <awnl@gmx-topmail.de>
Date2011-10-25 10:24 +0000
Message-ID<j862pk$5u1$1@smc.vnet.net>
In reply to#5820
Hi,

> Does anyone know how to create Objects in Mathematica, such as those
> produced by LinearModelFit or NDSolve`ProcessEquations? For instance,
> let data be a set of statistical data. Then data["Mean"] would give
> me the mean, data["Values"] would return me the original values,
> etc.
>
> Here is an example from LinearModelFit:
>
> data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}}; lm = LinearModelFit[data, x,
> x]; Save["Model.txt",lm];
>
> The saved output is
>
> lm = FittedModel[{"Linear", {0.18644067796610198,
> 0.6949152542372881}, {{x}, {1, x}}, {0, 0}}, {{1., 1., 1., 1.}}, {{0,
> 1}, {1, 0}, {3, 2}, {5, 4}}, {{1., 0.}, {1., 1.}, {1., 3.}, {1.,
> 5.}}, Function[Null, Internal`LocalizedBlock[{x}, #1], {HoldAll}]]
>
> Which has, basically, only the data and the fitted parameters.
> Nonetheless, by doing lm["FitResiduals"] it computes the residuals
> for me.
>
> In my impression, this is as close as one can get to object-oriented
> programming in Mathematica, and would be a quite useful feature to
> use. I haven't found any documentation on this. Anyone knowns?

It is a common programming pattern in Mathematica to define a "data 
type" by using a special head and then write functions that work with 
that kind of data type by pattern matching for that head, e.g.:

mean[ts_timeseries]:=Mean[timeseries[[1,All,2]]]

ts = timeseries[{{0, 1}, {1, 2}, {2, 4}}]

mean[ts]

You can create the behavior you were asking for by just defining 
corresponding patterns for such a "data type", e.g.:

timeseries[data_]["Mean"] := Mean[data[[All, 2]]]

ts = timeseries[{{0, 1}, {1, 2}, {2, 4}}]

ts@"Mean"

Using patterns as shown above to access certain "properties" of that 
kind of data type is then just syntactic sugar. Using Strings instead of 
symbols is convenient when working with name spaces (Contexts) because 
it avoids shadowing problems with common identifiers.

If you wonder where those rules are stored, that is the SubValues:

SubValues[timeseries]

which are unfortunately only documented very sparse. You will also find 
that for the built in functions you don't find these rules in SubValues:

SubValues[FittedModel]

but that is also true for the more often used DownValues, which are also 
not shown for built in symbols. I can't say whether that means that 
there is necessarily more than such definitions "behind the scene" for 
the built in symbols like FittedModel.

If you are thinking about using that approach you might also want to 
look at Format, which will let you define a convenient formatting for 
your data type, which is especially interesting when working with larger 
datasets which you don't want to be shown within a notebook by accident, 
e.g.:

Format[timeseries[data___]] :=
  Interpretation["timeseries"["<>"], timeseries[data]]

or even:

Format[timeseries[data___]] :=
  Interpretation[
   "timeseries"[ListPlot[data, ImageSize -> Tiny, Frame -> True,
    FrameTicks -> False]], timeseries[data]]

To look at the underlying data, you will not need to save that to a 
file, looking at the InputForm or FullForm is usually good enough:

data = {{0, 1}, {1, 0}, {3, 2}, {5, 4}};
LinearModelFit[data, x, x] // InputForm


hth,

albert

[toc] | [prev] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web