Re: [Tutor] problem with a sub-class

2017-12-01 Thread Sydney Shall

On 30/11/2017 22:08, Alan Gauld via Tutor wrote:

On 30/11/17 15:37, Shall, Sydney wrote:


My problem is with constructing a sub-class.

My sub-class is constructed as follows:

import Population_ProductivityV24 as POCWP


Note that POCWP is an alias for the *module* Population_ProductivityV24.
It is not a class.


line 27 : class SimulateCycleZero(POCWP):


Here you define a class that subclasses your imported module.
Frankly I'm surprised that you don't get an error there
but hey...


line 28 : def __init__(self, dirname_p):


But this is now an init for a subclass of module.


The error message is as follows:

File
"/Users/sydney/AnacondaProjects/Capital/Capital_with_productivity/Current_Versions/Simulate_Cycle_Zero_V3.py",
line 27, in 
  class SimulateCycleZero(POCWP):

TypeError: module.__init__() takes at most 2 arguments (3 given)


So I'm guessing the use of a module to subclass
has confused things and I confess I'm not clear on
exactly what is going on and why you get this message.
But I'm pretty sure you don;t want to subclass your
imported module and thats the mistake.




Thanks to Alan and Peter for explaining sub-classing to me. I understand 
a bit better now. My program is corrected and does not give the error 
any more.



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New Item

2017-10-15 Thread Sydney Shall

On 28/09/2017 11:46, Peter Otten wrote:

larrystale...@comcast.net wrote:


I am very new to Python and appreciate the input as I was able to fully
install Python with all needed libraries (i.e., numpy, pandas, etc.).
However, I now have an application question in needed to construct a 2D
Histogram.

Basically, I have an Excel file that includes three columns:
Column 1 - Gender (Male or Female)
Column 2 - Height (in inches)
Column 3 - Hand Span (in inches)


I have yet to grok your code samples, but my feeling is that your approach
is too low-level. Do you mean something like

http://matplotlib.org/examples/pylab_examples/hist2d_demo.html

by "2d histograms"? That would require very little code written by yourself:

import pandas as pd
from matplotlib import pyplot

filename = "size.xls"
sheetname = "first"

data = pd.read_excel(filename, sheetname)

for index, sex in enumerate(["female", "male"], 1):
 pyplot.figure(index)
 subset = data[data["Gender"] == sex]
 pyplot.hist2d(subset["Height"].values, subset["Hand Span"].values)

pyplot.show()





data=readExcel(excelfile)
X=np.array(data[:,1],dtype=float);
S=np.array(data[:,2],dtype=float);
T=np.array(data[:,0],dtype=str);




Finally, is my intended coding for the actual 2D histogram. I will get min
and max from the height and hand span arrays. Note I am still learning
Python and looping is new to me:




# Define histogram classifier to build histogram using two variables
def Build1DHistogramClassifier(X, S, smin, smax,T,B,xmin,xmax):
HF=np.zeros(B).astype('int32');
HM=np.zeros(B).astype('int32');
binindices1=(np.round(((B-1)*(X-xmin)/(xmax-xmin.astype('int32');
binindices2=(np.round(((B-1)*(S-smin)/(smax-smin.astype('int32');
for i,b in enumerate(binindices1):
for i,c in enumerate(bindindices2):
if T[i]=='Female':
HF[b,c]+=1;
else:
HM[b,c]+=1;
return [HF, HM]


Hi,

I have a similar problem, but my data is not in excel but is in 
OpenOffice "Spreadsheet', but not in "Database".


My question is can I use a similar simple procedure as that given by 
Peter Otten.


Ta muchly.



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Does matplotlib.finance still work?

2017-08-25 Thread Sydney Shall

On 24/08/2017 18:46, Alan Gauld via Tutor wrote:

On 24/08/17 14:51, C W wrote:


I have the following code, I get an error at the first line.


So don't make us guess. What is the error(full text please)?


from matplotlib.finance import quotes_historical_yahoo_ochl


And what does a dir() show for matplotlib.finance?
Are you sure the name is spelled right etc?


I have heard this package is either upgraded or replaced. If so, what do
you recommend?


Contact its author perhaps?




Is this the answer, perhaps.

>>>import matplotlib

>>>dir(matplotlib.finance)
>>>Traceback (most recent call last):

  File "", line 1, in 
dir(matplotlib.finance)

  AttributeError: module 'matplotlib' has no attribute 'finance'

Thanks to Alan G? for his excellent teaching.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unitest with random inputs

2017-07-19 Thread Sydney Shall

On 19/07/2017 18:56, Steven D'Aprano wrote:

On Wed, Jul 19, 2017 at 06:08:57PM +0200, Sydney Shall wrote:





(I haven't tested that code myself, so please try it, and if it doesn't
work for some reason, let us know on the mailing list and somebody can
fix it.)

But... I'm rather surprised that you need this test. Are you sure that
your array capitalsadvanced will *always* contain at least one Not A
Number value? Unless you put one in yourself, NANs generally indicate
that a mathematical error has occurred somewhere.



Steven,

Thanks again.

I started this precisely because I also thought and still think, that 
the origin of my problem is a mathematical error somewhere.


However, when I use predetermined input values, the errors are absent. 
They only appear when I use the random function. Although it should not 
be the case, I wondered whether the random function was feeding in a 
zero, because the errors seem to involve an invalid value after a 
true-divide according to some of the error reports earlier. So, my first 
step was to try and see if there are any zeros in the array that is used 
first. The tests say that the type and the length of the array is 
correct. But how do I test for a zero in a numpy.ndarray?



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unitest with random inputs

2017-07-19 Thread Sydney Shall

On 19/07/2017 18:42, Steven D'Aprano wrote:

On Wed, Jul 19, 2017 at 05:01:53PM +0200, Sydney Shall wrote:

[...]

  def test_zero_in_capitalsadvanced(self):
 self.assertIn(self.capitalsadvanced, 0.0)

The error message is:

Traceback (most recent call last):

[...]

in assertIn
 if member not in container:
TypeError: argument of type 'float' is not iterable


You are trying to test whether capitalsadvanced is in 0.0. Reverse the
arguments:

 self.assertIn(0.0, self.capitalsadvanced)

which will test whether 0.0 is in self.capitalsadvanced.



FAILED (failures=9, errors=1)

The failures all arise from a 'nan'.
It is this problem that I am trying to resolve.


Well, since you don't show us what those failing tests are, we cannot
possibly tell you how to fix them.

Start by showing us *one* failing test, and what the failure is.



Thank you Steve.

The remaining 'nan' problems are shown below.

runfile('/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py', 
wdir='/Users/sydney/Capital/Capital_with_productivity/Current_Versions')
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1582: 
RuntimeWarning: invalid value encountered in true_divide


/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1637: 
RuntimeWarning: invalid value encountered in true_divide

  constantcapitals is divided, element-wise by the array
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1665: 
RuntimeWarning: invalid value encountered in true_divide

  capitalsadvanced.
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1695: 
RuntimeWarning: invalid value encountered in true_divide

  The output is a numpy array of floats; and they are ratios of (Variable
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1729: 
RuntimeWarning: invalid value encountered in true_divide

  The method returns is a numpy array of floats; the ratios of (Variable
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1758: 
RuntimeWarning: invalid value encountered in true_divide

  The method returns a numpy array of floats, which are the ratios of
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1787: 
RuntimeWarning: invalid value encountered in true_divide

  The method returns a numpy array of floats which are the individual
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:1816: 
RuntimeWarning: invalid value encountered in true_divide

  The method returns a numpy array of floats which are the ratios of (New
..FF.F.FFF..FF...F.../Users/sydney/anaconda/lib/python3.6/unittest/case.py:1077: 
FutureWarning: elementwise comparison failed; returning scalar instead, 
but in the future will perform elementwise comparison

  if member not in container:
F../Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:2311: 
RuntimeWarning: invalid value encountered in double_scalars

  values in UCC.
/Users/sydney/Capital/Capital_with_productivity/Current_Versions/PopulationOfCapitalsWithProductivityV16_Python36.py:2256: 
RuntimeWarning: invalid value encountered in double_scalars




I have looked carefully at the lines indicated and they almost all 
involve 4 specific numpy.ndarrays. I suspect from the logic that they 
all results from the commonest array in the list.


The last error is different, but I belie that it is related.



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unitest with random inputs

2017-07-19 Thread Sydney Shall

On 19/07/2017 18:05, Alan Gauld via Tutor wrote:

On 19/07/17 16:01, Sydney Shall wrote:

I am learning to use unittest.




   def test_zero_in_capitalsadvanced(self):
  self.assertIn(self.capitalsadvanced, 0.0)


Remember the interpreter...



help(unittest.case.assertIn)

Help on function assertIn in module unittest.case:

assertIn(self, member, container, msg=None)
 Just like self.assertTrue(a in b), but with a nicer default message.
~


The error message is:

  self.assertIn(self.capitalsadvanced, 0.0)
File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
1077, in assertIn
  if member not in container:
TypeError: argument of type 'float' is not iterable


The obvious float is 0.0
The likely container is self.capitalsadvanced

They are reversed according to the help screen.

HTH

My apologies for giving you extra work. I am in fact a very long sitting 
member of the list. Ever since kindergarden. You taught me to walk.

I used thw wrong email account.

Thanks. Yes, that cures one problem. Also thanks for the guidance. It is 
most useful.


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unitest with random inputs

2017-07-19 Thread Sydney Shall

On 19/07/2017 17:43, Peter Otten wrote:

Sydney Shall wrote:


I am learning to use unittest.

I have written a program that runs as it should.
247 tests give me a satisfactory answer.

I have now added one more test and I get an error which I do not
understand.

The two relevant tests are:

   def test_type_capitalsadvanced(self):
  self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)

   def test_zero_in_capitalsadvanced(self):
  self.assertIn(self.capitalsadvanced, 0.0)

The error message is:

Traceback (most recent call last):
File


"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py",

line 320, in test_zero_in_capitalsadvanced
  self.assertIn(self.capitalsadvanced, 0.0)
File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
1077, in assertIn
  if member not in container:
TypeError: argument of type 'float' is not iterable

Final output from the tests is :

Ran 247 tests in 1.179s

FAILED (failures=9, errors=1)

The failures all arise from a 'nan'.


I don't think so. To fix the traceback shown above you have to swap the
arguments in assertIn():

 def test_zero_in_capitalsadvanced(self):
 self.assertIn(0.0, self.capitalsadvanced)

Digression: once this is done you may still get failures when searching for
NaN in a sequence as it does not compare equal to itself:


nan = float("nan")
nan == nan

False

a = numpy.array([nan])
nan in a

False

This is how it should be (*), but unfortunately Python's builtin
list/set/dict/tuple all assume that obj is obj implies obj == obj which
makes the result of containment test hard to predict:


nan in [nan]

True

nan in [float("nan")]

False


(*) See for example
<https://en.wikipedia.org/wiki/Floating-point_arithmetic>:
"every NaN compares unequal to every value, including itself"


It is this problem that I am trying to resolve.

My problem is that the first test tells me correctly that the object
capitalsadvanced is a numpy.ndarray. But the second test error message
says it is a float.

I should add that the program creates the initial data set by making use
of the random function which is given a mean to work with. Thus each
test run will be with different input data. But repeated tests show the
same errors.

When I run the same tests with predetermined, fixed data I get no errors
and no 'nan' errors.

Any guidance will be very welcome.





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Peter,

Thanks for your comment.
This has helped to cure the first error.

For the second error, regarding 'nan' finding 'nan', I received the 
following output.



FAIL: test_nan_in_capitalsadvanced (__main__.TestPOC)
--
Traceback (most recent call last):
  File 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
line 323, in test_nan_in_capitalsadvanced

self.assertIn('nan', self.capitalsadvanced)
AssertionError: 'nan' not found in array([ 12026.72641072, 
12434.53700436,  12185.56314119, ...,

12488.04714281,  12479.4662866 ,  12310.66016998])

Could I use assertNotIn with the other problems?

Thanks again.

Sydney

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] unitest with random inputs

2017-07-19 Thread Sydney Shall

I am learning to use unittest.

I have written a program that runs as it should.
247 tests give me a satisfactory answer.

I have now added one more test and I get an error which I do not understand.

The two relevant tests are:

 def test_type_capitalsadvanced(self):
self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)

 def test_zero_in_capitalsadvanced(self):
self.assertIn(self.capitalsadvanced, 0.0)

The error message is:

Traceback (most recent call last):
  File 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py", 
line 320, in test_zero_in_capitalsadvanced

self.assertIn(self.capitalsadvanced, 0.0)
  File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line 
1077, in assertIn

if member not in container:
TypeError: argument of type 'float' is not iterable

Final output from the tests is :

Ran 247 tests in 1.179s

FAILED (failures=9, errors=1)

The failures all arise from a 'nan'.
It is this problem that I am trying to resolve.

My problem is that the first test tells me correctly that the object 
capitalsadvanced is a numpy.ndarray. But the second test error message 
says it is a float.


I should add that the program creates the initial data set by making use 
of the random function which is given a mean to work with. Thus each 
test run will be with different input data. But repeated tests show the 
same errors.


When I run the same tests with predetermined, fixed data I get no errors 
and no 'nan' errors.


Any guidance will be very welcome.


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to write the __str__ function

2017-05-15 Thread Sydney Shall

On 15/05/2017 01:27, Alan Gauld via Tutor wrote:

On 14/05/17 19:03, Sydney Shall wrote:


The code that I have so far is as folows:

  def __str__(self):
 return("\n"
"   Output from __str__ of POCWP. "
"\n"
"\n After the first turnover, during the "
"'Population Of Capitals Init' cycle,"
"\n the productivities were raised from 1.0 "
"\n to a specific Unit Constant Capital (UCC) "
"for each specific capital: "
"\n The input value for the mean of UCC "
"was %7.5f" % (self.ucc),


Here endeth the first string


"\n The fractional sigma (FractionalSTD)"
" of UCC that was input was %7.5f " % (self.fractsigma_ucc))


And here the second. Returning two strings separated
by a comma makes it a tuple. Instead put the two values in a tuple at
the end of a single concatenated string.

And while at it make life easier for your self and use triple quotes:

def __str__(self):
return """
   Output from __str__ of POCWP.

After the first turnover, during the
'Population Of Capitals Init' cycle,
the productivities were raised from 1.0
to a specific Unit Constant Capital (UCC)
for each specific capital:
 The input value for the mean of UCC was %7.5f
 The fractional sigma (FractionalSTD) of UCC that was input was %7.5f
""" % ( self.ucc, self.fractsigma_ucc)

Tweak the formatting to suit.

However, I'm not sure thats really a good use of __str__,
I might be tempted to make that an explicit method that's
called pprint()  - for pretty-print - or somesuch.
__str__() methods are usually a fairly cocise depiction
of the objects state that you can embed in a bigger string.

Maybe pprint() would look like

def pprint(self):
return """
   Output from __str__ of POCWP.

After the first turnover, during the
'Population Of Capitals Init' cycle,
the productivities were raised from 1.0
to a specific Unit Constant Capital (UCC)
for each specific capital: %s""" % self

And __str__()

def __str__(self):
   return """
The input value for the mean of UCC was %7.5f
The fractional sigma (FractionalSTD) of UCC that was input was %7.5f """
% (self.ucc, self.fractsigma_ucc)

Thus pprint() uses str() to create the long version while str()
just gives the bare bones result.

Just a thought.


Here endeth the second (! -presumptious?) string.

"""I would like to thank you all for the five lessons.

The advice of course gave me several useful ways of outputting data.

I believe I now have a better understanding of output."""

Many thanks.


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How to write the __str__ function

2017-05-14 Thread Sydney Shall
I need some advice that I have been embarrased to ask for, because I 
think that my error is so elementary.


I have written, as advised by the tutors, a complex program in a topic 
that interests me. The program works well and the tests are OK.


Now I want to add a __str__ function, which I thought would be 
straightforward. But I cannot get it right.


The code that I have so far is as folows:

 def __str__(self):
return("\n"
   "   Output from __str__ of POCWP. "
   "\n"
   "\n After the first turnover, during the "
   "'Population Of Capitals Init' cycle,"
   "\n the productivities were raised from 1.0 "
   "\n to a specific Unit Constant Capital (UCC) "
   "for each specific capital: "
   "\n The input value for the mean of UCC "
   "was %7.5f" % (self.ucc),
   "\n The fractional sigma (FractionalSTD)"
   " of UCC that was input was %7.5f " % (self.fractsigma_ucc))

The error message is:

TypeError: __str__ returned non-string (type tuple)

When I omit either or both of the objects; self.ucc or 
self.fractsigma_ucc, the code works fine.


So, I guess my code has an error. But I cannot detect the error.

Guidance would be much appreciated.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] genfromtxt and dtype to convert data to correct format

2016-05-18 Thread Sydney Shall

On 18/05/2016 14:14, Ek Esawi wrote:

OPS! Sorry, I made a mistake on the posting. My output is in a string
format as shown below. I want the 1st and 8th integers, the 3rd string
which is OK as, the 2nd date and the rest time. I tried several
combinations of dtype but could not get the date and time data to without
the single quote -string format.




[ (b'312171', '1995-07-01', b'Old', '13:37:00', '01:43:00', '04:42:00',
'13:16:00', b'162', '13:19:00')
 (b'358237', '1993-05-25', b'Old', '12:22:00', '01:31:00', '04:16:00',
'12:03:00', b'160', '12:13:00')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Try the following;

line1 = [ (b'312171', '1995-07-01', b'Old', '13:37:00', '01:43:00', 
'04:42:00','13:16:00', b'162', '13:19:00')]
line2 = [(b'358237', '1993-05-25', b'Old', '12:22:00', 
'01:31:00','04:16:00','12:03:00', b'160', '12:13:00')]


item1A = line1[0][0]
item1B = line1[0][7]
item2A = line2[0][0]
item2B = line2[0][7]
print item1A, item1B
print item2A, item2B


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Fasta Identy

2016-03-08 Thread Sydney Shall

Dear Ali,

I suggest your best way is to use the resource at the EMBL or the 
National Library of Congress, NIH, resources.


There you can compare your FASTA sequences with authentic databases. The 
programs know about FASTA and will recognise the format. It will 
identify the gene for you. And it will give you a link to all the 
available data on that gene.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] idle??

2016-01-14 Thread Sydney Shall

On 13/01/2016 23:10, Danny Yoo wrote:

So, where does IDLE fit into this


IDLE is a sad little “IDE”, which is really ugly, because it’s written
in Tk. It lacks many IDE features. It comes with a really basic
debugger (that doesn’t even highlight the line that is being currently
executed…), function signature hinting, and some code completion.

And it doesn’t even do something as basic as line numbering.


Hi Chris,

The quality of a beginner-level IDE might not necessarily be based on
the number of features it has.  For someone who's starting out, IDLE
is probably fine because it gets out of your way.  It lets you type
programs and evaluate them.  For a beginner, that might just be enough
to focus on learning the language.


(Aside: I've had the contrary experience with Eclipse, for example,
which is as full-featured as they come, but makes me feel like I'm
staring at the flight controls of a space shuttle, with all this stuff
about launchers and Luna and such.  I can get productive with it  It
takes my a long time to learn.  I suppose I could say the same thing
about Emacs.)


That is, many features might be a *distraction* from learning to
program.  Tools for beginners should be measured by criteria for
learning, and that might not match with the features we care about as
professional developers.  But maybe that's a controversial opinion.

I think IDLE is ok for what it's designed for: to provide a simple,
textual environment for writing and running simple Python programs.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


I was a beginner who began with >idle< following advice from this list.
I found it invaluable for the reason Danny gives. More complex 
environments befuddled me, and distracted me from learning Python.

I do not use it any longer. I now use IPython which I like a lot.
But for beginners I would recommend it, speaking as a debutante myself.

I hope that Ma Laura gets better soon. But please take care and have it 
seen to or you will have arthritis later. I have never met nor 
corresponded with the fine woman, but I think she is >terrible> [in 
French, otherwise in English wonderful.]


--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittest with random population data

2015-06-02 Thread Sydney Shall

On 31/05/2015 03:00, Cameron Simpson wrote:

On 30May2015 12:16, Sydney Shall s.sh...@virginmedia.com wrote:

Following advice from you generous people, I have chosen a project
that interests me, to develop some knowledge of python.
My projest is a simulation of a biological population.
I have a base class and a simulation function, which uses instances of
the class.
This, after many months of work and lots of advice, now seems to work
well. It generates sensible data and when I write a small test program
it gives sensible output.
Now I want to learn to use unittest.
I have written a unittest class which works OK.
But the problem I have is that because I use the random module to
populate my initial arrays, my data is not strictly predictable even
though I am using seed(0). So the tests return many *fails* because
the numbers are not exactly correct, although they are all rather
close, consistent with the sigma value I have chosen for the spread of
my population. I do of course use *almostEqual* and not *Equal*.


First of all, several people have posted suggestions for getting
identical results on every run.

However, there is another approach, which you might consider. (And use
in addition, not inseadt of, the reproducable suggestions).

It is all very well to have a unit test that runs exactly the same with
a test set of data - it lets you have confidence that algorithm changes
do not change the outcome. But on for that data set.

You say that your results are all rather close, consistent with the sigma
value I have chosen for the spread of my population. I would advocate
making some contraint tests that verify this property for _any_ input
data set.

Then you can run with random and _changing_ input data sets to verify
that your code produces the expected _kind_ of results with many data sets.

So you would have one test which ran with a fixed data set which
confirms preidctable unchanging results. And you have other tests with
run with randomly chosen data and confirms that outcomes fall within the
parameters you expect. You can apply those checks (outcome in range)
to both sets of tests.

As an exmaple, I have a few classes which maintain data structures which
are sensitive to boundary conditions. The glaring example is a numeric
range class which stores contiguous ranges efficiently (a sequence of
(low,high) pairs). It has a few add/remove operations which are meant to
maintain that sequence on ordered minimal form. cutting and merging
adjacent ranges is very easy to get wrong, very sensitive to off-by-one
logic errors.

So my tests for this class include some random tests which do random
unpredictable add/remove operations, and run a consistency check on the
object after each operation. This gives me good odds of exercising some
tricky sequence which I have not considered explicitly myself.

You can see the test suite here:

  https://bitbucket.org/cameron_simpson/css/src/tip/lib/python/cs/range_tests.py

It has a bunch of explicit specific tests up the top, and then the
random consistency test down the bottom as test30random_set_equivalence.

Cheers,
Cameron Simpson c...@zip.com.au

MS-Word is Not a document exchange format - Jeff Goldberg
http://www.goldmark.org/netrants/no-word/attach.html


Cameron,
Thanks for your most helpful reply.
I have studied the material you indicated and it has been most helpful. 
I think that I have understood the principle involved, but I have had 
some problem implementing it.


The range tests are mostly clear to me but there is one aspect I cannot 
follow.
You use in this suite imports from Range, including Range, overlap, 
spans and Span.
Are these programs that you have written? If so, are they specific to 
your set up or are they generic? If so, is it possible to obtain these 
programs?
I have established a very primitive test suite based on your cs.range 
notions and it works fine, but it would be better, I am sure, to do it 
properly.


Finally, I have one comment for the respected Moderator, if he is not 
out on a walk in the highlands in this cold  and wet weather.


I have taken the liberty of raising my problem here rather than 
elsewhere, because I have observed that the biological and bio-medical 
community, who always come late to new notions, is now rapidly 
discovering  python. A great deal of work in these fields involve either 
stochastic simulations or statistical problems of analysis. The latter 
are more or less straight-forward, but the simulations are not.


Thanks for all the help. You people are a model of how we could perhaps 
civilize humanity.




--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittest with random population data

2015-06-02 Thread Sydney Shall

On 02/06/2015 07:59, Steven D'Aprano wrote:

Please keep your replies on the tutor list, so that others may offer
advice, and learn from your questions.

Thanks,

Steve

On Mon, Jun 01, 2015 at 06:03:08PM +0100, Sydney Shall wrote:

On 31/05/2015 00:41, Steven D'Aprano wrote:

On Sat, May 30, 2015 at 12:16:01PM +0100, Sydney Shall wrote:


I have written a unittest class which works OK.
But the problem I have is that because I use the random module to
populate my initial arrays, my data is not strictly predictable even
though I am using seed(0).


Please show us how you populate your arrays, because what you describe
sounds wrong. Seeding to the same value should give the same sequence of
values:

py import random
py random.seed(0)
py a = [random.random() for i in range(10**6)]
py random.seed(0)
py b = [random.random() for i in range(10**6)]
py a == b
True



Thank you for the advice Steven.
I was of course aware that I had to use random.seed(0), which I had
done. I was puzzled by the fact that it did not give me reprocibly
results, which it did when I was learning python. But because you drew
attention to the problem, I have looked at again. I surmised that
perhaps I had put the seed statement in the wrong place. I have tried
several places, but I always get the sam spread of results.

Perhaps, to help get advice I should explain that I populate a a list thus:
  self.ucc = np.random.normal(self.mean_ucc, self.sigma_ucc, 200)
This does give me list of 200 slightly different numbers.
The mean_ucc is always 15.0 and the sigma value is always 3.75.
The actual mean and sigma of the random numbers is checked that it is
within 5.0% of 15.0 and 3.75 respectively.
Following your advice I did a little test. I repeated a little test
program that I have written, which gives me sensible and proper results.
I repeated the test 8 times and a then noted a useful output result.
When I plot the actual mean of the population used against the output
result I chose, I obtain a perfect straight line, which I should.

Now I still think that I am using the random.seed(0) either incorrectly
or in the wrong place.
If there is any other information that might clarify my problem, I will
be grateful to be told.
I would be most grateful for any guidance you may have, indicating where
I should look for what I suspect is a beginner's error.

--
Sydney




Apolgies. I thought that I had dione so. I will be more careeful infuture.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] unittest with random population data

2015-05-30 Thread Sydney Shall

MAC OSX 10.10.3
Enthought Python 2.7

I am an almost beginner.

Following advice from you generous people, I have chosen a project that 
interests me, to develop some knowledge of python.

My projest is a simulation of a biological population.
I have a base class and a simulation function, which uses instances of 
the class.
This, after many months of work and lots of advice, now seems to work 
well. It generates sensible data and when I write a small test program 
it gives sensible output.

Now I want to learn to use unittest.
I have written a unittest class which works OK.
But the problem I have is that because I use the random module to 
populate my initial arrays, my data is not strictly predictable even 
though I am using seed(0). So the tests return many *fails* because the 
numbers are not exactly correct, although they are all rather close, 
consistent with the sigma value I have chosen for the spread of my 
population. I do of course use *almostEqual* and not *Equal*.
So, I would be very grateful for guidance. How does one proceed in this 
case? Should I simply create an arbitrary array or value to input into 
the function that I want to test?

I would be grateful for any guidance.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] What exactly is state?

2015-03-02 Thread Sydney Shall

I am a beginner and I am now at the strage of learning to write unittests.
I have followed the current discussion entitled How to test a class in 
pyhton, and I am not clear precisely what is meant by state. In its 
common meaning I can see some relevance. But is there a technical aspect 
to the notion. I see it mentioned often and feel rather uncomfortable 
that I know so little about it.

I have deliberately started a new thread.
Thanks.
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is state?

2015-03-02 Thread Sydney Shall

On 02/03/2015 18:03, Dave Angel wrote:

On 03/02/2015 11:25 AM, Sydney Shall wrote:

I am a beginner and I am now at the strage of learning to write
unittests.
I have followed the current discussion entitled How to test a class in
pyhton, and I am not clear precisely what is meant by state. In its
common meaning I can see some relevance. But is there a technical aspect
to the notion. I see it mentioned often and feel rather uncomfortable
that I know so little about it.
I have deliberately started a new thread.
Thanks.


When I started composing this, there were no other replies.  Sorry for
any duplication caused by that.

Starting with a dictionary definition:

http://www.merriam-webster.com/dictionary/state
the overall physical condition of something : the ability of something
to be used, enjoyed, etc.

Others:


The particular condition that someone or something is in at a specific
time

In computer science and automata theory, the state of a digital logic
circuit or computer program is a technical term for all the stored
information, at a given instant in time, to which the circuit or program
has access.

That last comes the closest to what I'd like to explain.

For a given fragment of executing code, the state includes all local
variables, all parameters, all closures, all visible globals (ie the
ones that *could* be visible to the code.  It also includes indirectly
the values of all environment variables, lots of system information like
the current directory, the time, the network IP address.  It also
includes the current phase of the moon, the astrological sign of the
current president of France, and the number of specs of sand on the
eastern shore of a certain Martian lake.

Thank you very much, Joel, Danny, Alan and Dave.
Your explanations are all very clear and very enlightening.
I shall have to change several of my unittests now. In good time.
I am particularly pleased with the examples; they clarify matters 
considerably for me.


Out of subject, I wonder from this exchange whether teaching should not 
always involve at least several teachers. Your replies are very 
complimentary!



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittest for: Raises an exception

2015-02-19 Thread Sydney Shall

On 18/02/2015 20:40, Ben Finney wrote:

Sydney Shall s.sh...@virginmedia.com writes:


My test code is the following:

def test_func_getSurplusLabourTime_Exc(self):

self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc))

[This last line should indented, but it refuses to do so!]


What is “it” which refuses to indent your text? You might need to use a
better message composition tool.

If you're typing into a Web application, please see the discussion
happening in this forum about appropriate email clients for posting
program code.

So I'll reformat that code for readability::

 def test_func_getSurplusLabourTime_Exc(self):
 self.assertRaises(
 ValueError,
 self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc))


The traceback is as follows:

==
ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp)
--
Traceback (most recent call last):

[…]

/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py,
 line 475, in assertRaises
 callableObj(*args, **kwargs)
TypeError: 'float' object is not callable


The error message is correct: the ‘assertRaises’ method expects a
callable object in the second parameter, but you've supplied an object
which is not callable (a float).

Have a closer look at the documentation for ‘TestCase.assertRaises’::

 assertRaises(exception, callable, *args, **kwds)

 Test that an exception is raised when callable is called with any
 positional or keyword arguments that are also passed to assertRaises().

 
URL:https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises

It's unfortunate the documentation doesn't give an example. But note
that clause “when `callable` is called with any […] arguments that *are
also passed to assertRaises*”.

So you don't call the function yourself; if you do, you get back its
return value (in your case, a float object) and *that's* your argument
to ‘assertRaises’ — not the function you're trying to test!

Instead of calling the function and getting its return value, you pass
*the function itself* to ‘assertRaises’, along with any arguments you
want *the test method* to call it with.

This indirection is a little confusing, and again I'm unhappy the
documentation doesn't show an example. Here's one::

 def test_func_getSurplusLabourTime_Exc(self):
 self.assertRaises(
 ValueError,
 self.cwp.getSurplusLabourTime,
 self.cwp.ww, self.cwp.uvc)

What the documentation does show as an example, though, is a new-ish
feature that might suit you better.

You can now make your test code more comprehensible by instead using the
‘assertRaises’ method as a context manager, and then you just call your
function normally. Like this::

 def test_func_getSurplusLabourTime_Exc(self):
 with self.assertRaises(ValueError):
 self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)

Context managers are a very helpful feature that can make code more
elegant and readable. They might seem a little magic for now if you
haven't learned about them yet, but this is a good demonstration of
the improvement they can make.


Raul and Ben,
Many thanks for the advice.
The use of this test is much clearer to me now, and I think it is now 
working with your help. But I will practice my use of it.


As for my formatting, this problem of indentation has not occurred before.
I use Thunderbird and Firefox and I have not had this problem up to now. 
I shall examine the problem and see what is wrong and correct it.

Thanks,
Sydney

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] unittest for: Raises an exception

2015-02-18 Thread Sydney Shall

I use a MAC OSX 10.9.5
Enthought Canopy Python 2.7.6

I am a learner.

I am now trying to learn unittests as is often emphasised on this list.
I think that I have understood the simple unit tests such as Equal, 
Greater etc.

But I am struggling with the syntax of a test for Raises an exception.

The function that I am tring to test is:
For some reason my indentation has not been correctly copied.
I am sure that it is correct becuase I have chacked it as well as the 
program. Also the 20 tests that are OK refer to all the other functions 
in the program.


def getSurplusLabourTime(self, ww, uvc):
self.ww = ww
 self.uvc = uvc
 try:
self.surplus_labour_time = self.ww - self.uvc
return self.surplus_labour_time
 except:
if self.surplus_labour_time = 0.0:
raise ValueError(Surplus labour time cannot be + \
 equal to or shorter than zero!)

My test code is the following:

def test_func_getSurplusLabourTime_Exc(self):

self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) 


[This last line should indented, but it refuses to do so!]

The traceback is as follows:

==
ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp)
--
Traceback (most recent call last):
  File 
/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current 
version/TestCWP_WorkDuration.py, line 88, in 
test_func_getSurplusLabourTime_Exc
self.assertRaises(ValueError, 
self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc))
  File 
/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py, 
line 475, in assertRaises

callableObj(*args, **kwargs)
TypeError: 'float' object is not callable

--
Ran 21 tests in 0.005s

FAILED (errors=1)


I do know that I have not added the arguments that would sause an 
exception to be raised. But I have tried several forms and none have 
worked. I get the same traceback as above.



Any guidance would be appreciated.



--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT: Preferred email client for sending plain text programming code snippets

2015-02-18 Thread Sydney Shall

On 18/02/2015 03:48, Mark Lawrence wrote:

On 17/02/2015 23:23, boB Stepp wrote:

Hopefully this is not a touchy subject like Emacs vs. Vim. ~(:))

My home PC uses Win7-64bit. I currently use Chrome, Gmail and have a
Nexus 5 phone. The nice thing about all of this is that all of my
information usually seamlessly syncs. That is nice! But I am getting
increasingly frustrated with Gmail in terms of communicating with this
group (and sometimes others). It seems that if I am not constantly
attentive, my settings change from plain text to html, or, now, my New
Courier fixed-width font vanishes from the Gmail ecosystem and cannot
be found. I actually have come to prefer plain text communication as I
only rarely need html formatting. And I rarely care to see most of the
crap people send me that require html!

So are there any recommendations from this group that would make
things easy, would still be able to receive/send from my Gmail
account, etc.?



Thunderbird.  Access to 300+ Python mailing lists, blogs and the rest
all in one place via gmane.  Personally I've never had a single problem
with it.


Mark,
Could you give  us or point us towards some simple instructions as how 
one uses gmane.comp.python.tutor with Thunderbird. I had a go and I have 
found it daunting.

Thanks

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 131, Issue 59 Order loop from methos on class (jarod...@libero.it)

2015-01-26 Thread Sydney Shall

On 26/01/2015 14:41, Dino Bektešević wrote:

2015-01-26 14:54 GMT+01:00 jarod...@libero.it jarod...@libero.it:

Thanks so much!! Now I understood it is a stupid thing!
So, could you elpme to decompose the problem?
I initiazlizate the class with the file to use so all the function have all
the parameters that I need.

At the moment I have in mind only to do this:
ena = Rna()
job1 = ena.trim()
job2 = ena.align()
It is no so elegant..



Any suggestion?



Without seeing what exactly are you trying to do (I'm not a
chemist/biologist) I'm not sure. Any detail about what you're trying
to do would be helpful.
If you're bothered by having to call 2 methods except of 1 you could
always make another method that uses the two. It really depends on the
decision if you want to do the operations in place or not, that is
transform the original object through it's methods, or do you want to
return a new object of the same class.
In your example you write job as if you're dealing with threads. I
can't tell if you want job1 and job2 to be another different objects
(maybe of Rna class maybe not) or is it just that you don't understand
that you can also call a method on an object without having a variable
to hold a return value.

If you want to return another Rna object that is the same as the
original one, maybe something like this is what you need?

i.e.
import copy

class Rna():
 def __init__(self):
 self.trimmed = False
 self.aligned = False

#NOT a part of the class
def trim(rna):
temp = copy.copy(rna)
temp.trimmed = True
return temp

#in interpreter

ena = Rna()
ena.trimmed

False

tena = trim(ena)
ena.trimmed

False

tena.trimmed

True

and both of ena and tena will be of class Rna. So you now have 2
different Rna objects.
You could also have it done in place, which saves memory and is more
natural and I'd recommend it:

class Rna():
def __init__(self):
self.trimmed=False
self.aligned=False
def trim(self):
 self.trimmed=True
def align(self):
self.aligned=True
def DoBoth(self):
 self.trim()
 self.align()
 print(Done!)

#in the interpreter

ena = Rna()
ena.trimmed

False

ena.aligned

False

ena.DoBoth()

Done!

ena.trimmed

True

ena.aligned

True

This way you can do both without having to constantly write them
yourself... you issue 1 call which then calls various other methods
you have on the instance itself

Even that print isn't necessary, that's just there to show it
finished. You don't always have to have a variable to catch potential
output of a method. But maybe if you need/want to catch the output
maybe that output is an object of a different class(?) maybe it's a
tuple, or an array?

class Rna():
def __init__(self):
self.trimmed=False
self.aligned=False
def trim(self):
 self.trimmed=True
def align(self):
self.aligned=True
def DoBoth(self):
 self.trim()
 self.align()
 print(Done! We return an list of solutions:)
 return [1,2,3,4,5,6,7,8,9]

#in the interpreter

ena = Rna()
solutions = ena.DoBoth()

Done! We return an list of solutions:

solutions

[1,2,3,4,5,6,7,8,9]

You could also add the solutions as an attribute to the object you
just did the calculation on:
def DoBoth(self):
 self.trim()
 self.align()
 print(Done! We return an list of solutions:)
 self.solutions =  [1,2,3,4,5,6,7,8,9]

#in the interpreter

ena = Rna()
ena.DoBoth()

Done! We return an list of solutions:

ena.solutions

[1,2,3,4,5,6,7,8,9]

The better you describe WHAT you want and HOW you want it the better
people here will be able to help you


Best of luck,
Dino
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



I do not know exactly what the OP wants to do, but it sounds like he is 
aligning RNA sequences.
At this stage I would suggest that he studies the possibilities of the 
BioPython package and the programs available at the NLM, USA or the 
Sanger Lab in Cambridge, England.

But I am only a beginner myself, so I might be way off track.
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Installing psutil 2.2.0-1 on Canopy Enthought

2015-01-23 Thread Sydney Shall

On 22/01/2015 22:53, Alan Gauld wrote:

On 22/01/15 12:56, Sydney Shall wrote:

I use MAC OSX 10.9.5
Canopy Enthought python 2.7.6

I also use the Enthought Package Manager to keep my installation
up-todate.



Canopy and Enthoughts paqckage management are well beyond the bounds of
standard Python.


What in fact is my problem? I simply want to update this package, and I
cannot.

I do not know if this is the best Forum to get advice on this, but any
guidance, including where else I might ask would be appreciated.


I'd try the Enthought/Canopy forums. Or perhaps even the SciPy forums
because Canopy has SciPy as standard (along with a bunch of other stuff)



Thanks Alan.
You have solved my problem.
I should have thought of Enthought/Canopy Forum.
Enjoy your walking.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Installing psutil 2.2.0-1 on Canopy Enthought

2015-01-22 Thread Sydney Shall

I use MAC OSX 10.9.5
Canopy Enthought python 2.7.6

I also use the Enthought Package Manager to keep my installation up-todate.

For about two weeks now, Canopy says that I need to install psutil 
2.2.0-1 instead of the currently installed version 2.1.1.
I appear to do that successfully, but the next day the Package manager 
says to install the updated psutil.


When I import psutil I get no error message.
And when I do:
psutil.__version__ , I get back '2.1.1', which is the old version, and I 
have just apparently succesfully udated the package.


What in fact is my problem? I simply want to update this package, and I 
cannot.


I do not know if this is the best Forum to get advice on this, but any 
guidance, including where else I might ask would be appreciated.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension with else

2015-01-19 Thread Sydney Shall

On 19/01/2015 00:55, Steven D'Aprano wrote:

On Sun, Jan 18, 2015 at 02:20:55PM -0800, Danny Yoo wrote:

Just to add, log(0) is mathematically undefined.
https://en.m.wikipedia.org/wiki/Logarithm.


For the record, IEEE-754 specifies that log(0.0) should return -INF.
That's what Decimal does:

py from decimal import Decimal
py Decimal(0).log10()
Decimal('-Infinity')


Alas, Python's math module only has partial support for the IEEE-754
standard.



So depending on the problem's context, it might be worth asking why log is
being applied on this input.  Is such input expected?  Make sure the code
isn't trying to correct for input that shouldn't be there in the first
place.


Correct. Replacing too small values with 0.0 is the wrong solution.
Using -INF is better, or a very large negative number. Otherwise,
sticking 0 in the result is equivalent to replacing the negative values
with 1.

data = [0.5, 1.0, 0.0]  # Good value, good value, bad value.
# This is the wrong way:
[0.0 if x == 0.0 else math.log(x) for x in data]
= returns [-0.6931471805599453, 0.0, 0.0]

That is mathematically equivalent to x = 0.0 being replaced with x = 1.0
before taking the log, and that makes no sense.


Thanks to both Steven and Danny. I will have to examine my logic again.
Superficially, just setting the very occasional 0.0 value to 0 served, 
but it is clearly inappropriate. I will try and find the correct answer 
to my problem. I may return for advice, although it is not strictly python.

Many thanks to you both.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension with else

2015-01-18 Thread Sydney Shall

On 18/01/2015 13:20, Sydney Shall wrote:

I am a beginner and I have a question of syntax.

I am just learning to use list comprehension, which oc course, I find
very helpful indeed.

However, I am stuck with a specific problem of how to incorporate an
else in a list comp-rehension. I cannot do it.

The following snippet of code does what I need. But, perhaps I am
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need to
obtain the logarithm of the number.

for i in range(len(cap)):
 if cap[i] == 0.0:
 tmp = math.log(1.0)
 lncap.append(tmp)
 else:
 lncap.append(math.log(cap[i]))

I have set mu options to plain text.


I apoligise. I should have added:
MAC OS OSX 10.9.5
python 2.7.6 (Enthought)

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] list comprehension with else

2015-01-18 Thread Sydney Shall

I am a beginner and I have a question of syntax.

I am just learning to use list comprehension, which oc course, I find 
very helpful indeed.


However, I am stuck with a specific problem of how to incorporate an 
else in a list comp-rehension. I cannot do it.


The following snippet of code does what I need. But, perhaps I am 
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need to 
obtain the logarithm of the number.


for i in range(len(cap)):
if cap[i] == 0.0:
tmp = math.log(1.0)
lncap.append(tmp)
else:
lncap.append(math.log(cap[i]))

I have set mu options to plain text.
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension with else

2015-01-18 Thread Sydney Shall

On 18/01/2015 13:41, Asokan Pichai wrote:


On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall s.sh...@virginmedia.com
mailto:s.sh...@virginmedia.com wrote:

I am a beginner and I have a question of syntax.

Welcome!


I am just learning to use list comprehension, which oc course, I
find very helpful indeed.

However, I am stuck with a specific problem of how to incorporate an
else in a list comp-rehension. I cannot do it.

The following snippet of code does what I need. But, perhaps I am
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need
to obtain the logarithm of the number.

for i in range(len(cap)):

Using a for loop like this is generally a poor idea.

for aCap in cap:

is the more pythonic way. And also will help you translate to a list
comprehension easily

 if cap[i] == 0.0:
 tmp = math.log(1.0)
 lncap.append(tmp)

Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler

 else:
 lncap.append(math.log(cap[i]))


Having said that above your present code, let me try to explain the
thought process behind constructing the list comprehension for your
purpose. It is possible that what you need is not an else in the list
comprehension

lncap = [ f(aCap) for aCap in cap]

will be the starting point;  where f() will need to provide either
math.log(aCap) or 0 as we saw earlier.

You can actually write an auxiliary function f that does just that; like say
def f(p):
   if p == 0.0:
   return 0.0
   return math.log(p)

Or write the list comprehension as:

lncap = [ (math.log(aCap) if aCap  0 else 0.0) for aCap in cap]

Hope this helps

Thanks. perfect. Thanks especialy for the explanation.

--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good approach regarding classes attributes

2014-09-09 Thread Sydney Shall

On 08/09/2014 18:39, Alan Gauld wrote:

On 08/09/14 15:17, Juan Christian wrote:

One tiny tweak...


class User():


You don't need the parens after User. You don;t have any superclasses 
so they do nothing. Python convention for an empty parent list is just 
to leave the parens off:


class User:


A simple question from a newbie, in response to this surprise.
Is it not helpful to always put (object) as the parent, if the class is 
not itself a sub-class?

And while I am writing, what does OP stand for in this list?


--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good approach regarding classes attributes

2014-09-09 Thread Sydney Shall

On 09/09/2014 15:44, Peter Otten wrote:

Sydney Shall wrote:


On 08/09/2014 18:39, Alan Gauld wrote:

On 08/09/14 15:17, Juan Christian wrote:

One tiny tweak...


class User():

You don't need the parens after User. You don;t have any superclasses
so they do nothing. Python convention for an empty parent list is just
to leave the parens off:

class User:


A simple question from a newbie, in response to this surprise.
Is it not helpful to always put (object) as the parent, if the class is
not itself a sub-class?

The answer differs between Python 2 and 3. In Python 3

class C: # preferred in Python 3
 pass

and

class C(object):
 pass

are the same, so there is no point adding the explicit object inheritance.

In Python 2 however

class C:
 pass

will create a classic class whereas

class C(object): # preferred in Python 2
 pass

is a newstyle class. The most notable difference between these is that
properties work correctly only with newstyle classes. Therefore making all
your classes newstyle is a good idea.


And while I am writing, what does OP stand for in this list?

Original Poster, as Leam says.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Thanks Peter, most helpful.
I was taught with Python 2.7, so  now I understand the advice.


--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good approach regarding classes attributes

2014-09-09 Thread Sydney Shall

On 09/09/2014 16:05, Joel Goldstick wrote:

On Tue, Sep 9, 2014 at 10:02 AM, Sydney Shall s.sh...@virginmedia.com wrote:

On 09/09/2014 15:44, Peter Otten wrote:

Sydney Shall wrote:

On 08/09/2014 18:39, Alan Gauld wrote:

On 08/09/14 15:17, Juan Christian wrote:

One tiny tweak...

class User():

You don't need the parens after User. You don;t have any superclasses
so they do nothing. Python convention for an empty parent list is just
to leave the parens off:

class User:

A simple question from a newbie, in response to this surprise.
Is it not helpful to always put (object) as the parent, if the class is
not itself a sub-class?

The answer differs between Python 2 and 3. In Python 3

class C: # preferred in Python 3
 pass

and

class C(object):
 pass

are the same, so there is no point adding the explicit object inheritance.

In Python 2 however

class C:
 pass

will create a classic class whereas

class C(object): # preferred in Python 2
 pass

is a newstyle class. The most notable difference between these is that
properties work correctly only with newstyle classes. Therefore making all
your classes newstyle is a good idea.

And while I am writing, what does OP stand for in this list?

Original Poster, as Leam says.


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Thanks Peter, most helpful.
I was taught with Python 2.7, so  now I understand the advice.


--
Sydney Shall

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Please post in plain text


My apologies. I thought I was. I will immediately change it.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Use of getter and setter attributes

2014-09-08 Thread Sydney Shall

On 08/09/2014 06:01, Danny Yoo wrote:

@property
def _avatar(self):
return self._avatar

Hi Joel,

The above code looks strange to me.  The method and the field name
should not use the same name.

ah! good catch Danny.  I didn't write it, I was commenting on the OP code.

But (and maybe this was discussed earlier in the thread), what value
is using the property decorator instead of just saving the data to
attributes?


Let's first point to documentation that says what property is:

https://docs.python.org/2/library/functions.html#property

If you read it a bit, one of the key terms that should come up is
managed attribute.

What do they mean by this?

A managed attribute is an attribute that the class's definition
actively controls.

Let's use a concrete example: say that we'd like to make sure a
Person's name is always capitalized.  We might try to enforce this
capitalization property in the constructor.

###
class Person(object):
 def __init__(self, name):
 self.name = name.title()
 def greet(self):
 print(Hi, I'm %s % self.name)

p = Person(joel goldstick)
p.greet()
###

However, this does not stop clients from assigning directly to the name,

#
p.name = joel goldstick
#

and therefore breaking a desire to keep the name capitalized.  So this
might be a problem.

So what we'd like is the following: to make sure that there's some
kind of program logic that kicks in whenever we assign to Person.name.

In some programming languages, we do this by marking the attribute
name in some way that makes it clear not to access it directly, and we
provide setter and getter methods, the code that can manage this
attribute.

#
class Person(object):
 def __init__(self, name):
 self._name = name.title()

 def getName(self):
 return self._name

 def setName(self, name):
 self._name = name.title()

 def greet(self):
 print(Hi, I'm %s % self._name)

## client code:
p = Person(joel goldstick)
print(p.getName())
p.greet()

p.setName(juan christian)
print(p.getName())
p.greet()
#


Python allows us to get setter and getter-like behavior while
still allowing client code to use the attribute with what looks like
direct attribute access:

#
class Person(object):
 def __init__(self, name):
 self._name = name.title()

 @property
 def name(self):
 return self._name

 @name.setter
 def name(self, newName):
 self._name = newName.title()

 def greet(self):
 print(Hi, I'm %s % self._name)

## client code:
p = Person(joel goldstick)
print(p.name)
p.greet()

p.name= juan christian
print(p.name)
p.greet()
#

where now the client code looks simpler, but the class definition
still gets to manage the attribute's value.


Hopefully that helps to make the suggestions in this thread a little
more understandable in context.  Python's properties allow us to make
the client code look direct but still allow for attribute management.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

I was taught to [generally] always use getter and setter, and I have 
found this clear and useful. But I am a beginner, so my question is 
whether there there are any other reasons to use the methods outlined 
above by the always helpful Danny Yoo, in addition to the simplification 
to which he draws attention?


--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A beginner having problems with inheritance

2014-07-10 Thread Sydney Shall

On 09/07/2014 20:17, Danny Yoo wrote:

My error was simply that I inadvertently used the same name for a method
(function) in the derived class that I had already used in the parent class.
The result was then a very obscure error because the wrong calculation was
performed and later on an array was empty.
Fortunately, thanks to you very generous tutors I have learned to read the
error trace very carefully indeed.


Ah, yes, that one.  It's happened to me too.

It's one of the reasons why inheritance makes me nervous sometimes.
It's a problem that's fairly language-independent.

(If you'd like to know the details, the example that I was involved in
is described in the comments on:
https://github.com/bootstrapworld/js-numbers/pull/5.  Essentially, we
subclassed some base class, and wrote a method called BigNumber.exp()
to do exponentiation.  Unfortunately, we didn't realize that our
superclass already had defined an exp() method.  It ended up showing
up as a very strange, obscure error.  Same class of problem.)


Side note, Python does have a hack called name mangling that can be
used to try to avoid this problem:

 
https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references


Good luck!


Thanks for the reply.
I had read the second reference that you gave some time ago, but of 
course I had forgotten about it.

I shall try and make use of it now.
Thanks for the help.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A beginner having problems with inheritance

2014-07-09 Thread Sydney Shall

On 06/07/2014 23:06, Danny Yoo wrote:

My apologies to the tutors.
I have identified my error, which was predictably elementary.
With many thanks,


By the way, can you say what your conceptual error was or give an
example?  It might help the other folks here who are learning and who
may be making a similar mistake.  (And I'm curious!)  But if you don't
want to say, that's ok too.


Good luck!


Thanks Danny,

My error was simply that I inadvertently used the same name for a method 
(function) in the derived class that I had already used in the parent class.
The result was then a very obscure error because the wrong calculation 
was performed and later on an array was empty.
Fortunately, thanks to you very generous tutors I have learned to read 
the error trace very carefully indeed.

Thanks a lot.
Sydney

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A beginner having problems with inheritance

2014-07-02 Thread Sydney Shall

On 01/07/2014 19:04, Sydney Shall wrote:

I am a beginner and I have always had problems with inheritance.

I can get inheritance to work with very simple classes.
But with more complex classes, I find that inheritance seems to work 
for simple variables, but I cannot get it to work with lists or arrays.
Specifically my problem is to access a numpy array in the parent 
class, from within the derived class.

When I test with instances in IPython everything works properly.
But I thought, perhaps wrongly, that with direct inheritance one does 
not need instances.
If one needs instances, how does one create them so that they are 
correctly recognised.


Perhaps, I need to read more about inheritance, Any suggestions for 
reading would be welcome.


With many thanks.


My apologies to the tutors.
I have identified my error, which was predictably elementary.
With many thanks,
Sydney

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] A beginner having problems with inheritance

2014-07-01 Thread Sydney Shall

I am a beginner and I have always had problems with inheritance.

I can get inheritance to work with very simple classes.
But with more complex classes, I find that inheritance seems to work for 
simple variables, but I cannot get it to work with lists or arrays.
Specifically my problem is to access a numpy array in the parent class, 
from within the derived class.

When I test with instances in IPython everything works properly.
But I thought, perhaps wrongly, that with direct inheritance one does 
not need instances.
If one needs instances, how does one create them so that they are 
correctly recognised.


Perhaps, I need to read more about inheritance, Any suggestions for 
reading would be welcome.


With many thanks.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-19 Thread Sydney Shall

On 19/06/2014 03:37, Steven D'Aprano wrote:

On Wed, Jun 18, 2014 at 12:35:20PM +0200, Sydney Shall wrote:

On 17/06/2014 22:35, Alan Gauld wrote:

Use modules instead of singleton classes

As a new beginner with Python, I am having problem understanding the
difference here.
I think I understand classes, but still have problems with inheritance,
but I do not understand what defines a module.

I assume you know how to make a class:

class Spam:
 def method(self, arg):
 ...


And then you make instances:

x = Spam()
y = Spam()

A singleton class is one which only allows there to be a single
instance (or occasionally, two instances, a doubleton class).

For example, None is a singleton. Like all instances, None has a class,
but see what happens if you try to create a second instance in Python
2.7 (Python 3.3 is slightly different):

py from types import NoneType
py x = NoneType()  # create a new instance
Traceback (most recent call last):
   File stdin, line 1, in module
TypeError: cannot create 'NoneType' instances


The error is slightly inaccurate, it's not that no instances can be
created at all, but that only *one* instance can be created, and it's
already created and named None.

Inheritence is a separate issue, big enough that it deserves a new
thread.

As for modules, you already use modules, I'm sure, you just don't
realise it. Every time you create a python file ending in .py, that's a
module. Scripts are modules. Every time you use the import command,
you're loading a module:

py import math
py print math
module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'


Python tries very hard to ensure that every module is loaded only once.
(There are circumstances where you can fool it, but they're rare.) Since
the module holds state (variables) and behaviour (functions), modules
perform the same sort of role as classes, so a module which is loaded
once is very similar to a singleton instance. In other words, if you
want a class to implement singleton behaviour, you have to work at it.
But if you shift the functionality from the class into a module, Python
gives you singleton behaviour for free.

But if you're not sure why anyone would want a singleton instance, I
agree with you: most (but not all) uses of singletons are unnecessary.



Thanks a lot. This was very useful and clear.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Sydney Shall

On 17/06/2014 22:35, Alan Gauld wrote:
Use modules instead of singleton classes 
As a new beginner with Python, I am having problem understanding the 
difference here.
I think I understand classes, but still have problems with inheritance, 
but I do not understand what defines a module.

With many thanks.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] How does one construct a module for import?

2014-06-02 Thread Sydney Shall

I am having a similar problem.
I have now worked out how to copy my helper file to the correct 
location, in my case is:

'/Users/sydney/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages'

When I type the following at the IPython prompt I get no error message;
import findGraphParametersV2

And the following led me to believe all was well.

I type in the following:
In [19]: dir(findGraphParametersV2)

Out[19]:
['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 'findGraphParameters',
 'np',
 'pylab']

However, when I use the import statement in my program I get a runtime 
error as follows:


ipython-input-14-abb1b897e8b9 in module()
 1 CapitalSimulation(51, 4000.0, 20.0, 20.0, 100, 1.0, 0.0, 40.0, 1.0)

/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current 
version/CapitalWithProdV14.py in CapitalSimulation(number_of_cycles, 
capital_advanced, unit_constant_capital, wagerate, labour_powers, 
productivity, prodinc, work_duration, labour_intensity)
525 lnsurplusvalue, lnvariablecapital, 
lnconstantcapital,
526 lnlabourpowers, lnnewvaluecreated, 
rationvtoac,

-- 527 rationvtorc)
528
529 plotDataV2(cycles, AdvancedCapital, lnAdvancedCapital, 
RealisedCapital,


TypeError: 'module' object is not callable

I do not really understand what Steven is recommending below.
Is it an init statement in a file or is it an independent file.

Thanks to you all.

Sydney


On 02/06/2014 03:55, Steven D'Aprano wrote:

On Sun, Jun 01, 2014 at 08:33:37PM -0500, Charles Agriesti wrote:

from swampy.World import World
world = World()

ImportError: No module name World

These scripts run with no problem as long as the file location is the
python27 folder. But not from outside the folder.

Where does swampy come from? Is it your module? Somebody else's?

It looks to me like it is a bug in swampy. You are trying to use it as
if it were a package containing a sub-module, but it isn't actually a
package, just a folder full of modules.

If swampy is somebody else's project, you should report this to them as
a bug, but if it is yours, then you should be able to fix it by adding
an empty __init__.py file inside the swampy folder.

My guess is that you have a folder like this inside the python27 folder:


python27
+-- [other python files]
+-- swampy
 +-- World.py


but you need this:

python27
+-- [other python files]
+-- swampy
 +-- __init__.py
 +-- World.py



If this is not what you have, you will need to explain in more detail
what the layout of your files is, where swampy came from, and where it
is.




--
Sydney Shall

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does one construct a module for import?

2014-06-02 Thread Sydney Shall

Alan,
Please forgive me, but I am still unclear.
Do you mean that I must add a file called __ini__.py to my folder or do 
you mean that each file that I wish to import should have that statement 
[ __init__.py ] immediately after (I presume) my def statement?

If it must be a file, what is in this file?
With many thanks,
Sydney


On 02/06/2014 14:52, Alan Gauld wrote:

On 02/06/14 13:21, Sydney Shall wrote:


I do not really understand what Steven is recommending below.
Is it an init statement in a file or is it an independent file.


It is an independent file (which can be empty) whose existence
indicates to python that a folder is a package.

Thus if you have a folder abc which contains files a,b and c.
Even if abc is in Python's import path you cannot
import a,b or c unless there is an __init__.py

HTH


--
Sydney Shall

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How does one construct a module for import?

2014-06-02 Thread Sydney Shall

Thanks for the detailed reply, Steven.
It seems that you have correctly identified my prblem.

But I am still puzzled, because I do not know how this happened.
I simply copied the two files that I wished to import to a directory 
called (nowMyModule).

It now contains only three files;

pwd
Out[99]: 
u'/Users/sydney/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MyModule'


ls -l
total 32
-rw-r--r--  1 sydney  staff29 Jun  2 16:31 __init__.py
-rw-r--r--  1 sydney  staff  2936 Jun  2 16:32 findGraphParametersV2.py
-rw-r--r--  1 sydney  staff  7147 Jun  2 16:32 plotDataV2.py

What does the line above; total 32 refer to?

But when I do the following, this is what I get.


dir(plotDataV2)
Out[107]:
['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 'plotData',
 'pylab']


In the file plotDataV2, I have imported of course, pylab.
I do not know where plotData comes from although there is such a file in 
another directory.


dir(findGraphParametersV2)
Out[108]:
['__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 'findGraphParameters',
 'np',
 'pylab']

Here I have imported numpy as np, pylab and math which doers not appear?

I do understand that I should have only ONE directory containing my own 
Modules and only ONE copy of each file in that directory. But that is 
what I thought I had done.


Do I undestand correctly that what I need to do is to have a single 
directory, say called MyModule, in the directory site-packages. And 
then I need to copy just once each of the two function files that I want 
to be importable?


Once again, many thanks for your advice,
Sydney


On 02/06/2014 16:31, Steven D'Aprano wrote:

On Mon, Jun 02, 2014 at 01:21:29PM +0100, Sydney Shall wrote:

I am having a similar problem.

Actually, I don't think so. Your problem doesn't appear to have anything
to do with the problem that Charles Agriesti is having. The only
connection seems to be that you are both using Python. Read on for more
details.



I have now worked out how to copy my helper file to the correct
location, in my case is:
'/Users/sydney/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages'

When I type the following at the IPython prompt I get no error message;
import findGraphParametersV2

Right. This says that, unlike Charles' situation, in your case Python is
correctly importing your module. You may have a problem, but *importing*
is not the problem.






And the following led me to believe all was well.

I type in the following:
In [19]: dir(findGraphParametersV2)

Out[19]:
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
  'findGraphParameters', 'np', 'pylab']

This shows that the findGraphParametersV2 (whew, that's a mouthful!)
module has eight attributes. Some of them (like __name__) are created
automatically by Python. Others, like np and pylab, are probably created
when your module imports other modules. The one that you probably care
about is findGraphParameters, which you need to call using:

 findGraphParametersV2.findGraphParameters( arguments )

Notice that you need to give the module name first, followed by the name
of the thing inside the module.

  

However, when I use the import statement in my program I get a runtime
error as follows:

Just a moment. A couple of sentences ago, you said that importing works.
Now you say it doesn't. Which is it?

Please be more specific about the code you are running. Unfortunately,
while we know Python quite well, we're not very good at reading your
mind, and we can't see your code. You need to identify what line of code
is being run, and tell us.

If the code is:

 import findGraphParametersV2

which then fails with ImportError, that tells us some valuable
information. If the code is:

 result = findGraphParametersV2(some, arguments, here)

which then fails with the error you mentioned:

 TypeError: 'module' object is not callable

that tells us something completely different! Both the type of the
exception (ImportError, TypeError) and the error message are important,
but equally important is what you did that resulted in the error.



ipython-input-14-abb1b897e8b9 in module()
 1 CapitalSimulation(51, 4000.0, 20.0, 20.0, 100, 1.0, 0.0, 40.0, 1.0)

/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current
version/CapitalWithProdV14.py in CapitalSimulation(number_of_cycles,
capital_advanced, unit_constant_capital, wagerate, labour_powers,
productivity, prodinc, work_duration, labour_intensity)


If I am reading this correctly, this has absolutely nothing to do with
the findGraphParametersV2 module or the findGraphParameters function
inside that module. It looks to me like you have a *different* module,
called CapitalSimulation, and you try to call it as if it were a
function.

It is difficult to tell exactly what is going on, but my guess is that
inside the CapitalSimulation module you have a function *also* called
CapitalSimulation

Re: [Tutor] How does one construct a module for import?

2014-06-02 Thread Sydney Shall

Thanks Steven I will try what you recommend.
You were correct.
Not understanding properly, I had constucted both a directory and a file 
in my module directory.

I can now correct it, I think.
Thanks for all your help
Sydney
On 02/06/2014 17:47, Steven D'Aprano wrote:

On Mon, Jun 02, 2014 at 05:08:21PM +0100, Sydney Shall wrote:

Thanks for the detailed reply, Steven.
It seems that you have correctly identified my prblem.

But I am still puzzled, because I do not know how this happened.
I simply copied the two files that I wished to import to a directory
called (nowMyModule).
It now contains only three files;
pwd
Out[99]:
u'/Users/sydney/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MyModule'

ls -l
total 32
-rw-r--r--  1 sydney  staff29 Jun  2 16:31 __init__.py
-rw-r--r--  1 sydney  staff  2936 Jun  2 16:32 findGraphParametersV2.py
-rw-r--r--  1 sydney  staff  7147 Jun  2 16:32 plotDataV2.py

What does the line above; total 32 refer to?

It is the number of disk blocks used by the files, assuming 1024 bytes
per block. In this example, the __init__.py file uses 29 bytes, and so
requires a minimum of 1 block; the findGraph file uses 2936 bytes, so
requires at least 3 blocks; the plotData file uses 7147 bytes, so it
needs at least 7 blocks. I don't actually know where the remaining 21
blocks end up. Possibly in the directory itself?


But when I do the following, this is what I get.


dir(plotDataV2)
Out[107]:
['__builtins__',
  '__doc__',
  '__file__',
  '__name__',
  '__package__',
  'plotData',
  'pylab']


In the file plotDataV2, I have imported of course, pylab.
I do not know where plotData comes from although there is such a file in
another directory.

You will have a line like

 from findGraphParametersV2 import plotData

or possibly:

 plotData = 23  # or anything really, who knows?

or

 def plotData(): ...


There's no way for us to tell what plotData is. But YOU can do it:

print(plotDataV2.plotData)



If that doesn't display enough information for you to identify what it
is, try these two commands:

print(repr(plotDataV2.plotData))
print(type(plotDataV2.plotData))




dir(findGraphParametersV2)
Out[108]:
['__builtins__',
  '__doc__',
  '__file__',
  '__name__',
  '__package__',
  'findGraphParameters',
  'np',
  'pylab']

Here I have imported numpy as np, pylab and math which doers not appear?

If math does not appear, you haven't imported it. Possibly you imported
it in findGraphParametersV1 or findGraphParametersV3, but not V2.

Or maybe you imported it, but then deleted it:

import math
del math

Again, there is no way for us to tell what you've done just by the
result.

  

I do understand that I should have only ONE directory containing my own
Modules and only ONE copy of each file in that directory. But that is
what I thought I had done.

Um, yes?



Do I undestand correctly that what I need to do is to have a single
directory, say called MyModule, in the directory site-packages. And
then I need to copy just once each of the two function files that I want
to be importable?

No, I'm saying, *forget about directories of files*. Have ONE FILE per
project. You seem to be confusing yourself into all sorts of knots by
having multiple files trying to import other files. You're working with
advanced functionality, packages, before you understand how to deal with
basic functionality, modules and attributes.


You currently have this:

site-packages/   # directory
+--  MyModule# directory inside site-packages
.+-- __init__.py # file inside MyModule
.+-- findGraphParametersV2.py# another file
.+-- plotDataV2.py   # yet another file


Instead, I suggest you should have:

site-packages/   # directory
+--  MyModule.py # file inside site-packages


and put the contents of findGraphParametersV2.py and plotDataV2.py
inside the MyModule.py file.





--
Sydney Shall

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] pylab axis

2014-05-29 Thread Sydney Shall
I would like to start by thanking all the tutors for their wonderful 
genourosity and excellent advice.


My problem concerns forcing pylab to give me the y axis I want.

My code is as follows:

pylab.figure(10)

pylab.title(Ratio of realised capital to advanced capital.)

pylab.xlabel(Time [Cycles of Capital reproduction])

pylab.ylabel(Ratio of realised capital to advanced capital.)

pylab.xlim = ((0.0, 1.5))

pylab.plot(cycles, ratiocrtoca)

pylab.show(10)


 My pylab output is as follows:


I regret I do not know how to put the pdf file in the message, so I have 
attached the pdf file of the graph. Please guide me on this too.


My problem is that I wish to force the y axis to simply be from 0.0 to 
1.5 without the detail which is just arithmetic noise, I think.


With thanks,

Sydney

--
Sydney Shall



Figure10.pdf
Description: Adobe PDF document
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittests

2014-04-04 Thread Sydney Shall

I would like to thank both Steven and Danny for their explanations.
They were much easier for me to understand than the documentation.
I now think that I understand what I have to do and how I proceed.
Thanks to you both for spending so much time on the answer.
Sydney



On 01/04/2014 18:54, Danny Yoo wrote:

Yes, that unit test was written by Danny (I assume -- I suppose he might
have copied it from somewhere else.)

Oh, who knows where I got that code from.  :P

---

Sydney, you can also take a look at some of the official documentation
of the unittest library:

 https://docs.python.org/2/library/unittest.html#basic-example

You don't have to read all of it, but touching on it and knowing where
the documentation and reference is can be helpful.  The
assertAlmostEqual is part of the library,

 
https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertAlmostEqual

In Scott's case, he was computing with floating point, so writing the
tests to use inexact almost-equality comparison seemed reasonable to
me.


You might find this also useful:

 http://www.diveintopython.net/unit_testing/




Although they might be a bug in the test! In this case, Danny intends
that as a deliberately buggy test -- 1.732... is *not* approximately
equal to 2, at least not according to the rules of unittest.

As a side note, when I'm writing tests, I usually write them
deliberately wrong the first time and run them to make sure that the
framework is properly reporting errors.  Only after I see failing
tests do I put in the right values for the test.  It helps me gain
more confidence that the universe is all right.



I am quite unclear how one proceeds to set up unittests.

Functions that take inputs and return values are usually easy to test.
  For simple programs, express a piece of functionality and some
property you expect that functionality to have.  In pure computations
like math functions, you can state the inputs and expected outputs as
a test.

By the way, if we can't even do that, to express the expected output
of our functions, then that might be a sign that we don't understand
what we're trying to code!  So there's a good reason to consider test
cases early: it forces us to put a stake in the ground and say: This
is what the function is supposed to do, and if it doesn't do this, the
code is wrong.

If I know that a properly functioning f() is supposed to behave like this:

f(9) == 3
f(10) == 42
f(1) == 32

then I want to write those concrete cases as tests.  An easy way to do
so is to use the unittest library to write those tests.  We can write
the cases above as the following test:

###
class MyTests(unittest.TestCase):
 def testCrazyFunction(self):
self.assertEqual(f(9), 3)
self.assertEqual(f(10), 42)
self.assertEqual(f(1), 32)
###

What this means is that I have some expectations on what the function
is supposed to do, apart from how it is actually coded.  That's
important, to express those expectations, because usually you trust
your expectations more than you trust the implementing code.  So if
the test breaks, usually it's the code that's broken, so it gives a
quick canary-in-the-coalmine.


If you want to explore this more, check for Kent Beck's: Test-driven
Development: By Example.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor




--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittests

2014-04-04 Thread Sydney Shall

On 04/04/2014 14:55, Albert-Jan Roskam wrote:

- Original Message -

From: Sydney Shall s.sh...@virginmedia.com
To: tutor@python.org
Cc:
Sent: Friday, April 4, 2014 3:12 PM
Subject: Re: [Tutor] unittests

I would like to thank both Steven and Danny for their explanations.
They were much easier for me to understand than the documentation.
I now think that I understand what I have to do and how I proceed.
Thanks to you both for spending so much time on the answer.
Sydney

Sydney,
  
I found this a very useful book: http://www.amazon.com/Python-Testing-Beginners-Daniel-Arbuckle/dp/1847198848
  
regards,

Albert-Jan


Dear Albert-Jan,
Many thanks for the suggestion. I will have a look at the book.
Best wishes,
Sydney

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] unittests

2014-04-01 Thread Sydney Shall

Another debutant!
I am having trouble learning to use unittests.
My question is;
In the example below, did you write the class 
SquareRootTests(unittest.TestCase): ?

   Or do I find a set of them in the library?
   And what is the significance of the name chosen 
self.assertAlmostEqual(square_root(3), 2.0) ?
  I take it the first argument is calling my function with its argument 
and the second argument is the correct answer?


I am quite unclear how one proceeds to set up unittests.

With many thanks in advance,

Sydney


On 01/04/2014 03:10, Danny Yoo wrote:

I tweaked it to what I thought was correct but when I test it I get nothing 
back.

def square_root(a, eps=1e-6):
x = a/2.0
while True:
y = (x + a/x)/2.0
if abs(x - y)  eps:
return y
x = y

round(square_root(9))

The way I tweaked it seems to work, I’m getting the correct answer on the 
calculator but the interpreter is not returning anything when I check in python.


I didn't want to keep you waiting, so I'll cut to the chase.  This
line here in your program:

 round(square_root(9))

computes a value... But it doesn't do anything with that value.

Try printing the value.


You may also try to see that your program is doing something effective
by unit testing it.  This is often a lot better than just printing
values and looking at them, because the test case will say what the
_expected_ value is, so it's more informative.



For this example, the following is a start at unit testing the above
function.  Add the following to the bottom of your program's source.


###
## See:  http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html
import unittest
class SquareRootTests(unittest.TestCase):
 def testSimpleCases(self):
 self.assertAlmostEqual(square_root(1), 1.0)
 self.assertAlmostEqual(square_root(4), 2.0)

if __name__ == '__main__':
 unittest.main()
###


Here's what it looks like when I run this:

##
$ python sqrt.py
4.472135955
.
--
Ran 1 test in 0.000s

OK
##


You can then start adding more and more to tests to gain confidence
that the code is doing something reasonable.



If we try to put in an intentionally broken test, like:

 self.assertAlmostEqual(square_root(3), 2.0)

in the body of testSimpleCases(), then we'll see the following error
when running the program:


##
$ python sqrt.py
4.472135955
F
==
FAIL: testSimpleCases (__main__.SquareRootTests)
--
Traceback (most recent call last):
   File sq.py, line 20, in testSimpleCases
 self.assertAlmostEqual(square_root(3), 2.0)
AssertionError: 1.7320508075688772 != 2.0 within 7 places

--
Ran 1 test in 0.000s

FAILED (failures=1)
##


And that's what you want to see.  If either the test or the code is
bad, it'll say something about it.


One other thing: you will want to check a particularly insidious case
that will cause the program here to behave badly.  Consider the zero
case: square_root(0).  Write the test case.  Run it.  You'll see
something interesting.



Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FASTA parsing, biological sequence analysis

2014-03-25 Thread Sydney Shall

I did not know about biopython, but then I am a debutant.
I tried to import biopython and I get the message that the name is unknown.
I am using Enthought Python 2.7.3on MAC OS X10.6.8.
Where and more importantly for me, how do I find and import BioPython on 
to my machine.

With many thanks,
Sydney


On 24/03/2014 18:58, Danny Yoo wrote:

Hi Jumana,

Following up.  Let's change the subject line.  This makes it much
easier for folks to see that this is a new topic of conversation.


[Apologies to the others on the list for my last reply: I didn't
realize that the subject was wrong, as well as the long quoted digest.
  I'll try to be more careful next time.]


Jumana, I would strongly suggest separating string parsing issues from
computational issues.  The suggestion to use Biopython is twofold: not
only do you get to avoid writing a FASTA parser, but it gets you in
the right mindset of processing _multiple_ sequences.


You are encountering this problem, as your comment suggests:


I wrote a program close to what Denis suggested , however it works only if I
have one sequence (one header and one sequence), I can not modify it to work
if I have several sequences (like above).


You want the structure of your program to do an analysis on each
biological sequence, rather than on just on each character of your
sequence.

###
### pseudocode below: #
###
from Bio import SeqIO
import sys


def doAnalysis(record):
 print(I see: , record.id, record.seq)
 ## fill me in


for record in SeqIO.parse(sys.stdin, 'fasta'):
 doAnalysis(record)
###


And you can fill in the details of doAnalysis() so that it does the
nucleotide counting and only needs to worry about the contents of the
record's single sequence.

In bioinformatics contexts, you must either deal with memory
consumption, or use libraries that naturally lend to doing things in a
memory-careful way, or else your computer will start swapping RAM.  At
least, unless your data sets are trivial, which I am guessing is not
the case.

In short, please use the BioPython library.  It will handle a lot of
issues that you are not considering, including memory consumption and
correct, stream-oriented parsing of FASTA.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor




--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FASTA parsing, biological sequence analysis

2014-03-25 Thread Sydney Shall

On 25/03/2014 15:55, Steven D'Aprano wrote:

On Tue, Mar 25, 2014 at 03:36:12PM +, Sydney Shall wrote:

I did not know about biopython, but then I am a debutant.
I tried to import biopython and I get the message that the name is unknown.
I am using Enthought Python 2.7.3on MAC OS X10.6.8.
Where and more importantly for me, how do I find and import BioPython on
to my machine.


https://duckduckgo.com/html/?q=download+biopython

which leads to this:

http://biopython.org/wiki/Biopython


If you read the installation instructions, they have instructions for
Macs. I don't know how much experience you have, I suggest you read the
instructions then come back with any questions. (We're not really Mac
experts here, or at least I'm not, it's been 15 years since I've used
one, but we can try to help.)


Thanks. I will ask if I have difficulty. I think that I understand the 
instructions.

Sydney

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread Sydney Shall

On 22/10/2013 00:42, Alan Gauld wrote:

On 22/10/13 00:07, Steven D'Aprano wrote:


I'd like to upgrade that process :D ...

1) think about your problem
2) if there are some heplful libraries that can make it way easier, 
use them

3) write some code
4) fix the bugs until it'll run
5) write unittests
6) test if it works correctly and if unittests pass
7) repeat until done



Heh, very true! But the most important step is step 1,


I agree. I've recently started coaching the son of a friend in 
computing for his new school (he is effectively a year behind

his new classmates). They use VB6 but at a level I can cope with! :-)

The interesting thing however is that the schools have not taught
any kind of approach to problem solving, they just give a homework 
assignment and expect them to produce code. My friend wants to

dive into Vuisual Studio to start work immediately. I've been
trying to get him to adopt a workflow where he writes on paper
an informal use case description of the solution and if
necessary a pseudo code design. But it's been a real challenge
to get him to slow down and understand exactly what he is being
asked to do before diving into code. (Some of that is just
natural youthful impatience, but mostly it's lack of instruction
in an alternative! :-)


Alan,
I am a newcomer to Python programing.
Could you please explain exactly what you mean by 'an informal use 
case description of the solution ..'?

I am not clear how this differs from pseudo code design.
Thanks to you all for your generous and always invaluable help.
Sydney

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] totalViruses[i] /= float(numTrials),

2013-04-24 Thread Sydney Shall

//I am a beginner just learning Python.

I have come across the following usage for the first time.

  totalViruses[i] /= float(numTrials)

Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to extract a float from an instancemethod call

2013-04-14 Thread Sydney Shall



On 08/04/2013 13:52, Dave Angel wrote:

On 04/08/2013 08:40 AM, Sydney Shall wrote:

Hi,
I am  learning Python.

I use MAC OSX 10.6.8
Python 2.7.3

I have been given a project to write a program involving random walks.
I have drafted a program which has passed all the static tests, but on
testing my program i get the following error message:


Traceback (most recent call last):
   File /Users/Sydney/Documents/6.00x Files/Problem
Sets/ProblemSet7/ps7 copy.py, line 303, in module
 testRobotMovement(StandardRobot, RectangularRoom)
   File ps7_verify_movement.py, line 12, in testRobotMovement
   File /Users/Sydney/Documents/6.00x Files/Problem
Sets/ProblemSet7/ps7 copy.py, line 285, in updatePositionAndClean
 while self.room.isPositionInRoom(self.position) == False:
   File /Users/Sydney/Documents/6.00x Files/Problem
Sets/ProblemSet7/ps7 copy.py, line 163, in isPositionInRoom
 return self.room[(x,y)] in self.room
KeyError: (bound method Position.getX of __main__.Position object at
0x4699490, bound method Position.getY of __main__.Position object at
0x4699490)
 

The program text referred to is the following, I give the whole module,
which is part of a larger program.
  def isPositionInRoom(self, pos):
 
 Return True if pos is inside the room.

 pos: a Position object.
 returns: True if pos is in the room, False otherwise.
 
 x = pos.getX
 y = pos.getY


You never show the code for Position.getX and Position.getY, but I'd 
expect they're methods that take no arguments.  in that case, you need 
parens in order to call them.


   x = pos.getX()
   y = pos.getY()


 return self.room[(x,y)] in self.room



a simple print of x and y could have revealed this as well.



Dear Dave,
Thanks for  pointing out my mistake. I thought it would be some small 
error on my part.

I had a print statement, but I could not correctly interpret the output.
It solves that problem.



--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to extract a float from an instancemethod call

2013-04-08 Thread Sydney Shall

Hi,
I am  learning Python.

I use MAC OSX 10.6.8
Python 2.7.3

I have been given a project to write a program involving random walks.
I have drafted a program which has passed all the static tests, but on 
testing my program i get the following error message:



Traceback (most recent call last):
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 303, in module

testRobotMovement(StandardRobot, RectangularRoom)
  File ps7_verify_movement.py, line 12, in testRobotMovement
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 285, in updatePositionAndClean

while self.room.isPositionInRoom(self.position) == False:
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 163, in isPositionInRoom

return self.room[(x,y)] in self.room
KeyError: (bound method Position.getX of __main__.Position object at 
0x4699490, bound method Position.getY of __main__.Position object at 
0x4699490)



The program text referred to is the following, I give the whole module, 
which is part of a larger program.

 def isPositionInRoom(self, pos):

Return True if pos is inside the room.

pos: a Position object.
returns: True if pos is in the room, False otherwise.

x = pos.getX
y = pos.getY
return self.room[(x,y)] in self.room

The module that made the call is;
 def updatePositionAndClean(self):

Simulate the raise passage of a single time-step.

Move the robot to a new position and mark the tile it is on as 
having

been cleaned.

steps = 0
self.position = self.room.getRandomPosition()
print self.position

self.x = self.position.getX
self.y = self.position.getY
print self.room

self.room.cleanTileAtPosition((self.x, self.y))

self.direction = self.getRobotDirection()

print 'Initial direction in degrees is ' , self.direction

self.position = self.position.getNewPosition(self.direction, 
self.speed)

steps += 1
while self.room.isPositionInRoom(self.position) == False:
self.direction = Robot.getRobotDirection()
self.position = Position.getNewPosition(self.direction, 
self.speed)

steps += 1
self.x = self.position.getX
self.y = self.position.getY


print 'Current position is x,y ', self.x, self.y
print 'Current direction is ' , self.direction + 'Degrees.'

self.room.cleanTileAtPosition((self.x, self.y))

print self.room.isTileCleaned((self.x, self.y))

I do not understand how one extracts a number from an instance method 
that should return a number.

I need to convert this number a float to an int to avoid the key error.
But I do not know how to extract the float.

This conclusion I derive from this earlier error message;

Traceback (most recent call last):
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 303, in module

testRobotMovement(StandardRobot, RectangularRoom)
  File ps7_verify_movement.py, line 12, in testRobotMovement
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 285, in updatePositionAndClean

while self.room.isPositionInRoom(self.position) == False:
  File /Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py, line 163, in isPositionInRoom

return self.room[(int(x), int(y))] in self.room
TypeError: int() argument must be a string or a number, not 'instancemethod'
  RESTART 



I would be grateful for any guidance.






--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor