├── README.md ├── __init__.py ├── abm ├── __init__.py ├── agents │ ├── __init__.py │ └── agents001.py ├── ca │ └── conway1970.py ├── games │ ├── __init__.py │ └── simple2p │ │ ├── __init__.py │ │ ├── simple_game.py │ │ └── user_utils.py ├── gridworld │ └── gridworld.py ├── historical │ ├── Wallich-2012-PublicChoice │ │ └── supplyDemandWallich.py │ ├── bergmann1990.bas │ └── bergmann1990.txt ├── netlogo │ └── netlogo4to6.py ├── pestieau1984oep │ ├── __init__.py │ └── agents.py ├── segregate │ └── schelling02.py ├── template_models │ ├── Cell.Data │ ├── README.txt │ ├── template00.py │ ├── template01.py │ ├── template02.py │ ├── template03.py │ ├── template04.py │ ├── template05.py │ ├── template06.py │ ├── template07.py │ ├── template08.py │ ├── template09.py │ ├── template10.py │ ├── template11.py │ ├── template12.py │ ├── template13.py │ ├── template14.py │ ├── template15.py │ └── template16.py └── utilities.py ├── dynopt ├── __init__.py ├── detcake.py └── kurtz.py ├── finance ├── finance.py └── test_finance.py ├── growth └── solow │ └── solow.py ├── integrate ├── __init__.py └── quadrature.py ├── math ├── __init__.py ├── simfloat.py └── tests │ └── test_simfloat.py ├── optimize ├── __init__.py └── iterate.py ├── plot └── plot.py ├── pythonresources.html ├── pytrix ├── __init__.py ├── __init__.pyc ├── fmath.py ├── fmath.pyc ├── ls.py ├── opendatabank.htm ├── opendatabank.txt ├── principal_components.py ├── pwt.py ├── pyGAUSS.py ├── pytrix.py ├── pytrix.xhtml ├── pytrixIO.py ├── stat.py ├── tseries.py ├── unitroot.py ├── utilities.py └── utilities.pyc ├── scripts └── scripts_config.py ├── software4econ.html ├── tests ├── __init__.py ├── simplest.py ├── test_abm.py ├── test_functions.py ├── test_iterate.py ├── test_ls.py ├── test_pestieau.py ├── test_pytrix.py ├── test_quadrature.py ├── test_stat.py ├── test_text_utilities.py ├── test_tseries.py ├── test_utilities.py ├── tests_config.py └── tests_config.pyc ├── text ├── README └── vimfiles │ ├── ai_texmenus.vim │ ├── ai_vimrc.vim │ ├── aisaac │ ├── _gvimrc │ └── _vimrc │ ├── colors │ ├── astronaut.vim │ ├── bmichaelsen.vim │ ├── breeze.vim │ ├── darkblue.vim │ ├── darker-robin.vim │ ├── darkerdesert.vim │ ├── darkslategray.vim │ ├── desert.vim │ ├── download_script.php │ ├── dusk.vim │ ├── greyblue.vim │ ├── hhazure.vim │ ├── hhdgray.vim │ ├── hhteal.vim │ ├── metacosm.vim │ ├── navajo-night.vim │ ├── ps_color.vim │ ├── sienna.vim │ └── timchase.vim │ ├── filetype.vim │ ├── ftplugin │ ├── html_xhb.vim │ ├── mail_ai.vim │ ├── python_ai.vim │ ├── rst_ai.vim │ └── tex_ai.vim │ ├── share_vimrc.vim │ ├── spell │ ├── en.latin1.add │ ├── en.latin1.add.spl │ ├── en.utf-8.add │ └── en.utf-8.add.spl │ ├── syntax │ ├── eviews.vim │ ├── gauss.vim │ ├── netlogo.vim │ └── rest.vim │ └── template │ ├── template.tex │ ├── template.xhb │ └── template.xhs └── utilities ├── __init__.py ├── mso.py ├── sftp_client.py ├── table.py ├── test_table.py └── wordfreq.py /README.md: -------------------------------------------------------------------------------- 1 | # econpy 2 | 3 | A collection of Python 2.7 modules useful to social scientists, 4 | esepcially those interested in agent-based modeling. 5 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/agents/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/ca/conway1970.py: -------------------------------------------------------------------------------- 1 | """ 2 | An ultra-simple version of Conway's game of life. 3 | Implements the Gosper glider gun for illustration. 4 | Uses a finite world, so there is a small anomaly 5 | at the edge. 6 | 7 | :see: http://www.argentum.freeserve.co.uk/lex_g.htm#gosperglidergun 8 | """ 9 | from time import sleep 10 | import numpy as np 11 | from scipy import ndimage 12 | import matplotlib.pyplot as plt 13 | 14 | #turn on interactive use 15 | plt.ion() 16 | plt.hold(False) 17 | 18 | #initialize figure 19 | fig1 = plt.figure(1) 20 | ax1 = fig1.gca() 21 | 22 | #initialize array 23 | grid = np.zeros( (100,100), dtype=np.int) 24 | 25 | """ 26 | #blinker 27 | grid[2,1:4] = 1 28 | print grid 29 | 30 | #glider 31 | grid[2:5,2:5] = [(0,1,0),(0,0,1),(1,1,1)] 32 | 33 | #rabbits 34 | grid[40:43,40:47]= np.array([ 35 | 1,0,0,0,1,1,1, 36 | 1,1,1,0,0,1,0, 37 | 0,1,0,0,0,0,0, 38 | ]).reshape((3,-1)) 39 | 40 | """ 41 | #Gosper glider gun 42 | grid[2:11,2:38] = np.array([ 43 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 44 | 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0, 45 | 0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1, 46 | 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1, 47 | 1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 48 | 1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0, 49 | 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 50 | 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 51 | 0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 52 | ]).reshape(9,-1) 53 | 54 | 55 | 56 | 57 | #Game of Life footprint and rules 58 | fp = [(1,1,1),(1,1,1),(1,1,1)] 59 | def fnc(buffer): 60 | alive = buffer[4] 61 | s = sum(buffer) 62 | test = ((s==3) or (s-alive==3)) 63 | return test 64 | 65 | 66 | for _ in range(1000): 67 | plt.matshow(grid, fignum=False) 68 | grid = ndimage.generic_filter(grid, fnc, footprint=fp, mode='constant') 69 | sleep(0.05) 70 | 71 | 72 | -------------------------------------------------------------------------------- /abm/games/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/games/simple2p/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/games/simple2p/user_utils.py: -------------------------------------------------------------------------------- 1 | # File: user_utils.py 2 | from collections import defaultdict 3 | 4 | 5 | 6 | 7 | ############# alternative approach to grid population ####################### 8 | ########### (a bit faster but more obscure for reading) ##################### 9 | import itertools 10 | def groupsof(lst,n): #used to populate SimpleTorus by row 11 | """Return len(self)//n groups of n, discarding last len(self)%n players.""" 12 | #use itertools to avoid creating unneeded lists 13 | return itertools.izip(*[iter(lst)]*n) 14 | 15 | def alt_populate(nrows, ncols, players): 16 | assert len(players)==nrows*ncols 17 | #fill a 2d grid with players 18 | players2d = list( list(g) for g in groupsof(players, ncols) ) 19 | return players2d 20 | 21 | -------------------------------------------------------------------------------- /abm/historical/bergmann1990.bas: -------------------------------------------------------------------------------- 1 | 0 REM See bergmann1990.txt for documentation. 2 | 3 | 10 DEFINT I-N 4 | 20 REM open "results.vi" FOR OUTPUT AS #1 5 | 30 DIM IEMPST(1000), IDATE(1000), NEMP(70), ELIG(1000) 6 | 7 | 40 FOR IWEEK= 1 TO 19 : NEMP(IWEEK) = 950 : NEXT 8 | 45 FOR IWEEK = 20 TO 29 : NEMP(IWEEK) = NEMP(IWEEK - 1) - 5 : NEXT 9 | 50 FOR IWEEK = 30 TO 40 : NEMP(IWEEK) = 895 : NEXT 10 | 57 FOR IWEEK = 41 TO 50 : NEMP(IWEEK) = NEMP(IWEEK- 1) + 5 : NEXT 11 | 60 FOR IWEEK = 51 TO 70 : NEMP(IWEEK) = 950 : NEXT 12 | 70 LABFOR= 1000 : RATLV= .015 13 | 80 UN= LABFOR - NEMP(1) 14 | 15 | 90 FOR IPERS= 1 TO NEMP(1) 16 | 100 IEMPST(IPERS) = 1 : ELIG(lPERS) = 6 17 | 102 NEXT IPERS 18 | 104 FOR IPERS = NEMP(1) + 1 TO LABFOR 19 | 110 IEMPST(IPERS) =0 20 | 111 IDAT = IDAT + 1 : IF IDAT>4 THEN IDAT = 0 21 | 112 IDATE(IPERS) = (-1)*IDAT 22 | 115 EL = EL + 1 : IF EL>6 THEN EL = 0 23 | 117 ELIG(IPERS)=EL 24 | 120 NEXT IPERS 25 | 26 | 130 FOR IWEEK = 2 TO 70 27 | 28 | 140 LEAVS= RATLV*(LABFOR - UN) 29 | 150 DIFEMP = NEMP(IWEEK) - NEMP(IWEEK - 1) 30 | 160 IF DIFEMP O THEN IHIR = LEAVS + DIFEMP ELSE IHIR = LEAVS 39 | 231 IHIR = IHIR + VAC 40 | 240 FOR L = 1 TO IHIR 41 | 241 NFAIL=O 42 | 250 ICHOSE= RND*LABFOR + .5 43 | 260 IF IEMPST(ICHOSE)=1 THEN GOTO 250 44 | 265 IF IDATE(ICHOSE)=IWEEK THEN GOTO 267 45 | 266 IF ELIG(ICHOSE)<2 THEN GOTO 270 46 | 267 NFAIL = NFAIL + 1 47 | 268 IF NFAIL<10 THEN GOTO 250 ELSE GOTO 290 48 | 270 IEMPST(ICHOSE)=1 49 | 290 NEXT L 50 | 51 | 300 UN= 0 : TIMSUM = 0 52 | 310 FOR IPERS= 1 TO LABFOR 53 | 311 IF IEMPST(IPERS) = 1 THEN ELIG(IPERS) = ELIG(IPERS) + 1 / 3 54 | 312 IF IEMPST(IPERS) = 0 THEN ELIG(IPERS) = ELIG(IPERS) - 1 55 | 313 IF ELIG(IPERS)>6 THEN ELIG(IPERS)=6 56 | 314 IF ELIG(IPERS)O GOTO 370 58 | 330 UN= UN+ 1 59 | 340 UTIM = IWEEK- IDATE(IPERS) 60 | 350 PRINT IPERS ``1'' UTIM `` ''; 61 | 360 TIMSUM = TIMSUM + UTIM 62 | 370 NEXT IPERS 63 | 372 VAC = NEMP(IWEEK) - (LABFOR- UN) 64 | 380 UTIMAV = TIMSUM / UN 65 | 390 UR= UN / LABFOR 66 | 400 PRINT "simulated macro variables", IWEEK, UR, UTIMAV 67 | 405 REM PRINT #1, "simulated macro variables", IWEEK, UR, UTIMAV 68 | 69 | 410 NEXT IWEEK 70 | 71 | 420 END 72 | 73 | -------------------------------------------------------------------------------- /abm/historical/bergmann1990.txt: -------------------------------------------------------------------------------- 1 | The file bergmann1990.bas contains a transcription of the BASIC program 2 | in Bergmann, Barbara (1990), Micro-to-Macro Simulation: A Primer with 3 | a Labor Market Example, Journal of Economic Perspectives. 4 | The article provides detailed documentation of the model. 5 | I commented out the file handling and referenced this documentation. 6 | I also added bergmann1990.py, a simple translation into Python. 7 | For better or worse, I made changes for readability in the Python code. 8 | - Alan G. Isaac 9 | 10 | Currently a short tutorial for BASIC may be found at 11 | http://www.math.hawaii.edu/~hile/basic/basicmain.htm 12 | 13 | Bergmann (1990) documents the following variables: 14 | 15 | DIFEMP 16 | change in employment desired by employers 17 | ELIG(I) 18 | weeks remaining of UI stipend for Ith worker 19 | EL 20 | number that fluctuates between 0 and 6 21 | ICHOSE 22 | ID of worker chosen to change status 23 | IDAT 24 | number that fluctuates between 0 and 4 25 | IDATE(I) 26 | date Ith worker last became unemployed 27 | IEMPST(I) 28 | current employment status of Ith worker 29 | IHIR 30 | number of workers employers wish to hire currently 31 | IPERS 32 | ID of a person 33 | ISEP 34 | number of persons to be separated 35 | IWEEK 36 | week number 37 | K,L 38 | number of times operation done 39 | LABFOR 40 | size of labor force 41 | LEAVS 42 | number of separations if no net change in desired employment 43 | NEMP(I) 44 | quantity of employment desired by employers in Ith week 45 | NFAIL 46 | number of candidates an employer can interview in a week 47 | RATLV 48 | rate of separations of employed workers 49 | RND 50 | newly generated uniform random number between 0 and 1 51 | TIMSUM 52 | summation of values of UTIM 53 | UN 54 | number of persons unemployed 55 | UR 56 | unemployment rate 57 | UTIM 58 | number of weeks since worker's last separation 59 | UTIMAV 60 | average duration of current unfinished spells of unemployment 61 | VAC 62 | number of vacant job slots at end of hiring period 63 | 64 | -------------------------------------------------------------------------------- /abm/netlogo/netlogo4to6.py: -------------------------------------------------------------------------------- 1 | """Provides function `netlogo4to6` to convert NetLogo version 4 files 2 | to NetLogo files that can be loaded by version 6. 3 | (NOTE: NetLogo 6 will convert version 5 files itself.) 4 | Please send comments to alan DOT isaac AT gmail DOT com. 5 | """ 6 | charsetProblem = """ 7 | Unhandled problematic characters: 8 | NetLogo 4 files with characters outside of UTF-8 9 | (e.g., from the old Windows character set) 10 | will baffle this script. You will have to 11 | remove these by hand, usually from the Info tab. 12 | """ 13 | 14 | import os, re, sys, textwrap, warnings 15 | 16 | sectionsep = "@#$#@#$#@" 17 | header = """Converted from NetLogo version 4 by netlogo4to6.py. 18 | Known limitations: 19 | 1. Conversion does not handle lambdas. (Therefore instances 20 | of `foreach` and `map` must be edited by hand.) 21 | 2. You may need to add by hand a `reset-ticks` 22 | command to the setup procedure. 23 | """ 24 | commentHeader = textwrap.indent(header, "; ") 25 | 26 | def netlogo4to6(fpath): 27 | """ 28 | Version 4 sections are separated by sectionsep: 29 | 0 : code 30 | 1 : interface widgets 31 | 2 : Info tab 32 | 3 : shapes 33 | 4 : version info 34 | 5 : commands? 35 | 6 : empty? 36 | 7 : experiments 37 | 8 : empty? 38 | 9 : commands 39 | 10 : empty (just end of file?) 40 | Version 6 adds a section: 41 | 11 : 0 42 | Version 6 does not allow a CC-WINDOW widget. 43 | Version 6 buttons append a disable-until-ticks parameter (0 or 1). 44 | """ 45 | global commentHeader 46 | if not fpath.endswith(".nlogo"): 47 | raise ValueError("not a .nlogo file") 48 | with open(fpath, "r", encoding="utf-8") as fin: 49 | try: 50 | data = fin.read() 51 | except UnicodeDecodeError: 52 | warnings.warn(charsetProblem) 53 | commentHeader += textwrap.indent(charsetProblem, "; ") 54 | data = open(fpath, "r").read() 55 | sections = list(map(lambda x:x.strip(), data.split(sectionsep))) 56 | #print(sections[0]) 57 | if not (11 == len(sections)): 58 | _msg = "{} sections instead of the 11 expected from a version 4 file." 59 | assert (12 == len(sections) and sections[-1]==""), _msg.format(len(sections)) 60 | if not sections[4].startswith("NetLogo 4"): 61 | raise ValueError("not a version 4 file") 62 | #fix the sections: 63 | sections[0] = commentHeader + fixCode( sections[0] ) 64 | sections[1] = fixWidgets4to6(sections[1]) 65 | sections[4] = "NetLogo 6.0.0" 66 | sections[7] = fixPrimitives4to6( sections[7] ) 67 | sections.insert(-1, "0") 68 | #prepare output 69 | _sectionsep = "\n" + sectionsep + "\n" 70 | return _sectionsep.join(sections) 71 | 72 | def fixWidgets4to6(widgetsAsString): 73 | oldWidgets = widgetsAsString.split("\n\n") 74 | if not oldWidgets[0].startswith("GRAPHICS-WINDOW"): 75 | raise ValueError("not a .nlogo file") 76 | newWidgets = list() 77 | for w in oldWidgets: 78 | if w.startswith("CC-WINDOW"): 79 | continue 80 | elif w.startswith("BUTTON"): 81 | w = w + "\n1" 82 | newWidgets.append( fixCode(w) ) 83 | return "\n\n".join(newWidgets) 84 | 85 | def fixCode(codeSection): 86 | lines = list() 87 | for line in codeSection.split("\n"): 88 | lines.append( fixPrimitives4to6(line) ) 89 | return "\n".join(lines) 90 | 91 | def fixPrimitives4to6(mystr): 92 | for cmd in ("update-plots", "clear-globals", "clear-ticks", 93 | "hubnet-clients-list", "hubnet-kick-client", "hubnet-kick-all-clients", 94 | "range", "sort-on", "stop-inspecting", "stop-inspecting-dead-agents"): 95 | mystr = re.sub("\\b" + cmd + "\\b", cmd + "-4to6", mystr) 96 | return mystr 97 | 98 | if __name__=="__main__": 99 | for pth in sys.argv[1:]: 100 | fname, fext = os.path.splitext(pth) 101 | outname = fname + "_v6" + fext 102 | with open(outname,"w") as fout: 103 | fout.write(netlogo4to6(pth)) 104 | 105 | -------------------------------------------------------------------------------- /abm/pestieau1984oep/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /abm/segregate/schelling02.py: -------------------------------------------------------------------------------- 1 | """ 2 | :note: 3 | The original Schelling model placed agents on a small grid. 4 | Here agents can occupy any point on the screen, 5 | as in Allen Downey's misnamed ``RacistWorld`` model. 6 | 7 | :requires: Python 2.6+ (for new turtle.py) 8 | """ 9 | from __future__ import division 10 | import turtle 11 | import random, math 12 | import time 13 | 14 | class SchellingWorld(object): 15 | def __init__(self, n_agents=250): 16 | self.n_agents = n_agents 17 | self.history = list() 18 | self.screen = turtle.Screen() 19 | self.screen.tracer(False) 20 | agents = [SchellingAgent() for i in range(self.n_agents)] 21 | self.screen.tracer(True) 22 | def run(self, maxiter=200, trace_all=False): 23 | screen = self.screen 24 | agents = list(screen._turtles) 25 | ct = 0 26 | while ct < maxiter: 27 | screen.tracer(trace_all) 28 | random.shuffle(agents) 29 | for t in agents: 30 | t.step() 31 | screen.tracer(True) 32 | self.add2history() 33 | ct += 1 34 | def add2history(self): 35 | """Return None. Calculate segregation ratio 36 | and store in `history`. 37 | """ 38 | agents = self.screen._turtles 39 | n = len(agents) 40 | seg_stat = sum(t.segregation_ratio() for t in agents) / n 41 | self.history.append(seg_stat) 42 | 43 | 44 | class SchellingAgent(turtle.Turtle): 45 | """A SchellingAgent moves if there 46 | aren't enough nearby agents like himself. 47 | """ 48 | def __init__(self, **kw): 49 | turtle.Turtle.__init__(self, **kw) 50 | color = random.choice(['red','black']) 51 | self.tags = set() 52 | self.tags.add(color) 53 | self.color(color) 54 | self.penup() 55 | width, height = self.canvas_size() 56 | x = random.randint(-width//2, width//2) 57 | y = random.randint(-height//2, height//2) 58 | self.goto(x,y) 59 | self.setheading(random.randint(0,360)) 60 | self.onclick(self.show_neighbors) 61 | 62 | def forward(self, distance=1, constrain=True): 63 | """Return None. Move agent by amount 64 | `distance` using current heading, 65 | but stay on the canvas.""" 66 | my_heading = self.heading() 67 | if constrain: 68 | while not self.on_canvas(): 69 | self.setheading(self.towards(0,0)) 70 | turtle.Turtle.forward(self, 1) 71 | self.setheading(my_heading) 72 | turtle.Turtle.forward(self, distance) 73 | if constrain: 74 | while not self.on_canvas(): 75 | self.back(1) 76 | 77 | fd = forward 78 | 79 | def canvas_size(self): 80 | """Return tuple, canvas width and height.""" 81 | width = self.screen.window_width() 82 | height = self.screen.window_height() 83 | return width, height 84 | 85 | def on_canvas(self): 86 | """Return bool; True if turtle on canvas. 87 | """ 88 | x, y = self.position() 89 | width, height = self.canvas_size() 90 | if (abs(x) >= width//2 or abs(y) >= height//2): 91 | return False 92 | return True 93 | 94 | def constrained_position(self): 95 | x, y = self.position() 96 | width, height = self.canvas_size() 97 | if abs(x) >= width//2: 98 | x = math.copysign(width//2, x) 99 | if abs(y) > height//2: 100 | y = math.copysign(height//2, y) 101 | return x, y 102 | 103 | def step(self): 104 | if not self.is_content(): 105 | self.setheading(random.randint(0,360)) 106 | self.fd(5) 107 | 108 | def is_content(self, threshold=0.33): 109 | """Return bool, True if content. 110 | Find the `k` closest neighbors. 111 | Determine the fraction of these that are the same "kind". 112 | This is called the segregation_ratio. 113 | If segregation_ratio>threshold, the agent is content. 114 | Schelling threshold: "each wants something 115 | more than one-third of his neighbors to be like himself" (p.148). 116 | """ 117 | ratio = self.segregation_ratio() 118 | is_content = True if (ratio > threshold) else False 119 | return is_content 120 | 121 | def segregation_ratio(self): 122 | nbrs = self.neighbors() 123 | n_alike = sum(self.is_like(other) for other in nbrs) 124 | ratio = float(n_alike) / len(nbrs) 125 | return ratio 126 | 127 | def neighbors(self): 128 | """Return list, the neighbors. 129 | Schelling had 8 neighbors (Moore neighborhood on a grid). 130 | """ 131 | return self.nearest(8) 132 | 133 | def nearest(self, k): 134 | """Return list, the k nearest neighbors.""" 135 | agents = self.screen._turtles 136 | others = (t for t in agents if t is not self) 137 | sortkey = self.distance 138 | nearest = sorted(others, key=sortkey)[:k] 139 | return nearest 140 | 141 | def add_tag(self, s): 142 | self.tags.add(s) 143 | 144 | def remove_tag(self, s): 145 | self.tags.remove(s) 146 | 147 | def is_like(self, other): 148 | return bool(self.tags & other.tags) 149 | 150 | def show_neighbors(self, x=0, y=0): 151 | mycolor = self.color() 152 | self.fillcolor('green') 153 | x1, y1 = self.position() 154 | nbrs = self.neighbors() 155 | """ 156 | #assume neighbors sorted by distance 157 | radius = self.distance(nbrs[-1]) 158 | self.right(90) 159 | self.fd(radius, constrain=False) 160 | self.left(90) 161 | self.pendown() 162 | self.circle(radius) 163 | self.pu() 164 | self.goto(x1,y1) 165 | """ 166 | nbr_colors = dict() 167 | for nbr in nbrs: 168 | nbr_colors[nbr] = nbr.color() 169 | nbr.pencolor('green') 170 | time.sleep(2) 171 | self.clear() 172 | #restore colors 173 | self.color(*mycolor) 174 | for nbr in nbrs: 175 | nbr.color(*nbr_colors[nbr]) 176 | 177 | 178 | if __name__ == "__main__": 179 | world = SchellingWorld() 180 | world.run() 181 | print(world.history) 182 | turtle.mainloop() 183 | 184 | -------------------------------------------------------------------------------- /abm/template_models/README.txt: -------------------------------------------------------------------------------- 1 | This README accompanies the code used in the paper entitled 2 | "The ABM Template Models: A Reformulation with Reference Implementations". 3 | The code is copyright 2011 by Alan G. Isaac, but is released under 4 | the MIT license: http://www.opensource.org/licenses/mit-license 5 | (Roughly that means you can do as you wish with the code, 6 | as long as you acknowledge this copyright and do not expect any warranty.) 7 | 8 | To run this code you need: 9 | 10 | - Python 2.6 or 2.7 (including Tkinter) 11 | - the gridworld module: 12 | http://econpy.googlecode.com/svn-history/r176/trunk/abm/gridworld/gridworld.py 13 | - the cell data file for template model 15 14 | from http://condor.depaul.edu/~slytinen/abm/ 15 | 16 | To run template model 8 and above, you need write privileges 17 | on your computer: the models will attempt to write to 18 | /temp/temp.csv. (This location is easily changed at 19 | the top of template08.py.) 20 | 21 | Each model is designed to be run separately, 22 | but later models import from earlier models. 23 | So unzip all of the template models into a common directory. 24 | Also, copy gridworld.py into this same directory 25 | (or make it available on your PYTHONPATH). 26 | Finally, unzip the cell data file into the same directory, 27 | giving the name Cell.Data to the unzipped file. 28 | 29 | Note that gridworld uses Tkinter. Do not try to run the 30 | template models in IDLE, which is also written in Tkinter. 31 | It is best to run them from a command shell. 32 | 33 | 34 | ADDENDUM 2018-08-12: Thanks to Steve Railsback for permitting 35 | the addition of the file Cell.Data to this repository, also 36 | under the MIT license. 37 | -------------------------------------------------------------------------------- /abm/template_models/template00.py: -------------------------------------------------------------------------------- 1 | """ Template Model 1 (procedural): Random Movement on a Toroidal Grid """ 2 | 3 | import random 4 | from gridworld import Agent, TorusGrid, GridWorld 5 | from gridworld import moore_neighborhood, GridWorldGUI 6 | 7 | params = dict(world_shape=(100,100), n_agents=100, maxiter=100) 8 | 9 | def move(agent): 10 | choice = choose_location(agent) 11 | agent.position = choice 12 | 13 | def choose_location(agent): 14 | old_position = agent.position 15 | hood = moore_neighborhood(radius=4, center=old_position) 16 | random.shuffle(hood) 17 | for location in hood: 18 | if agent.world.is_empty(location): 19 | return location 20 | return old_position 21 | 22 | def schedule(): 23 | for agent in myagents: 24 | move(agent) 25 | 26 | def run(maxiter): 27 | for ct in range(maxiter): 28 | myobserver.off() 29 | schedule() 30 | myobserver.on() 31 | 32 | #create a grid and a world based on this grid 33 | mygrid = TorusGrid(shape=params['world_shape']) 34 | myworld = GridWorld(topology=mygrid) 35 | #create agents, located in `myworld`, and then set display suggestions 36 | myagents = myworld.create_agents(AgentType=Agent, number=params['n_agents']) 37 | for agent in myagents: 38 | agent.display(shape='circle', fillcolor='red', shapesize=(0.25,0.25)) 39 | #add an observer 40 | myobserver = GridWorldGUI(myworld) 41 | #run the simulation by repeatedly executing the schedule 42 | run(maxiter=params['maxiter']) 43 | -------------------------------------------------------------------------------- /abm/template_models/template01.py: -------------------------------------------------------------------------------- 1 | """ Template Model 1: Random Movement on a Toroidal Grid """ 2 | 3 | import random 4 | from gridworld import Agent, TorusGrid, GridWorld 5 | from gridworld import moore_neighborhood, GridWorldGUI 6 | params = dict(world_shape=(100,100), n_agents=100, maxiter=100) 7 | 8 | class Agent01(Agent): 9 | def move(self): 10 | choice = self.choose_location() 11 | self.position = choice 12 | def choose_location(self): 13 | old_position = self.position 14 | hood = moore_neighborhood(radius=4, center=old_position) 15 | random.shuffle(hood) 16 | for location in hood: 17 | if self.world.is_empty(location): 18 | return location 19 | return old_position 20 | 21 | class World01(GridWorld): 22 | def schedule(self): 23 | for agent in self.agents: 24 | agent.move() 25 | 26 | if __name__ == '__main__': #setup and run the simulation 27 | mygrid = TorusGrid(shape=params['world_shape']) 28 | myworld = World01(topology=mygrid) 29 | myagents = myworld.create_agents(AgentType=Agent01, number=params['n_agents']) 30 | for agent in myagents: 31 | agent.display(shape='circle', fillcolor='red', shapesize=(0.25,0.25)) 32 | observer = GridWorldGUI(myworld) 33 | myworld.run(maxiter=params['maxiter']) #run the schedule repeatedly 34 | -------------------------------------------------------------------------------- /abm/template_models/template02.py: -------------------------------------------------------------------------------- 1 | """ Template Model 2: Dynamic Agent State """ 2 | 3 | from time import sleep 4 | from gridworld import ask 5 | from template01 import * 6 | params.update(agent_initial_size=0.0, extraction_rate=0.1) 7 | 8 | class Agent02(Agent01): 9 | def initialize(self): 10 | self.size = params['agent_initial_size'] 11 | self.display(shape='circle', shapesize=(0.25,0.25)) 12 | self.change_color() 13 | def change_size(self): 14 | self.size += self.extract() 15 | self.change_color() 16 | def extract(self): 17 | return params['extraction_rate'] 18 | def change_color(self): 19 | g = b = max(0.0, 1.0 - self.size/10) 20 | self.display(fillcolor=(1.0, g, b)) 21 | 22 | class World02(GridWorld): 23 | def schedule(self): 24 | sleep(0.2) 25 | ask(self.agents, 'move') 26 | ask(self.agents, 'change_size') 27 | 28 | if __name__ == '__main__': 29 | myworld = World02(topology=TorusGrid(shape=params['world_shape'])) 30 | myagents = myworld.create_agents(Agent02, number=params['n_agents']) 31 | myobserver = GridWorldGUI(myworld) 32 | myworld.run(maxiter=params['maxiter']) 33 | myobserver.mainloop() # keep GUI open after `run` completes 34 | -------------------------------------------------------------------------------- /abm/template_models/template03.py: -------------------------------------------------------------------------------- 1 | """ Template Model 3: Spatially Distributed Resources """ 2 | 3 | from gridworld import Patch 4 | from template02 import * 5 | params.update(cell_initial_supply=0.0, cell_max_produce=0.01) 6 | params.update(agent_max_extract=1.0) 7 | 8 | class Cell03(Patch): 9 | max_produce = params['cell_max_produce'] 10 | supply = params['cell_initial_supply'] 11 | def produce(self): 12 | self.supply += random.uniform(0, self.max_produce) 13 | def provide(self, amount): 14 | amount = min(self.supply, amount) 15 | self.supply -= amount 16 | return amount 17 | 18 | class Agent03(Agent02): 19 | max_extract = params['agent_max_extract'] 20 | def extract(self): 21 | mytake = self.patch.provide(self.max_extract) 22 | return mytake 23 | 24 | class World03(GridWorld): 25 | def schedule(self): 26 | ask(self.patches, 'produce') 27 | ask(self.agents, 'move') 28 | ask(self.agents, 'change_size') 29 | 30 | if __name__ == '__main__': 31 | myworld = World03(topology=TorusGrid(shape=params['world_shape'])) 32 | mypatches = myworld.create_patches(Cell03) #setup patches 33 | myagents = myworld.create_agents(Agent03, number=params['n_agents']) 34 | myobserver = GridWorldGUI(myworld) 35 | myworld.run(maxiter=params['maxiter']) 36 | myobserver.mainloop() 37 | -------------------------------------------------------------------------------- /abm/template_models/template04.py: -------------------------------------------------------------------------------- 1 | """ Template Model 4: Probe Object State """ 2 | 3 | from template03 import * 4 | 5 | class GUI04(GridWorldGUI): 6 | def gui(self): 7 | self.add_clickmonitor('Agent', Agent03, 'size') 8 | self.add_clickmonitor('Cell', Cell03, 'supply') 9 | 10 | if __name__ == '__main__': 11 | myworld = World03(topology=TorusGrid(shape=params['world_shape'])) 12 | mypatches = myworld.create_patches(Cell03) #setup patches 13 | myagents = myworld.create_agents(Agent03, number=params['n_agents']) 14 | myobserver = GUI04(myworld) 15 | myworld.run(maxiter=params['maxiter']) 16 | myobserver.mainloop() 17 | -------------------------------------------------------------------------------- /abm/template_models/template05.py: -------------------------------------------------------------------------------- 1 | """ Template Model 5: Parameter Interface """ 2 | 3 | from template04 import * 4 | 5 | class Agent05(Agent03): 6 | def initialize(self): 7 | Agent03.initialize(self) 8 | self.max_extract = self.world.agent_max_extract 9 | 10 | class World05(World03): 11 | AgentType = Agent05 12 | PatchType = Cell03 13 | n_agents = params['n_agents'] 14 | agent_max_extract = params['agent_max_extract'] 15 | def setup(self): 16 | self.setup_patches() 17 | self.setup_agents() 18 | def setup_patches(self): 19 | self.create_patches(self.PatchType) 20 | def setup_agents(self): 21 | self.create_agents(self.AgentType, number=self.n_agents) 22 | 23 | class GUI05(GUI04): 24 | def gui(self): 25 | GUI04.gui(self) 26 | self.add_slider('Initial Number of Bugs', 'n_agents', 10, 500, 10) 27 | self.add_slider('Agent Max Extract', 'agent_max_extract', 0.0, 2.0, 0.1) 28 | self.add_button('Set Up', 'setup') 29 | self.add_button('Run', 'run') 30 | self.add_button('Stop', 'stop') 31 | 32 | if __name__ == '__main__': 33 | myworld = World05(topology=TorusGrid(shape=params['world_shape'])) 34 | myobserver = GUI05(myworld) 35 | myobserver.mainloop() 36 | -------------------------------------------------------------------------------- /abm/template_models/template06.py: -------------------------------------------------------------------------------- 1 | """ Template Model 6: Animated Histogram """ 2 | 3 | from template05 import * 4 | 5 | class GUI06(GUI05): 6 | def gui(self): 7 | GUI05.gui(self) 8 | def get_agent_sizes(): 9 | agents = self.subject.get_agents(self.subject.AgentType) 10 | return list(agent.size for agent in agents) 11 | self.add_histogram('Agent Sizes', get_agent_sizes, bins=range(11)) 12 | 13 | if __name__ == '__main__': 14 | myworld = World05(topology=TorusGrid(shape=params['world_shape'])) 15 | myobserver = GUI06(myworld) 16 | myobserver.mainloop() 17 | -------------------------------------------------------------------------------- /abm/template_models/template07.py: -------------------------------------------------------------------------------- 1 | """ Template Model 7: Stopping Condition """ 2 | 3 | from template06 import * 4 | 5 | class World07(World05): 6 | def schedule(self): 7 | World05.schedule(self) 8 | if max(agent.size for agent in self.agents) >= 100: 9 | self.stop(exit=True) 10 | 11 | if __name__ == '__main__': 12 | myworld = World07(topology=TorusGrid(shape=params['world_shape'])) 13 | myobserver = GUI06(myworld) 14 | myobserver.mainloop() 15 | -------------------------------------------------------------------------------- /abm/template_models/template08.py: -------------------------------------------------------------------------------- 1 | """ Template Model 8: Log Model State Information to File """ 2 | 3 | from gridworld import describe 4 | from template07 import * 5 | params.update(logfile='/temp/sizes.csv', logformat='\n{min}, {mean}, {max}') 6 | 7 | class World08(World05): 8 | def setup(self): 9 | World05.setup(self) 10 | self.header2logfile() # write header to logfile 11 | def header2logfile(self): 12 | with open(params['logfile'], 'w') as fout: 13 | fout.write('minimum, mean, maximum') 14 | def log2logfile(self): 15 | agents = self.get_agents(self.AgentType) 16 | sizes = list(agent.size for agent in agents) 17 | stats = describe(sizes) 18 | with open(params['logfile'], 'a') as fout: 19 | fout.write(params['logformat'].format(**stats)) 20 | def schedule(self): 21 | self.log2logfile() 22 | World05.schedule(self) 23 | if max(agent.size for agent in self.agents) >= 100: #from model 7 24 | self.log2logfile() #log final agent state 25 | self.stop(exit=True) 26 | 27 | if __name__ == '__main__': 28 | myworld = World08(topology=TorusGrid(shape=params['world_shape'])) 29 | myobserver = GUI06(myworld) 30 | myobserver.mainloop() 31 | -------------------------------------------------------------------------------- /abm/template_models/template09.py: -------------------------------------------------------------------------------- 1 | """ Template Model 9: Randomized Agent Actions """ 2 | 3 | from gridworld import askrandomly 4 | from template08 import * 5 | 6 | class World09(World08): 7 | def schedule(self): 8 | self.log2logfile() #version 8 adds logging 9 | ask(self.patches, 'produce') 10 | #version 9: agents move in random order 11 | askrandomly(self.agents, 'move') 12 | ask(self.agents, 'change_size') 13 | #consistency chk: no two agents should share a position 14 | assert len(set(a.position for a in self.agents))==len(self.topology) 15 | #version 7 adds stopping condition 16 | if max(agent.size for agent in self.agents) >= 100: 17 | self.stop(exit=True) 18 | 19 | if __name__ == '__main__': 20 | myworld = World09(topology=TorusGrid(shape=params['world_shape'])) 21 | myobserver = GUI06(myworld) 22 | myobserver.mainloop() 23 | -------------------------------------------------------------------------------- /abm/template_models/template10.py: -------------------------------------------------------------------------------- 1 | """ Template Model 10: Hierarchy """ 2 | 3 | from template09 import * 4 | 5 | class World10(World08): 6 | def sortkey10(self, agent): 7 | return agent.size 8 | def schedule(self): 9 | self.log2logfile() #from model 8 10 | ask(self.patches, 'produce') #from model 3 11 | agents = self.get_agents(self.AgentType) 12 | agents.sort(key=self.sortkey10, reverse=True) #model 10 13 | ask(agents, 'move') #from model 1 14 | ask(agents, 'change_size') #from model 3 15 | if max(agent.size for agent in agents) >= 100: #from model 7 16 | self.log2logfile() #from model 8 17 | self.stop(exit=True) 18 | 19 | if __name__ == '__main__': 20 | myworld = World10(topology=TorusGrid(shape=params['world_shape'])) 21 | myobserver = GUI06(myworld) 22 | myobserver.mainloop() 23 | -------------------------------------------------------------------------------- /abm/template_models/template11.py: -------------------------------------------------------------------------------- 1 | """ Template Model 11: Optimization """ 2 | 3 | from gridworld import maximizers 4 | from template10 import * 5 | 6 | class Agent11(Agent05): 7 | def sortkey11(self, cell): 8 | return cell.supply 9 | def choose_location(self): 10 | MyType = self.__class__ 11 | hood = self.neighborhood('moore', 4) #get the neighboring cells 12 | available = [cell for cell in hood if not cell.get_agents(MyType)] 13 | available.append(self.patch) #agent can always stay put 14 | best_cells = maximizers(self.sortkey11, available) 15 | if self.patch in best_cells: 16 | return self.position 17 | else: 18 | return random.choice(best_cells).position 19 | 20 | class World11(World10): 21 | AgentType = Agent11 22 | 23 | if __name__ == '__main__': 24 | myworld = World11(topology=TorusGrid(shape=params['world_shape'])) 25 | myobserver = GUI06(myworld) 26 | myobserver.mainloop() 27 | -------------------------------------------------------------------------------- /abm/template_models/template12.py: -------------------------------------------------------------------------------- 1 | """ Template Model 12: Entry and Exit """ 2 | 3 | from template11 import * 4 | params.update(agent_exit_probability=0.05) 5 | 6 | class Agent12(Agent11): 7 | def split_if_ready(self): 8 | if self.size > 10: 9 | self.propagate() 10 | self.die() 11 | def propagate(self): 12 | MyType = self.__class__ #splits share agent class 13 | hood4split = self.neighborhood('moore', radius=3) 14 | cells4split = list() 15 | for i in range(5): #5 propagation attempts 16 | for cell in random.sample(hood4split, 5): #5 tries per attempt 17 | if cell not in cells4split and not cell.get_agents(MyType): 18 | cells4split.append(cell) 19 | break 20 | splitlocs = list(cell.position for cell in cells4split) 21 | splits = self.world.create_agents(MyType, locations=splitlocs) 22 | return splits 23 | def venture(self): 24 | if random.uniform(0,1) < params['agent_exit_probability']: 25 | self.die() 26 | 27 | class World12(World11): 28 | AgentType = Agent12 29 | def schedule(self): 30 | World11.schedule(self) 31 | agents = self.get_agents(self.AgentType) 32 | askrandomly(agents, 'split_if_ready') #creates new entrants 33 | agents = self.get_agents(self.AgentType) #include new entrants 34 | ask(agents, 'venture') 35 | if (self.iteration==1000) or (len(agents)==0): #model 12 36 | self.log2logfile() #from model 8 37 | self.stop() 38 | 39 | if __name__ == '__main__': 40 | myworld = World12(topology=TorusGrid(shape=params['world_shape'])) 41 | myobserver = GUI06(myworld) 42 | myobserver.mainloop() 43 | -------------------------------------------------------------------------------- /abm/template_models/template13.py: -------------------------------------------------------------------------------- 1 | """ Template Model 13: Time-Series Plot """ 2 | 3 | from template12 import * 4 | 5 | class GUI13(GUI06): 6 | def gui(self): 7 | GUI06.gui(self) 8 | def number_living(): 9 | world = self.subject 10 | return len(world.get_agents(world.AgentType)) 11 | self.add_plot('Number of Agents', number_living) 12 | 13 | if __name__ == '__main__': 14 | myworld = World12(topology=TorusGrid(shape=params['world_shape'])) 15 | myobserver = GUI13(myworld) 16 | myobserver.mainloop() 17 | -------------------------------------------------------------------------------- /abm/template_models/template14.py: -------------------------------------------------------------------------------- 1 | """ Template Model 14: Randomized Model Initialization """ 2 | 3 | from template13 import * 4 | params.update(agent_size_mean=0.1, agent_size_sd=0.03) 5 | 6 | class World14(World12): 7 | agent_size_mean = params['agent_size_mean'] 8 | agent_size_sd = params['agent_size_sd'] 9 | def setup_agents(self): #random size for initial agents 10 | myagents = self.create_agents(self.AgentType, number=self.n_agents) 11 | mean = self.agent_size_mean 12 | sd = self.agent_size_sd 13 | for agent in myagents: 14 | size_drawn = random.normalvariate(mean, sd) 15 | agent.size = max(0.0, size_drawn) 16 | 17 | class GUI14(GUI13): 18 | def gui(self): 19 | GUI13.gui(self) 20 | self.add_slider('Init. Size Mean', 'agent_size_mean', 0.0, 1.0, 0.1) 21 | self.add_slider('Init. Size SD', 'agent_size_sd', 0.0, 0.1, 0.01) 22 | 23 | if __name__ == '__main__': 24 | myworld = World14(topology=TorusGrid(shape=params['world_shape'])) 25 | myobserver = GUI14(myworld) 26 | myobserver.mainloop() 27 | -------------------------------------------------------------------------------- /abm/template_models/template15.py: -------------------------------------------------------------------------------- 1 | """ Template Model 15: Data-Based Model Initialization """ 2 | 3 | from gridworld import RectangularGrid 4 | from template14 import * 5 | params.update(cell_data_file='Cell.Data') 6 | 7 | def read_celldata(filename): 8 | location2value = dict() 9 | maxx, maxy = 0, 0 10 | fh = open(filename, 'r') 11 | for _ in range(3): #discard 3 lines 12 | trash = next(fh) 13 | for line in fh: 14 | x, y, prodrate = line.split() 15 | x, y, prodrate = int(x), int(y), float(prodrate) 16 | location2value[(x,y)] = prodrate 17 | maxx, maxy = max(x,maxx), max(y,maxy) 18 | location2value['shape'] = (maxx+1, maxy+1) 19 | return location2value 20 | 21 | class Cell15(Cell03): 22 | def initialize(self): 23 | self.change_color() 24 | def produce(self): 25 | self.supply += self.max_produce #no longer random 26 | self.change_color() 27 | def change_color(self): 28 | r = b = 0 29 | g = min(2*self.supply, 1.0) 30 | self.display(fillcolor=(r, g, b)) 31 | 32 | class World15(World14): 33 | PatchType = Cell15 34 | def setup_patches(self): 35 | celldata = read_celldata(params['cell_data_file']) 36 | shape = celldata.pop('shape') 37 | self.set_topology(RectangularGrid(shape=shape)) 38 | patches = self.create_patches(self.PatchType) 39 | for (x,y), prodrate in celldata.items(): 40 | patches[x][y].max_produce = prodrate 41 | 42 | if __name__ == '__main__': 43 | myworld = World15(topology=None) 44 | myobserver = GUI14(myworld) 45 | myobserver.mainloop() 46 | -------------------------------------------------------------------------------- /abm/template_models/template16.py: -------------------------------------------------------------------------------- 1 | """ Template Model 16: Interacting Agents of Different Types """ 2 | 3 | from template15 import * 4 | 5 | class Hunter(Agent): 6 | def initialize(self): 7 | self.display(fillcolor='yellow', shapesize=(0.75,0.75)) 8 | def hunt(self): 9 | hunthood = self.neighborhood('moore', radius=1, keepcenter=True) 10 | random.shuffle(hunthood) 11 | change_position = True 12 | for patch in hunthood: 13 | hunters = patch.get_agents(AgentType=Hunter) 14 | gatherers = patch.get_agents(Agent12) 15 | if hunters and not self in hunters: 16 | change_position = False 17 | break 18 | elif gatherers: 19 | gatherers.pop().die() 20 | self.position = patch.position 21 | change_position = False 22 | break 23 | if change_position: #encountered no gatherers nor hunters 24 | newcell = random.choice(hunthood) 25 | self.position = newcell.position 26 | 27 | class World16(World15): 28 | def schedule(self): 29 | World15.schedule(self) 30 | hunters = self.get_agents(Hunter) 31 | askrandomly(hunters, 'hunt') 32 | def setup(self): 33 | World15.setup(self) 34 | hunter_locations = self.random_locations(200) 35 | hunters = self.create_agents(Hunter, locations=hunter_locations) 36 | 37 | if __name__ == '__main__': 38 | myworld = World16(topology=TorusGrid(shape=params['world_shape'])) 39 | myobserver = GUI14(myworld) 40 | myobserver.mainloop() 41 | -------------------------------------------------------------------------------- /abm/utilities.py: -------------------------------------------------------------------------------- 1 | from ..pytrix.utilities import permutations, py_gini 2 | import logging 3 | 4 | import random 5 | rng = random.Random() 6 | rng.seed(314) 7 | 8 | import numpy as np 9 | 10 | def match_exclude(group1, group2, exclude): 11 | """Return list of matched pairs meeting an exclusion criterion. 12 | 13 | :Parameters: 14 | group1 : sequence 15 | first group for matches 16 | group2 : sequence 17 | second group for matches 18 | exclude : function 19 | should return True if pairing is excluded else False 20 | :rtype: list of tuples 21 | :return: pairs meeting exclusion criterion 22 | :requires: Python 2.5+ (uses `any`) 23 | :requires: permutations from econpy.pytrix.utilities 24 | :since: 2005-06-20 25 | :date: 2007-12-05 26 | :contact: mailto:aisaac AT american.edu 27 | """ 28 | #one group may be larger; call it group2 29 | success = False 30 | #get all the permutations of the larger group 31 | # TODO: use k-permuations 32 | if len(group1) <= len(group2): 33 | biggroup_permutations = permutations(group2) 34 | for g in biggroup_permutations: 35 | result = zip(group1, g) 36 | if not any( exclude(m,f) for (m,f) in result ): 37 | success = True 38 | break 39 | else: 40 | biggroup_permutations = permutations(group1) 41 | for g in biggroup_permutations: 42 | result = zip(g, group2) 43 | if not any( exclude(m,f) for (m,f) in result ): 44 | success = True 45 | break 46 | if success: 47 | return result 48 | 49 | def sexer_mf(n): 50 | """Yield str: M, F n times each.""" 51 | for i in range(n): 52 | yield 'M' 53 | yield 'F' 54 | 55 | def sexer_random2(n, rng=rng): 56 | """Yield str: 'M' or 'F' randomly, 57 | holding overall sex ratio constant. 58 | 59 | n : int 60 | number of each sex 61 | rng : Random instance 62 | random number generator 63 | :note: wasteful if cohorts are very large, 64 | use n_each_rand instead 65 | """ 66 | sexes = list('MF'*n) 67 | rng.shuffle(sexes) 68 | for s in sexes: 69 | yield s 70 | 71 | 72 | 73 | def n_each_rand(n, kindtuple=('M','F'), rng=rng): 74 | """Yields n of each of two (immutable) objects, 75 | in random order. 76 | 77 | If we still need to generate 78 | ct0 of kind0 and ct1 of kind1 79 | then we will yield 80 | a kind0 object with probability ct0/(ct0+ct1) 81 | 82 | Parameters 83 | ---------- 84 | 85 | n : int 86 | number of *each* kind to generate 87 | kindtuple : tuple 88 | 2-tuple contains the two immutable objects 89 | 90 | :requires: Python 2.4+ 91 | :since: 2005-06-20 92 | :date: 2007-12-05 93 | """ 94 | assert (n>0), "n shd be a positive integer" 95 | kind0, kind1 = kindtuple 96 | ct0, total = n, n+n 97 | while (total > 0): 98 | if rng.random() * total < ct0: 99 | next_kind = kind0 100 | ct0 -= 1 101 | else: 102 | next_kind = kind1 103 | total -= 1 104 | yield next_kind 105 | assert (ct0 == 0) 106 | 107 | 108 | 109 | def gini2sharesPareto(gini, nbrackets): 110 | """Return generator of floats: the incremental 111 | income share implied by `gini` for each bracket. 112 | (Brackets are evenly spaced.) 113 | 114 | Write the Lorenz curve for the Pareto distribution as 115 | $F(p) = 1 - (1 - p)^\delta$, 116 | where $p$ is the cumulative proportion of the population, 117 | $\delta=(1-G)/(1+G)$, and $G$ is the Gini. 118 | With $N$ brackets, let $p_i= i/N$ ($i=1,\dots,N$) 119 | and set the share of the $i/N$ proportion of agents to 120 | $F(p_i) = 1 - (1 - p_i)^\delta$. 121 | The incremental share is the $i$-th bracket is therefore 122 | F(p_i) - F(p_{i-1})$ and $p_{i}-p_{i-1} = 1/N$, so 123 | $(1 - (i- 1)/N)^\delta - (1 - i/N)^\delta$. 124 | or 125 | $[(N - (i- 1))^\delta - (N - i)^\delta](1/N)^\delta$. 126 | 127 | :note: roughly based on Eswaran & Kotwal (1986) 128 | :note: uses a right sum, so resulting Gini slightly low 129 | :since: 2013-10-19 130 | """ 131 | if not (0 <= gini < 1): 132 | raise ValueError('gini must be in (0,1)') 133 | if nbrackets != int(abs(nbrackets)): 134 | raise ValueError('nbrackets should be a positive integer') 135 | d = (1-gini)/(1+gini) #delta = B/(2A+B) 136 | sb = 1.0/nbrackets #width of brackets 137 | fpc1 = 1 # 1-F(0) 138 | i = 0.0 139 | for _ in range(nbrackets): 140 | i += 1 141 | #complement of i-th cumulative share 142 | fpc2 = (1 - i/nbrackets)**d #1-F(p_i) 143 | yield fpc1 - fpc2 144 | fpc1 = fpc2 145 | 146 | def gini2sharesPower(gini, nbrackets): 147 | """Return generator of floats: 148 | income share implied by `gini` for each bracket. 149 | (Income follows a power distribution.) 150 | 151 | :note: based on Yunker 1999, p.238 152 | :note: uses a right sum, so resulting Gini slightly low 153 | :note: consider Lorenz curve function representation 154 | y=x**g for g>1 155 | B = \int_0^1 x**g dx = x**(g+1)/(g+1) | = 1/(g+1) 156 | So G = 1-2B = (g-1)/(g+1) is the implied Gini 157 | Note (1+G)/(1-G) = 2g/2 = g. (Used below.) 158 | :since: 2006-06-20 159 | :date: 2013-10-19 160 | """ 161 | if not (0 <= gini < 1): 162 | raise ValueError('gini must be in (0,1)') 163 | if nbrackets != int(abs(nbrackets)): 164 | raise ValueError('nbrackets should be a positive integer') 165 | g = (1+gini)/(1-gini) # (2A+B)/B 166 | sb = 1.0/nbrackets #size (i.e., width) of brackets 167 | sbg = sb**g 168 | ig = 0 169 | for i in range(nbrackets): 170 | #i-th cumulative share is (1+i)**g * sb**g 171 | ig2 = (1+i)**g 172 | yield (ig2-ig) * sbg 173 | ig = ig2 174 | 175 | 176 | #Use of gini2shares is deprecated 177 | gini2shares = gini2sharesPower 178 | 179 | 180 | def impose_gini(wtotal, units, gini, shuffle=False): 181 | """Return None. 182 | Distribute resources `wtotal` among members of `units` based on `gini`, 183 | imposing a `gini` based distribution. 184 | 185 | :Parameters: 186 | wtotal : number 187 | total resources to distribute 188 | units : list 189 | units (households) to share `wtotal`, must have `payin` method 190 | gini : float 191 | Gini coefficient that should result from distribution 192 | shuffle : bool 193 | if False, first unit receives least resources, etc. 194 | :note: lots of copying! (not good for very large number of households) 195 | :note: need to compute number of units *before* distributing. 196 | :todo: eliminate redundant error checks 197 | :comment: uses Indiv methods ... 198 | :comment: was named `distribute` long ago 199 | """ 200 | units = list(units) 201 | logging.debug("""Enter utilities.impose_gini. 202 | wtotal: %f 203 | units: %s 204 | gini: %f 205 | shuffle: %s"""%(wtotal,units[:5],gini, shuffle) ) 206 | nb = len(units) #number of brackets 207 | shares = list( gini2shares(gini, nb) ) 208 | if shuffle: #enforce Gini but distribute randomly 209 | rng.shuffle(shares) 210 | w = ( wtotal*share for share in shares ) 211 | ct = 0 212 | units2 = set() #this is just for error check 213 | for i, w_i in zip(units, w): 214 | i.payin(w_i) #ADD to individual wealth 215 | units2.add(i) 216 | assert len(units2)==nb, "`units` shd not contain duplicates" 217 | logging.debug( "Desired gini: %4.2f, Achieved Gini: %4.2f"%( gini,calc_gini( i.networth for i in units2 ))) 218 | 219 | -------------------------------------------------------------------------------- /dynopt/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /dynopt/detcake.py: -------------------------------------------------------------------------------- 1 | """ DETERMINISTIC CAKE EATING MODEL 2 | ** Follows Chapter 2 of Adda and Cooper (See Section 2.4.1, Page 16) 3 | ** This code modifies detcake.m (as provided by the book authors 22 Dec 03) 4 | ** to improve efficiency and avoid propagating missing values. 5 | 6 | 7 | :contact: aisaac AT american DOT edu 8 | :since: 29 Dec 2003 9 | 10 | Comments: 11 | Some simplifying tricks are used: 12 | i. Following Adda & Cooper (and many others) restrict possible 13 | consumption levels so that K(t+1) = K(t)-c is in the 14 | discrete domain of the numerical value function, 15 | thereby avoiding interpolation. 16 | ii. Note that the value function iterates as 17 | V[K(t),iter+1] = max_ik2 {ln(K(t)-K(t+1))+beta*V[K(t+1),iter]} 18 | where K takes a discrete set of values 19 | [Kmin,Kmin+inc,Kmin+2inc,...,Kmax]. 20 | Problem: suppose K(t) = Kmin. Then K(t+1) = Kmin and c(t) = 0. 21 | (This includes the case where Kmin = 0.) 22 | Adda and Cooper set the value to missing (-inf wd work the same). 23 | Problem: consider K(t) = Kmin+inc. Then K(t+1) = Kmin and c(t) = inc. 24 | (This includes the case where Kmin = 0.) But if V(Kmin) = missing, 25 | missing values will propogate to V(Kmin+inc) upon iteration, 26 | and these in turn will propogate. 27 | So: we extrapolate V(Kmin) instead of setting it to missing. 28 | Problem: gives a silly answer at the boundary when Kmin = 0. 29 | We can live with this. 30 | """ 31 | import numpy as np 32 | from matplotlib import pyplot as plt 33 | 34 | dimIter = 40 # number of iterations 35 | dimK = 101 36 | K = np.arange(dimK) # grid over cake size (starts at 0; see notes above) 37 | # Note: grid over consumption is the same 38 | # Note: graph appearance depends on grid! 39 | 40 | #Define payoff: 41 | # any continuous, strictly increasing, strictly concave function shd be ok 42 | def u(x): return np.log(x) #single period payoff 43 | beta = 0.9 # discount factor 44 | 45 | """ 46 | V stores the value function iterations. 47 | Rows are cake sizes, columns the iteration. 48 | Only initialization of the first column matters (iteration 0)""" 49 | V = np.zeros( (dimK, dimIter+1) ) 50 | #note: ^ 51 | 52 | #tempind stores best index (of K) after each iteration 53 | tempind = np.zeros( (dimK,) ) * np.nan 54 | #doe dimIter iterations 55 | for iter in range(dimIter): 56 | temp = np.zeros( (dimK,) ) * np.nan #stores values during iteration 57 | for ik in range(dimK-1): #loop over initial (endowment) cake sizes 58 | ik += 1 59 | #max u over next period cake sizes (which imply c) 60 | c = K[ik]-K[:ik] #positive possible consumption values 61 | Vk = u(c)+beta*V[:ik,iter] #current payoff plus value of remaining cake 62 | #store best value this iteration (ik, iteration over K) 63 | temp[ik] = np.nanmax(Vk) 64 | if iter == dimIter-1: #on last iter, save index of best size 65 | tempind[ik] = np.argmax(Vk) 66 | V[:,iter+1] = temp # optimizing over size of next period cake 67 | #Next: a crude extrapolation just to avoid propogating missing values from V(0): 68 | V[0,iter+1] = 2*V[1,iter+1]-V[2,iter+1] 69 | 70 | # computing the optimal consumption as a function of initial cake size 71 | tempind[np.isnan(tempind)] = 1 72 | Ind = tempind.astype(np.int) 73 | optK = K[Ind]+temp*0 #Note: Ind[r] = 1 when cakesize r is all missing values 74 | optC = K-optK 75 | 76 | # ** Plotting the value function after each iterations ** 77 | fig1 = plt.figure(1) 78 | fig1ax = fig1.gca() 79 | fig1ax.set_xlabel("Size of Cake") 80 | fig1ax.set_ylabel("Value Function") 81 | fig1ax.plot(K,V[:,1:]) 82 | 83 | # ** Plotting the optimal consumption levels ** 84 | fig2 = plt.figure(2) 85 | fig2ax = fig2.gca() 86 | fig2ax.set_xlabel("Size of Cake") 87 | fig2ax.set_ylabel("Optimal Consumption (vs. 45 degree line)") 88 | fig2ax.plot(K,optC) 89 | fig2ax.plot(K,K) 90 | 91 | plt.show() 92 | 93 | 94 | -------------------------------------------------------------------------------- /dynopt/kurtz.py: -------------------------------------------------------------------------------- 1 | """ 2 | This implements a finite-state optimal consumption model. 3 | You can find a description of the model and another approach to solution 4 | in John Stachurski's book *Economic Dynamics* (on p.104) 5 | and in `John Stachurski's online notes`_. 6 | We will call this version the Kurtz model, 7 | in honor of Stachurski's supporting story. 8 | 9 | :requires: Python 2.5+; NumPy 1.3+ 10 | :since: 2009-05-07 11 | :contact: aisaac AT american DOT edu 12 | 13 | .. _`John Stachurski's online notes`: 14 | http://johnstachurski.net/lectures/finite_growth.html 15 | """ 16 | import numpy as np 17 | 18 | class KurtzModel: 19 | def __init__(self): 20 | """Return None. 21 | """ 22 | #parameters (initialized to the Stachurski example values) 23 | self.maxcapacity = 5 24 | self.maxbites = 10 25 | self.rho = 0.9 #discount factor 26 | #create the shock space 27 | self.shock_space_size = self.maxbites + 1 28 | self.shock_space = np.arange(self.shock_space_size, dtype=np.int64) 29 | self.pdf_shocks = self.pdf() 30 | #create the state space 31 | self.state_space_size = self.shock_space_size + self.maxcapacity 32 | self.state_space = np.arange(self.state_space_size, dtype=np.int64) 33 | #list to store history 34 | self.value_history = list() 35 | 36 | def pdf(self): 37 | """Return array of float, 38 | the probability density (mass) function for the shock space 39 | (uniform distribution).""" 40 | return np.ones(self.shock_space_size) / self.shock_space_size 41 | 42 | def feasible_actions(self, state): 43 | """Return array of int, 44 | representing the feasible actions. 45 | In the Kurtz model, the state is total fish 46 | (past frozen plus random new catch) and the 47 | action is (capacity constrained) amount frozen. 48 | """ 49 | constraint = min(state, self.maxcapacity) 50 | return np.arange(constraint+1, dtype=np.int64) 51 | 52 | def payoffs(self, state, v): 53 | """Return array, the payoff for each feasible action. 54 | 55 | :param `state`: int, an index representing the state 56 | :param `v`: array, value of each future state 57 | """ 58 | acts = self.feasible_actions(state) 59 | current_values = self.u(state - acts) #utility for each act 60 | next_state = np.add.outer(acts, self.shock_space) #len(acts) by len(shock_space) 61 | future_values = np.dot(v[next_state], self.pdf_shocks) 62 | return current_values + self.rho * future_values 63 | 64 | def greedy(self, v): 65 | return list( self.payoffs(state, v).argmax() for state in self.state_space ) 66 | 67 | def T(self, v): 68 | """Return array, the iterated values. 69 | T is an implementation of the Bellman operator. 70 | 71 | :param `v`: array, function values on `state_space` 72 | """ 73 | values = ( self.payoffs(state, v).max() for state in self.state_space ) 74 | Tv = np.fromiter(values, dtype=np.float64) 75 | return Tv 76 | 77 | def u(self, c): 78 | """Return array of float, 79 | the 'utility' of each ci.""" 80 | return np.sqrt(c) 81 | 82 | def value_iteration(self, v=None, tol=1e-5): 83 | """Return None. Run the value iteration. 84 | """ 85 | T = self.T 86 | if v is None: 87 | #array of utilitys for a=0 (i.e., never store) 88 | v = self.u(self.state_space) 89 | history = list() 90 | history.append(v) 91 | vold = np.zeros_like(v) 92 | while (np.abs(v-vold).max()>tol): 93 | vold, v = v, T(v) 94 | history.append(v) 95 | self.value_history = history 96 | 97 | -------------------------------------------------------------------------------- /finance/test_finance.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Test functions for numpy.lib.financial 3 | 4 | All are taken from the OpenDocument Open Formula project 5 | 6 | http://www.oasis-open.org/committees/documents.php 7 | ''' 8 | 9 | import numpy.lib.financial as finance 10 | import numpy as np 11 | from numpy.testing import * 12 | import finance as f 13 | 14 | ### Additional tests for existing functions 15 | 16 | class TestFinancial(TestCase): 17 | 18 | def test_rate(self): 19 | # +- .001 20 | # assert_almost_equal(np.rate(12,-100,1000),0.0292285,3) 21 | # needs 4 values default should assume fv = 0 22 | assert_almost_equal(np.rate(12,-100,1000,100),0.01623133, 3) 23 | 24 | def test_rate(self): 25 | assert_almost_equal(np.rate(12,-100,1000,100,1), 0.01996455, 3) 26 | 27 | def test_rate(self): 28 | assert_almost_equal(np.rate(12,-100,1000,100,1,.01), 0.01996455, 3) 29 | # assert_almost_equal(np.rate(0,-100,1000),) This should raise an error 30 | # High Precision test +- .00000000001 31 | 32 | def test_rate(self): 33 | assert_almost_equal(np.rate(48,-50,2000,0,1,0),0.0080529819239056, 16) 34 | 35 | def test_rate(self): 36 | assert_almost_equal(np.rate(48,-50,2000,50,0,0),0.0080529819239056, 16) 37 | 38 | def test_rate(self): 39 | # Note Gnumeric truncates Nper is it is not an integer 40 | # OO Does not truncate and uses the fractional part in the calculation 41 | # OO behavior 42 | assert_almost_equal(np.rate(12.9,-100,1000, 0),.0388, 4) 43 | 44 | def test_rate(self): 45 | # Gnumeric behavior 46 | assert_almost_equal(np.rate(12.9,-100,1000, 0),.0292, 4) 47 | 48 | # rate notes 49 | # Excel allows fractional values of PayType 50 | # It appears to be an offset to the end date of the payment period 51 | # towards the start date of the period 52 | 53 | def test_irr(self): 54 | I = [-29, 20, 30] 55 | assert_almost_equal(np.irr(I), 0.418787000165341, 5) 56 | 57 | def test_pv(self): 58 | assert_almost_equal(np.pv(.10,12,-100,100), 649.51, 2) 59 | 60 | def test_fv(self): 61 | assert_almost_equal(np.fv(.10,12,-100,100),1824.59, 2) 62 | 63 | def test_pmt(self): 64 | assert_almost_equal(np.pmt(.05,12,1000),-112.82541, 3) 65 | 66 | def test_pmt(self): 67 | assert_almost_equal(np.pmt(.05,12,1000,100),-119.10795, 3) 68 | 69 | def test_pmt(self): 70 | assert_almost_equal(np.pmt(.05,12,1000,100,1), -113.43614, 3) 71 | 72 | def test_pmt(self): 73 | assert_almost_equal(np.pmt(0,10,1000),-100) 74 | 75 | def test_nper(self): 76 | assert_almost_equal(np.nper(.05,-100,1000),14.2067, 3) 77 | 78 | def test_nper(self): 79 | assert_almost_equal(np.nper(.05,-100,1000,100),15.2067, 3) 80 | 81 | def test_nper(self): 82 | assert_almost_equal(np.nper(.05,-100,1000,100,1),14.2067, 3) 83 | 84 | def test_nper(self): 85 | assert_almost_equal(np.nper(0,-100,1000),10) 86 | 87 | def test_nper(self): 88 | assert_almost_equal(np.nper(-.01,-100,1000),9.483283066, 3) 89 | 90 | def test_npv(self): 91 | # assert_almost_equal(np.npv(1.00,4,5,7), 4.125, 3) 92 | # cannot take values like this 93 | assert_almost_equal(np.npv(1.00,[4,5,7]), 4.125, 3) 94 | # assert_almost_equal(np.npv(.1,100,200), 256.198347107438, 3) 95 | # cannot take values like this 96 | 97 | def test_mirr(self): 98 | assert_almost_equal(np.mirr((100, 200,-50, 300,-200), .05, .06), 99 | 0.342823387842, 8) 100 | 101 | ### EconPy Functions 102 | def test_ipmt(self): 103 | assert_almost_equal(f.ipmt(.05/12,10,360,100000),-412.0850243, 4) 104 | 105 | # def test_ipmt(self): 106 | # Gnumeric and KSpread result 107 | # Note: kspread seems to have deprecated the beginning of period option 108 | # Check Gnumeric on Gnome at school 109 | # assert_almost_equal(f.ipmt(.05/12,10,360,100000,0,1), -412.1699604, 4) 110 | # This value is wrong. It is equivalent to finding the payments 111 | # of m=pmt(.05/12,10,360,100000,0,1) and using this beginning of period 112 | # value to calculate -(.05/12)*(100000)*(1+.05/12)**9 - m*((1+.05/12)**9-1) 113 | 114 | def test_impt(self): 115 | # Excel and OO results 116 | assert_almost_equal(f.ipmt(.05/12,10,360,100000,0,1), -410.38, 2) 117 | # This is correct and is based on the value of 118 | # -(.05/12)*(100000+m)*(1+.05/12)**9 - m*((1+/05/12)**9-1) 119 | 120 | def test_ppmt(self): 121 | assert_almost_equal(f.ppmt(.03,1,12,100), -7.046208547, 4) 122 | 123 | def test_ppmt(self): 124 | assert_almost_equal(f.ppmt(.03,1,12,100,200), -21.138625642, 4) 125 | 126 | def test_ppmt(self): 127 | assert_almost_equal(f.ppmt(.03,1,12,100,200,1), -23.435558876, 4) 128 | 129 | def test_ppmt(self): 130 | assert_almost_equal(f.ppmt(.08,5,24,10000,0), -203.773514049, 4) 131 | 132 | def test_ppmt(self): 133 | assert_almost_equal(f.ppmt(.08,10,24,100000,20), -359.292174601, 4) 134 | 135 | def test_ppmt(self): 136 | assert_almost_equal(f.ppmt(.08,10,24,10000,2000,1), -332.677939445, 4) 137 | 138 | 139 | if __name__=="__main__": 140 | run_module_suite() 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /integrate/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/integrate/__init__.py -------------------------------------------------------------------------------- /integrate/quadrature.py: -------------------------------------------------------------------------------- 1 | '''Provide some quadrature related classes and functions. 2 | 3 | :date: 2008-08-12 4 | :since: 2008-08-08 5 | :copyright: Alan G. Isaac, except where another author is specified. 6 | :license: `MIT license`_ 7 | 8 | .. _`MIT license`: http://www.opensource.org/licenses/mit-license.php 9 | ''' 10 | from __future__ import absolute_import 11 | from __future__ import division 12 | 13 | __docformat__ = "restructuredtext en" 14 | __author__ = 'Alan G. Isaac (and others as specified)' 15 | __lastmodified__ = '2008-08-12' 16 | 17 | from ..optimize.iterate import IterativeProcess, AbsDiff 18 | 19 | 20 | def riemann_p(f, p, tags): 21 | """Return float, 22 | a Riemann sum for the partition `p`.""" 23 | x1x2 = zip(p[:-1],p[1:]) 24 | if tags == 'left': 25 | result = sum( (x2-x1)*f(x1) for x1,x2 in x1x2 ) 26 | elif tags == 'right': 27 | result = sum( (x2-x1)*f(x2) for x1,x2 in x1x2 ) 28 | elif tags in ('center','middle'): 29 | result = sum( (x2-x1)*f((x1+x2)/2.0) for x1,x2 in x1x2 ) 30 | elif tags == 'trapz': #delay division by 2 31 | result = sum( (x2-x1)*(f(x1)+f(x2)) for x1,x2 in x1x2 ) 32 | else: 33 | raise ValueError("Unknown tag type: %s" % (tags)) 34 | if tags == 'trapz': 35 | result *= 0.5 36 | return result 37 | 38 | def riemann_n(f, a, b, n, tags): 39 | """Return float, 40 | a Riemann sum for `n` equal intervals.""" 41 | dx = (b - a) / float(n) 42 | if tags in ('left','right','trapz'): 43 | pt = a + dx 44 | elif tags in ('middle','center'): 45 | pt = a + dx/2.0 46 | else: 47 | raise ValueError("unknown tag type"%(tags)) 48 | result = sum(f(pt + i*dx) for i in range(n-1) ) 49 | if tags == 'left': 50 | result += f(a) 51 | elif tags == 'right': 52 | result += f(b) 53 | elif tags == 'trapz': 54 | result += (f(a) + f(b)) / 2.0 55 | else: # tags in ('middle','center'): 56 | result += f(b - dx/2.0) 57 | result *= dx 58 | return result 59 | 60 | def iterative_trapz(f, a, b, maxiter=100, prt=False): 61 | """Return float, 62 | quadrature of `f` based on iterative trapezoid rule. 63 | 64 | :requires: `riemann_n` 65 | """ 66 | refine = True; n = 1; iter = 0 67 | area = (b - a) * (f(a)+f(b)) / 2.0 68 | while(refine and iter 1.5e-8 75 | area = area_new 76 | return area 77 | 78 | class IterativeTrapz(IterativeProcess): 79 | def __init__(self, f, a, b, criterion=None, reportfreq=0): 80 | '''Return: None. 81 | Initialize the quadrature problem. 82 | Set a criterion. 83 | ''' 84 | self.f = f 85 | self.bounds = a, b 86 | self.iteration = 0 87 | self.ntrapz = 1 88 | self.value = (b - a) * (f(a)+f(b)) / 2.0 89 | self.history = [ self.value ] 90 | self.set_criterion(criterion) 91 | self.reportfreq = reportfreq 92 | #users usually override the following methods 93 | def default_criterion(self): 94 | return AbsDiff(precision=1.5e-8, maxiter=100) 95 | #users must implement the following methods 96 | def iterate(self): 97 | """Return float, 98 | quadrature of `f` based on iterative trapezoid rule. 99 | Used by `next`. 100 | 101 | :requires: `riemann_n` 102 | """ 103 | f = self.f 104 | a, b = self.bounds 105 | ntrapz = self.ntrapz 106 | area_old = self.history[-1] 107 | area_new = 0.5*(area_old + riemann_n(f, a, b, ntrapz, 'middle')) 108 | self.ntrapz *= 2 109 | return area_new 110 | def get_testinfo(self, value=None, iteration=0): 111 | '''Should return: testinfo usable by `criterion`. 112 | ''' 113 | return self.history[-1], value 114 | 115 | -------------------------------------------------------------------------------- /math/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/math/__init__.py -------------------------------------------------------------------------------- /optimize/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /plot/plot.py: -------------------------------------------------------------------------------- 1 | import pyx 2 | 3 | def pyx_scatter_plot_matrix(group,figwidth=18,hsep=1,vsep=1): 4 | """ 5 | Return: pyx canvas, 6 | a scatter plot matrix for the group. 7 | (group[i] must be the i-th series.) 8 | Sample use:: 9 | 10 | import numpy as np 11 | data = np.random.random((3,10)) 12 | test1 = pyx_scatter_plot_matrix(data) 13 | test1.writeEPSfile("c:/temp/temp.eps") 14 | """ 15 | g_len = len(group) 16 | subplot_size = (figwidth - (g_len-1)*hsep)/g_len 17 | c = pyx.canvas.canvas() 18 | g_id = range(g_len) 19 | xlinks = [] 20 | for yi in g_id[::-1]: 21 | for xi in g_id: 22 | xseries = group[xi] 23 | yseries = group[yi] 24 | if xi == 0: 25 | ylinkaxis = None 26 | else: 27 | ylinkaxis = pyx.graph.axis.linkedaxis(ylink.axes["y"]) 28 | if yi == g_len-1: 29 | xlinkaxis = None 30 | else: 31 | xlinkaxis = pyx.graph.axis.linkedaxis(xlinks[xi].axes["x"]) 32 | newgraph = c.insert(pyx.graph.graphxy(width=subplot_size, height=subplot_size, 33 | xpos=(subplot_size+hsep)*xi, 34 | ypos=(subplot_size+vsep)*(g_len-1-yi), 35 | x = (xlinkaxis or pyx.graph.axis.linear()), 36 | y = (ylinkaxis or pyx.graph.axis.linear()), 37 | ) 38 | ) 39 | newgraph.plot(pyx.graph.data.points(zip(xseries,yseries), x=1, y=2)) 40 | if xi == 0: 41 | ylink = newgraph 42 | if yi == g_len -1: 43 | xlinks.append( newgraph ) 44 | return c 45 | 46 | -------------------------------------------------------------------------------- /pytrix/__init__.py: -------------------------------------------------------------------------------- 1 | '''Econometric and Other Economics Related Utilities for Python 2 | 3 | Please contribute to this archive of econometrics related code for Python. 4 | 5 | :see: `pyTrix homepage`_. 6 | :contact: alan DOT isaac AT gmail DOT com 7 | :note: documentation generation as 8 | c:\\Python24\\Lib\\site-packages\\epydoc\\cli.py -o pytrix/doc --docformat=restructuredtext --html pytrix 9 | 10 | .. _`pyTrix homepage`: http://econpy.googlecode.com/svn/trunk/pytrix/pytrix.xhtml 11 | .. _`MIT license`: http://www.opensource.org/licenses/mit-license.php 12 | ''' 13 | __docformat__ = "restructuredtext en" 14 | 15 | -------------------------------------------------------------------------------- /pytrix/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/pytrix/__init__.pyc -------------------------------------------------------------------------------- /pytrix/fmath.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Provides a couple useful floating point math operations, 3 | primarily `feq` (fuzzy equality). 4 | 5 | :see: http://orion.math.iastate.edu/burkardt/c_src/machar/machar.html 6 | ''' 7 | from __future__ import absolute_import 8 | import math 9 | 10 | 11 | ## radix 12 | float_radix = 0 13 | 14 | def calc_float_radix(): 15 | '''Return: floating point radix. (Usually 2.) 16 | ''' 17 | float_radix = 0 18 | a = 1.0 19 | test = True 20 | while test: 21 | a += a 22 | temp1 = a + 1.0 23 | temp2 = temp1 - a 24 | test = (temp2 - 1.0 != 0.0) 25 | b = 1.0 26 | while float_radix == 0: 27 | b += b 28 | temp1 = a + b 29 | float_radix = int(temp1 - a) 30 | return float_radix 31 | 32 | def get_float_radix(): 33 | global float_radix 34 | if float_radix == 0: 35 | float_radix = calc_float_radix() 36 | return float_radix 37 | 38 | ## machine precision 39 | machine_precision = 0.0 40 | 41 | def calc_machine_precision(): 42 | '''Return: machine_precision (float) 43 | ''' 44 | float_radix = get_float_radix() 45 | inverse_radix = 1.0/float_radix 46 | machine_precision = 1.0 47 | temp = 1.0 + machine_precision 48 | while (temp - 1.0 != 0.0): 49 | machine_precision *= inverse_radix 50 | temp = 1.0 + machine_precision 51 | return machine_precision 52 | 53 | def get_machine_precision(): 54 | global machine_precision 55 | if machine_precision == 0: 56 | machine_precision = calc_machine_precision() 57 | return machine_precision 58 | 59 | ## default_numerical_precision 60 | default_numerical_precision = 0.0 61 | 62 | def get_default_numerical_precision(): 63 | global default_numerical_precision 64 | if default_numerical_precision == 0: 65 | default_numerical_precision = math.sqrt(get_machine_precision()) 66 | return default_numerical_precision 67 | 68 | 69 | def feq(a, b, precision=get_default_numerical_precision()): 70 | '''Return: bool 71 | Fuzzy equality comparison for floats. 72 | ''' 73 | inf_norm = max(abs(a), abs(b)) 74 | return (inf_norm < precision) or (abs(a-b) < precision * inf_norm) 75 | 76 | -------------------------------------------------------------------------------- /pytrix/fmath.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/pytrix/fmath.pyc -------------------------------------------------------------------------------- /pytrix/opendatabank.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/pytrix/opendatabank.txt -------------------------------------------------------------------------------- /pytrix/principal_components.py: -------------------------------------------------------------------------------- 1 | import numpy as N 2 | 3 | #%%%%%%%%%%%%%%%%%%%%%%%%%%% Tomic code %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 4 | class PCA: 5 | def __init__(self, inputMatrix, meancenter): 6 | """ 7 | This class carries out Principal Component Analysis on (numeric/numarray) 8 | matrices. 9 | 10 | use: 11 | analysis = PCA(Matrix, 0) / no mean centering of data 12 | analysis = PCA(Matrix, 1) / mean centering of data 13 | 14 | Matrix: array from package 'numeric'/'numarray' 15 | 16 | :author: Oliver Tomic 17 | :organization: Matforsk - Norwegian Food Research Institute 18 | :version: 1.0 19 | :since: 29.06.2005 20 | :see: Modular Data Toolkit for another implementation http://mdp-toolkit.sourceforge.net/ 21 | :see: prepca from matplotlib.mlab (simpler implementation) 22 | """ 23 | 24 | from numpy.lib.mlab import svd, std, cov 25 | [numberOfObjects, numberOfVariables] = shape(inputMatrix) 26 | 27 | # This creates a matrix that keeps the original input matrix. That is 28 | # necessary, since 'inputMatrix' will be centered in the process and 29 | # the function GetCorrelationLoadings requires the original values. 30 | self.originalMatrix = zeros((numberOfObjects, numberOfVariables), float32) 31 | for rows in range(numberOfObjects): 32 | for cols in range(numberOfVariables): 33 | self.originalMatrix[rows, cols] = inputMatrix[rows, cols] 34 | 35 | # Meancenter inputMatrix if required 36 | if meancenter == 1: 37 | 38 | variableMean = average(inputMatrix, 0) 39 | 40 | for row in range(0, numberOfObjects): 41 | inputMatrix[row] = inputMatrix[row] - variableMean 42 | 43 | 44 | # Do the single value decomposition 45 | [U,S_values,V_trans] = svd(inputMatrix) 46 | 47 | S = zeros((len(S_values),len(S_values)), float32) 48 | for singVal in range(len(S_values)): 49 | S[singVal][singVal] = S_values[singVal] 50 | 51 | # Calculate scores (T) and loadings (P) 52 | self.scores = U*S_values 53 | self.loadings = transpose(V_trans) 54 | 55 | self.inputMatrix = inputMatrix 56 | 57 | def GetScores(self): 58 | """ 59 | Returns the score matrix T. First column is PC1, second is PC2, etc. 60 | """ 61 | return self.scores 62 | 63 | def GetLoadings(self): 64 | """ 65 | Returns the loading matrix P. First row is PC1, second is PC2, etc. 66 | """ 67 | return self.loadings 68 | 69 | def GetCorrelationLoadings(self): 70 | """ 71 | Returns the correlation loadings matrix based on T and inputMatrix. 72 | For variables in inputMatrix with std = 0, the value 0 is written 73 | in the correlation loadings matrix instead of 'Nan' as it should be 74 | (as for example in Matlab) 75 | """ 76 | 77 | # Creates empty matrix for correlation loadings 78 | self.correlationLoadings = zeros((shape(self.scores)[1], shape(self.originalMatrix)[1]), float32) 79 | 80 | # Calculates correlation loadings with formula: 81 | # correlation = cov(x,y)/(std(x)*std(y)) 82 | 83 | # For each PC in score matrix 84 | for PC in range(shape(self.scores)[1]): 85 | PCscores = self.scores[:, PC] 86 | PCscoresSTD = std(PCscores) 87 | 88 | # For each variable/attribute in original matrix (not meancentered) 89 | for var in range(shape(self.originalMatrix)[1]): 90 | origVar = self.originalMatrix[:, var] 91 | origVarSTD = std(origVar) 92 | 93 | # If std = 0 for any variable an OverflowError occurs. 94 | # In such a case the value 0 is written in the matrix 95 | try: 96 | self.correlationLoadings[PC, var] = cov(PCscores, origVar) / (PCscoresSTD * origVarSTD) 97 | 98 | except OverflowError: 99 | self.correlationLoadings[PC, var] = 0 100 | 101 | return self.correlationLoadings 102 | 103 | 104 | 105 | 106 | 107 | #%%%%%%%%%%%%%%%%%%%%%%%%%%% Pincus code %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 108 | def pca(data, algorithm='eig'): 109 | """pca(data) -> mean, pcs, norm_pcs, variances, positions, norm_positions 110 | Perform Principal Components Analysis on a set of n data points in k 111 | dimensions. The data array must be of shape (n, k). 112 | This function returns the mean data point, the principal components (of 113 | shape (p, k), where p is the number pf principal components: p=min(n,k)), 114 | the normalized principal components, where each component is normalized by 115 | the data's standard deviation along that component (shape (p, k)), the 116 | variance each component represents (shape (p,)), the position of each data 117 | point along each component (shape (n, p)), and the position of each data 118 | point along each normalized component (shape (n, p)). 119 | 120 | The optional algorithm parameter can be either 'svd' to perform PCA with 121 | the singular value decomposition, or 'eig' to use a symmetric eigenvalue 122 | decomposition. Empirically, eig is faster on the datasets I have tested. 123 | 124 | :license: public domain 125 | :author: Zachary Pincus 126 | """ 127 | 128 | data = N.asarray(data) 129 | mean = data.mean(axis = 0) 130 | centered = data - mean 131 | if algorithm=='eig': 132 | pcs, variances, stds, positions, norm_positions = _pca_eig(centered) 133 | elif algorithm=='svd': 134 | pcs, variances, stds, positions, norm_positions = _pca_svd(centered) 135 | else: 136 | raise RuntimeError('Algorithm %s not known.'%algorithm) 137 | norm_pcs = pcs * stds[:, N.newaxis] 138 | return mean, pcs, norm_pcs, variances, positions, norm_positions 139 | 140 | def _pca_svd(data): 141 | u, s, vt = N.linalg.svd(data, full_matrices = 0) 142 | pcs = vt 143 | v = N.transpose(vt) 144 | data_count = len(flat) 145 | variances = s**2 / data_count 146 | root_data_count = N.sqrt(data_count) 147 | stds = s / root_data_count 148 | positions = u * s 149 | norm_positions = u * root_data_count 150 | return pcs, variances, stds, positions, norm_positions 151 | 152 | def _pca_eig(data): 153 | values, vectors = _symm_eig(data) 154 | pcs = vectors.transpose() 155 | variances = values / len(flat) 156 | stds = N.sqrt(variances) 157 | positions = N.dot(flat, vectors) 158 | err = N.seterr(divide='ignore', invalid='ignore') 159 | norm_positions = positions / stds 160 | N.seterr(**err) 161 | norm_positions[~N.isfinite(norm_positions)] = 0 162 | return pcs, variances, stds, positions, norm_positions 163 | 164 | def _symm_eig(a): 165 | """Return the eigenvectors and eigenvalues of the symmetric matrix a'a. If 166 | a has more columns than rows, then that matrix will be rank-deficient, 167 | and the non-zero eigenvalues and eigenvectors can be more easily extracted 168 | from the matrix aa'. 169 | From the properties of the SVD: 170 | if a of shape (m,n) has SVD u*s*v', then: 171 | a'a = v*s's*v' 172 | aa' = u*ss'*u' 173 | let s_hat, an array of shape (m,n), be such that s * s_hat = I(m,m) 174 | and s_hat * s = I(n,n). (Note that s_hat is just the elementwise 175 | reciprocal of s, as s is zero except on the main diagonal.) 176 | 177 | Thus, we can solve for u or v in terms of the other: 178 | v = a'*u*s_hat' 179 | u = a*v*s_hat 180 | """ 181 | m, n = a.shape 182 | if m >= n: 183 | # just return the eigenvalues and eigenvectors of a'a 184 | vecs, vals = _eigh(N.dot(a.transpose(), a)) 185 | vecs = N.where(vecs < 0, 0, vecs) 186 | return vecs, vals 187 | else: 188 | # figure out the eigenvalues and vectors based on aa', which is smaller 189 | sst_diag, u = _eigh(N.dot(a, a.transpose())) 190 | # in case due to numerical instabilities we have sst_diag < 0 anywhere, 191 | # peg them to zero 192 | sst_diag = N.where(sst_diag < 0, 0, sst_diag) 193 | # now get the inverse square root of the diagonal, which will form the 194 | # main diagonal of s_hat 195 | err = N.seterr(divide='ignore', invalid='ignore') 196 | s_hat_diag = 1/N.sqrt(sst_diag) 197 | N.seterr(**err) 198 | s_hat_diag[~N.isfinite(s_hat_diag)] = 0 199 | # s_hat_diag is a list of length m, a'u is (n,m), so we can just use 200 | # numpy's broadcasting instead of matrix multiplication, and only create 201 | # the upper mxm block of a'u, since that's all we'll use anyway... 202 | v = N.dot(a.transpose(), u[:,:m]) * s_hat_diag 203 | return sst_diag, v 204 | 205 | def _eigh(m): 206 | values, vectors = N.linalg.eigh(m) 207 | order = N.flipud(values.argsort()) 208 | return values[order], vectors[:,order] 209 | 210 | -------------------------------------------------------------------------------- /pytrix/pwt.py: -------------------------------------------------------------------------------- 1 | """Provides a simple class to extract data from the 2 | Penn World Tables, which must be available in CSV format. 3 | (E.g., download the Excel file from http://pwt.econ.upenn.edu/, 4 | open it, and save as CSV.) 5 | """ 6 | import csv 7 | 8 | class DataSet(object): 9 | """Creates a dataset from the PWT (input as a CSV file). 10 | A data set is a collection of countries, 11 | where each country maps year(s) to the requested variable values 12 | (in the order requested). 13 | :requires: Python 2.6+ (tuples don't have an index method until 2.6) 14 | """ 15 | def __init__(self, pwt_csv, country_names=None, years=None, vnames=None): 16 | self.country_names = country_names 17 | self._countries = list() 18 | self.years = years 19 | self.vnames = vnames 20 | names2countries = dict() #temporary variable to help data set construction 21 | with open(pwt_csv, "rb") as fh: 22 | reader = csv.reader(fh) 23 | headers = list( h.strip() for h in next(reader) ) 24 | nitems = len(headers) 25 | vars_idx = tuple( headers.index(vname) for vname in vnames ) 26 | name_idx = headers.index('country') 27 | try: 28 | iso_idx = headers.index('isocode') 29 | except ValueError: #must be an older PWT 30 | iso_idx = headers.index('country isocode') 31 | year_idx = headers.index('year') 32 | for line in reader: 33 | assert len(line)==nitems 34 | name = line[name_idx].strip() 35 | iso = line[iso_idx].strip() 36 | year = int( line[year_idx] ) 37 | cond1 = years is None or year in years 38 | cond2 = country_names is None or name in country_names 39 | if cond1 and cond2: 40 | data = tuple( line[i] for i in vars_idx ) 41 | if ('' not in data) and ('na' not in data): #use complete records only 42 | #add country to data set (if needed) 43 | country = names2countries.setdefault(name, Country(name, iso, self) ) 44 | # add year to country's data 45 | country[year] = map(float, data) 46 | else: 47 | print "%s %d discarded (missing data)"%(name,year) 48 | self._countries = list( names2countries.values() ) 49 | def get_iso(self, alpha3): 50 | """Get country by ISO 3166-1 alpha-3 (three letter) 51 | country code. 52 | """ 53 | if len(alpha3) != 3: 54 | raise ValueError('See http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3') 55 | for ctry in self.countries: 56 | if ctry.alpha3 == alpha3: 57 | return ctry 58 | raise ValueError('ISO code {0} not available.'.format(alpha3)) 59 | def get_index(self, vname): 60 | return self.vnames.index(vname) 61 | @property 62 | def countries(self): 63 | return self._countries 64 | 65 | 66 | class Country(dict): 67 | """Provides individual country data storage, 68 | mapping year(s) to requested variable values 69 | (in the order requested at dataset construction). 70 | """ 71 | def __init__(self, name, alpha3, dataset=None): 72 | dict.__init__(self) 73 | self.name = name 74 | self.alpha3 = alpha3 75 | self.dataset = dataset 76 | """ 77 | self.rgdpwok = dict() 78 | self.rgdpch = dict() 79 | self.POP = dict() 80 | self.y = dict() 81 | """ 82 | def __str__(self): # chk wise?? 83 | return "%s (%s)"%(self.name,self.alpha3) 84 | def get_observation(self, year, vname): 85 | data = self[year] 86 | vname_idx = self.dataset.get_index(vname) 87 | return self[year][vname_idx] 88 | @property 89 | def vnames(self): 90 | return self.dataset.vnames 91 | 92 | -------------------------------------------------------------------------------- /pytrix/utilities.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/pytrix/utilities.pyc -------------------------------------------------------------------------------- /scripts/scripts_config.py: -------------------------------------------------------------------------------- 1 | try: 2 | import econpy 3 | except ImportError: 4 | import os, sys 5 | package4tests = os.path.abspath(__file__) 6 | for _ in range(3): 7 | package4tests = os.path.split(package4tests)[0] 8 | sys.path.insert(0,package4tests) #need location of econpy 9 | import econpy 10 | 11 | import logging 12 | logging.basicConfig(level=logging.INFO,format='%(levelname)-10s %(message)s') 13 | script_logger = logging.getLogger('script_logger') 14 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /tests/simplest.py: -------------------------------------------------------------------------------- 1 | #BEGIN orderedpartitions 2 | def ordered_partitions(n, nparts): 3 | result = list() 4 | if (nparts == 1): 5 | result.append([n]) 6 | else: 7 | for n1 in range(n+1): 8 | for rest in ordered_partitions(n-n1, nparts-1): 9 | result.append([n1] + rest) 10 | return result 11 | #END orderedpartitions 12 | 13 | 14 | # vim: set noet:ts=4:sw=4 15 | -------------------------------------------------------------------------------- /tests/test_abm.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for the `abs` package. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import division, absolute_import 9 | __docformat__ = "restructuredtext en" 10 | 11 | import random, unittest 12 | import numpy as np 13 | 14 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 15 | from econpy.pytrix.utilities import calc_gini, calc_gini2 16 | from econpy.abm import utilities 17 | from econpy.abm.pestieau1984oep import agents #chk 18 | 19 | class test_utilities(unittest.TestCase): 20 | wealths = [random.random() for _ in range(30)] 21 | indivs = [agents.PestieauIndiv(sex=x) for x in "MF"*15] 22 | def test_match_exclude(self): 23 | f = lambda x,y: x==y #exclude if equal 24 | g1 = [1,2] 25 | g2 = [1,2,1] 26 | pairs = utilities.match_exclude(g1,g2,f) 27 | pairs.sort() 28 | self.assert_( pairs == [(1,2),(2,1)] ) 29 | def testGini(self): #TODO: move this 30 | gini1 = calc_gini(self.wealths) 31 | gini2 = calc_gini2(self.wealths) 32 | print "gini1:%f, gini2:%f"%(gini1, gini2) 33 | self.assert_( abs(gini1-gini2)<1e-8 ) 34 | def test_gini2shares(self): 35 | nshares = 30 36 | test_gini = random.random() 37 | shares = list( utilities.gini2sharesPower(test_gini, 30) ) 38 | shares02 = np.diff( np.linspace(0, 1, nshares+1)**((1+test_gini)/(1-test_gini)) ) 39 | self.assertTrue(np.allclose(shares, shares02)) 40 | shares_gini = calc_gini(share*100 for share in shares) 41 | #print test_gini, shares_gini 42 | #TODO: improve accuracy 43 | self.assert_( abs(test_gini - shares_gini ) < 1e-02 ) 44 | 45 | 46 | 47 | 48 | if __name__=="__main__": 49 | unittest.main() 50 | 51 | 52 | # vim: set noet:ts=4:sw=4 53 | -------------------------------------------------------------------------------- /tests/test_functions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for the `functions` package. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | __docformat__ = "restructuredtext en" 9 | from typing import Any, Callable, Sequence 10 | from numbers import Real, Integral 11 | import operator 12 | from functools import reduce 13 | 14 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 15 | import unittest 16 | import random 17 | import numpy 18 | #from econpy.functions import polyuv 19 | from typing import Callable 20 | Function = Callable 21 | from numbers import Real, Integral 22 | 23 | #BEGIN:function.differenceQuotient 24 | def simplest_differenceQuotient( 25 | f: Function, #underlying function 26 | x: Real, #source point 27 | h: Real #step 28 | ) -> Real: 29 | df = f(x + h) - f(x) #change of value of f 30 | return df / h #value of difference quotient 31 | #END:function.differenceQuotient 32 | 33 | #BEGIN:function.simplest_horner 34 | #goal: evaluate polynomial at point x 35 | #input: 36 | # coefficients : tuple (ordered as (a_0,...,a_N)) 37 | # x : number (point of evaluation) 38 | #output: 39 | # result : number (value of polynomial at x) 40 | def simplest_horner(coefficients, x): 41 | result = 0 42 | for coef in reversed(coefficients): 43 | result = coef + result * x 44 | return result 45 | #END:function.simplest_horner 46 | 47 | #BEGIN:simplest_hornerd 48 | #goal: evaluate polynomial p and derivative p' at point x 49 | #input: 50 | # coefficients : tuple (ordered as (a_0,...,a_N)) 51 | # x : number (point of evaluation) 52 | #output: 53 | # result : number,number = p(x), p'(x) 54 | def hornerd(coefficients, x): 55 | p0 = 0 56 | p1 = 0 57 | for coef in reversed(coefficients): 58 | p1 = p1*x + p0 59 | p0 = p0*x + coef 60 | return p0, p1 61 | #END:simplest_hornerd 62 | 63 | #BEGIN:horner 64 | def horner(coefficients: Sequence[float], x: float): 65 | f = lambda acc, coef: coef + x * acc 66 | return reduce(f, reversed(coefficients), 0) 67 | #END:horner 68 | 69 | class test_functions(unittest.TestCase): 70 | coefficients = random.sample(range(1,20), 5) 71 | coefs = [1.0, 0.2, 1.0, -0.4] 72 | """ 73 | def test_polyderiv(self): 74 | a = self.coefficients 75 | b = [ (i+1)*a[i+1] for i in range(len(a)-1) ] 76 | self.assertEqual(b, polyuv.polyderiv(a)) 77 | c = [ (i+1)*b[i+1] for i in range(len(b)-1) ] 78 | self.assertEqual(c, polyuv.polyderiv(b)) 79 | self.assertEqual(c, polyuv.polyderiv(a,d=2)) 80 | """ 81 | def test_horner(self): 82 | cs = self.coefficients 83 | cs1 = [ (i+1)*cs[i+1] for i in range(len(cs)-1) ] 84 | cs2 = [ (i+1)*cs1[i+1] for i in range(len(cs1)-1) ] 85 | x = random.random() 86 | ref0 = simplest_horner(cs, x) 87 | ref1 = simplest_horner(cs1,x) 88 | ref2 = simplest_horner(cs2,x) 89 | self.assertEqual(ref0, horner(cs, x) ) 90 | self.assertEqual(ref0, hornerd(cs, x)[0] ) 91 | self.assertAlmostEqual(ref1, hornerd(cs, x)[1] ) 92 | 93 | """ 94 | def test_PolynomailUV(self): 95 | p1 = polyuv.PolynomialUV(self.coefs) 96 | x = -1.9 97 | self.assertEqual( p1(x), ((-0.4*x + 1.0)*x + 0.2)*x + 1.0 ) 98 | def test_deriv(self): 99 | coefs = range(6) 100 | random.shuffle(coefs) 101 | p = numpy.poly1d(list(reversed(coefs))) 102 | for n in range(len(coefs)): 103 | self.assertEqual(polyuv.polyderiv(coefs, n), list(p.deriv(m=n).c)[::-1] ) 104 | """ 105 | def test_differenceQuotient(self): 106 | f = lambda x: x * x 107 | x0 = 2 108 | h = 1 109 | df = f(x0+h) - f(x0) 110 | self.assertEqual(5, simplest_differenceQuotient(f,x0,h)) 111 | 112 | ''' 113 | zeros = p1.zeros() 114 | for z in zeros: 115 | print z, p1(z) 116 | p2 = Polynomial([[1.,0.3],[-0.2,0.5]]) 117 | y = 0.3 118 | print p2(x,y), 1. + 0.3*y - 0.2*x + 0.5*x*y 119 | fit = fitPolynomial(2, [1.,2.,3.,4.], [2.,4.,8.,14.]) 120 | print fit.coeff 121 | 122 | p = Polynomial([1., 1.]) 123 | invp = 1./p 124 | pr = RationalFunction(p) 125 | print pr+invp 126 | ''' 127 | 128 | 129 | 130 | if __name__=="__main__": 131 | unittest.main() 132 | 133 | # vim: set expandtab:ts=4:sw=4 134 | -------------------------------------------------------------------------------- /tests/test_iterate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for the `iterate` module. 3 | :requires: Python 3.5+ 4 | 5 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 6 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 7 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 8 | ''' 9 | import random 10 | from math import sqrt, exp 11 | from typing import Callable 12 | from numbers import Real, Integral 13 | 14 | __docformat__ = "restructuredtext en" 15 | __author__ = 'Alan G. Isaac (and others as specified)' 16 | 17 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 18 | import unittest 19 | import math, random 20 | from econpy.pytrix import utilities, fmath 21 | from econpy.optimize import iterate 22 | 23 | 24 | #BEGIN:optimize.bracket; 25 | def simplest_bracket( 26 | f : Callable, #float->float (continuous function) 27 | xa : float, #interval lower bound 28 | xb : float, #interval upper bound 29 | nextpoint : Callable, #(float,float,float,float)->(float,float) 30 | reiter : Callable, #(float,float,float,float,int)->bool 31 | ) -> float: #x in (xa .. xb) s.t. f(x) approx 0 32 | fa, fb = f(xa), f(xb) 33 | ct = 0 34 | while reiter(xa, xb, fa, fb, ct): 35 | xnew = nextpoint(xa, xb, fa, fb) 36 | fnew = f(xnew) 37 | if(fnew * fa > 0):#then 38 | xa, fa = xnew, fnew 39 | else: 40 | xb, fb = xnew, fnew 41 | ct = ct + 1 42 | return xa if(abs(fa) < abs(fb)) else xb 43 | #END:optimize.bracket; 44 | 45 | #simplest implementation of bisection 46 | #BEGIN:optimize.bisect; 47 | def xmid(xa, xb, fa, fb): 48 | return (xa + xb) / 2.0 49 | #END:optimize.bisect; 50 | 51 | #BEGIN:optimize.ftol; 52 | def simplest_ftol(xa, xb, fa, fb, itr): 53 | ftol = 1e-9 54 | return (abs(fa) > ftol) and (abs(fb) > ftol) 55 | #END:optimize.ftol; 56 | 57 | #goal: find root by bisection 58 | #BEGIN:optimize.bisection; 59 | def simplest_bisection(f, xa, xb): 60 | return simplest_bracket( 61 | f, xa, xb, 62 | nextpoint=xmid, 63 | reiter=simplest_ftol) 64 | #END:optimize.bisection; 65 | 66 | def simplest_randomsection(f, xa, xb): 67 | return simplest_bracket( 68 | f, xa, xb, 69 | nextpoint=lambda xa, xb, fa, fb: xa + (xb-xa)*random.random(), 70 | reiter=simplest_ftol) 71 | 72 | 73 | #simplest implementation of regula falsi 74 | #BEGIN:optimize.falsi; 75 | def xfalse(xa, xb, fa, fb): 76 | lam = fb / (fb - fa) 77 | return lam * xa + (1 - lam) * xb 78 | 79 | def simplest_falseposition(f, xa, xb): 80 | return simplest_bracket( 81 | f, xa, xb, 82 | nextpoint=xfalse, 83 | reiter=simplest_ftol) 84 | #END:optimize.falsi; 85 | 86 | def simplest_falseposition_old(f, x1, x2): 87 | #comment: set small number for convergence test 88 | eps = 1e-8 89 | f1, f2 = f(x1), f(x2) 90 | if f1*f2 > 0: 91 | raise ValueError("Sign changing interval required.") 92 | xnew, fnew = x2, f2 93 | while abs(fnew) > eps: 94 | #compute: x such that f(x) is near 0 95 | lam = f2 / (f2 - f1) 96 | xnew = lam*x1 + (1-lam)*x2 97 | fnew = f(xnew) 98 | if fnew*f1 > 0: 99 | x1, f1 = xnew, fnew 100 | else: 101 | x2, f2 = xnew, fnew 102 | return xnew 103 | 104 | #simplest implementation of Ridders' method 105 | # comment: does not test midpt (natural extension) 106 | #BEGIN lst:optimize.ridders 107 | def simplest_ridders(f, x1, x2): 108 | #comment: set small number for convergence test 109 | eps = 1e-8 110 | f1, f2 = f(x1), f(x2) 111 | #require: sign change over initial interval 112 | if f1*f2 > 0: 113 | raise ValueError("Sign changing interval required.") 114 | xnew, fnew = (x2, f2) if (abs(f2) eps: 116 | #compute: x such that f(x) is near 0 117 | xmid = (x1 + x2)/2. 118 | fmid = f(xmid) 119 | xnew = xmid - (x2-xmid)*fmid/sqrt(fmid*fmid-f1*f2) 120 | fnew = f(xnew) 121 | if fnew*f1 > 0: 122 | x1, f1 = xnew, fnew 123 | else: 124 | x2, f2 = xnew, fnew 125 | return xnew 126 | #END lst:optimize.ridders 127 | 128 | 129 | 130 | 131 | #Return: `p` approximate fixed point, `pseq` approximating sequence 132 | def smallchange(p1,p2,eps=1e-6,tol=1e-6): 133 | abs_change = abs(p1 - p2) 134 | rel_change = abs_change/(abs(p2)+eps) 135 | return min(abs_change,rel_change) Real: #comment: the approximate fixed point 143 | p_1, p = p, fn(p) 144 | while (not smallchange(p_1,p)): 145 | p_1, p = p, fn(p) 146 | return p 147 | #END:sequence.picard1; 148 | def old_simplest_picard(fn : Callable, p : Real) -> Real: 149 | while True: 150 | p_1, p = p, fn(p) 151 | if smallchange(p_1,p): 152 | return p 153 | 154 | def simple_picard(fn, p, itermax): 155 | for iternum in range(itermax): 156 | p_1, p = p, fn(p) 157 | if smallchange(p_1,p): 158 | return p 159 | print("Warning: convergence failed; maximum iteration reached.") 160 | 161 | 162 | 163 | 164 | # cx:sequence.picard2 class Picard 165 | 166 | class Iterator4Test(iterate.IterativeProcess): 167 | def iterate(self): 168 | pass 169 | def get_testval(self): 170 | return 1 171 | 172 | 173 | class test_iter(unittest.TestCase): 174 | def test_IterativeProcess(self): 175 | N = random.randrange(100) 176 | crit = lambda x, value, iteration: x.iteration >= N 177 | ip = Iterator4Test(crit) 178 | ip.run() 179 | self.assertEqual(ip.iteration,N) 180 | ip = Iterator4Test(None) 181 | ip.run() 182 | self.assertEqual(ip.iteration,100) 183 | def test_bisect(self): 184 | print("""START TEST""") 185 | x4zero = random.randrange(20) 186 | f = lambda x: (x-x4zero)**3 187 | crit = iterate.AbsDiff(1e-9) 188 | b1 = iterate.Bisect(f, x4zero - 1.0, x4zero+1.0, crit) 189 | b1.run() 190 | #print b1.report() 191 | result1 = b1.value 192 | result2 = iterate.bisect(f, x4zero - 1.0, x4zero+1.0, eps=1e-9) 193 | result3 = simplest_bisection(f, x4zero - 1.0, x4zero+1.0) 194 | print("testvals", b1.value) 195 | print("simple bisect", result2) 196 | print("simplest bisection", result3) 197 | self.assertTrue(fmath.feq(b1.value, x4zero, 1e-8)) 198 | self.assertTrue(fmath.feq(result2, x4zero, 1e-8)) 199 | self.assertTrue(fmath.feq(result3, x4zero, 1e-7)) 200 | def test_falsi(self): 201 | x4zero = random.randrange(20) 202 | f = lambda x: (x-x4zero)**3 203 | result1 = simplest_falseposition(f, x4zero - 1.0, x4zero+1.0) 204 | print("testvals", result1) 205 | self.assertTrue(fmath.feq(result1, x4zero, 1e-8)) 206 | def test_ridders(self): 207 | shift = random.randrange(20) 208 | f = lambda x: x*exp(x) - shift 209 | testval = simplest_bisection(f, -10., 10.) 210 | result1 = simplest_ridders(f, -10., 10.) 211 | print("Ridders method with shift=%f"%shift) 212 | print("testvals", result1) 213 | self.assertTrue(fmath.feq(result1, testval, 1e-8)) 214 | def test_picard(self): 215 | f1 = lambda x: 0.5*(x+2/x) #approx sqrt of 2 216 | self.assertTrue(fmath.feq(iterate.Picard(f1, 1, 100, tol=1e-6).fp,math.sqrt(2),1e-6)) 217 | f2 =lambda x: math.exp(-x) 218 | best_result = iterate.Picard(f2, 1, 100, tol=1e-6).fp #must match tolerance... 219 | result1 = simplest_picard(f2, 1) 220 | result2 = simple_picard(f2, 1, 100) 221 | result3 = old_simplest_picard(f2, 1) 222 | self.assertTrue(fmath.feq(result1, best_result, 1e-6)) 223 | self.assertTrue(fmath.feq(result2, best_result, 1e-6)) 224 | self.assertTrue(fmath.feq(result3, best_result, 1e-6)) 225 | self.assertEqual(result3, result1) 226 | #picard(lambda x: -x,1,100) 227 | 228 | if __name__=="__main__": 229 | unittest.main() 230 | #print(simplest_randomsection(lambda x: x*x*x, -10, 1)) 231 | 232 | 233 | # vim: set noet:ts=4:sw=4 234 | -------------------------------------------------------------------------------- /tests/test_ls.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for ls.py. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | from __future__ import division 10 | 11 | __docformat__ = "restructuredtext en" 12 | __author__ = 'Alan G. Isaac (and others as specified)' 13 | 14 | from itertools import izip 15 | import random 16 | import numpy as np 17 | import numpy.linalg as la 18 | import unittest 19 | 20 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 21 | from econpy.pytrix.pytrix import Vector, Vplus, dot, norm 22 | from econpy.pytrix.ls import rolsf, OLS 23 | 24 | 25 | class testPytrix(unittest.TestCase): 26 | def test_ols(self): 27 | b0 = random.randint(1,10) 28 | b1 = random.randint(1,10) 29 | x = np.random.random((1000,1)) 30 | e = np.random.random((1000,1)) * 0.1 31 | y = b0 + b1*x + e 32 | model = OLS(dep=y, indep=x) 33 | b1hat, b0hat = model.coefs #constant comes last 34 | self.assert_(abs(b1hat-b1)<0.1) 35 | self.assert_(abs(b0hat-b0)<0.1) 36 | 37 | # +++++++++++++++++++++++++++++++++++++++++++ 38 | # rolsftest.py 39 | # :author: j. c. hassler 40 | # 12-feb-95 41 | # Originally written in Matlab. Translated to Python 2-oct-07. 42 | # This is a simple driver program to test recursive OLS with a 43 | # forgetting factor, rolsf. The process is an ARMA model driven by 44 | # a random input. The parameters are estimated by ROLSF. 45 | # 46 | # ------------------------------------------ 47 | 48 | tht = [-.50, .25, 1., .25] # true parameters 49 | p = 1000.* np.eye(4) # initialize covariance matrix 50 | # large values because we have very low confidence in the initial guess. 51 | th = [0., 0., 0., 0.] # initial guesses at parameters 52 | lam = 0.95 # forgetting factor 53 | xt = [0., 0., 0., 0.] # other initial values 54 | x = [0., 0., 0., 0.] 55 | a = np.zeros(200,float) 56 | b = np.zeros(200,float) 57 | indx = np.zeros(200,int) 58 | for i in range(200): 59 | if i>100: # change one of the parameters 60 | tht[0] = -.40 # .. on the fly. 61 | # the point of the forgetting factor is to make the estimator responsive 62 | # to such changes. 63 | e = 0.02*(.5 - random.random()) # random 'noise' 64 | u = 1.*(.5 - random.random()) # random forcing function 65 | yt = np.inner(xt,tht) # truth model 66 | 67 | xt[1] = xt[0] # stuff in the new truth-value-y ... 68 | xt[0] = yt # ... and new input 69 | xt[3] = xt[2] 70 | xt[2] = u 71 | y = yt + e # add 'measurement noise' to the true value 72 | th,p = rolsf(x,y,p,th,lam) # call recursive OLS with FF 73 | x[1] = x[0] # stuff in the new y ... 74 | x[0] = y # ... and new input to the design model 75 | x[3] = x[2] 76 | x[2] = u 77 | a[i] = th[0] # save for later plotting 78 | b[i] = th[1] 79 | indx[i] = i 80 | 81 | ''' 82 | import matplotlib.pyplot as plt 83 | plt.plot(indx,a,indx,b) 84 | plt.grid() 85 | plt.show() 86 | ''' 87 | 88 | if __name__=="__main__": 89 | unittest.main() 90 | 91 | -------------------------------------------------------------------------------- /tests/test_pestieau.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for Pestieau replication. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | import unittest 10 | import random 11 | 12 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 13 | from econpy.abs.pestieau1984oep import agents 14 | from econpy.pytrix import utilities, iterate, fmath 15 | 16 | 17 | 18 | class testPestieau(unittest.TestCase): 19 | def setUp(self): 20 | self.N = 5 21 | self.wealths = [random.random() for _ in range(2*self.N)] 22 | self.indivs = [agents.PestieauIndiv(sex=x) for x in "MF"*self.N] 23 | ''' 24 | def test_match_exclude(self): 25 | males = self.indivs[:2] 26 | females = self.indivs[-2:] 27 | for i in range(2): 28 | males[i].siblings.add(females[i]) 29 | females[i].siblings.add(males[i]) 30 | mf = blindermodel.match_exclude(males,females, lambda x,y: x in y.siblings) 31 | self.assertEqual(mf , [(males[0],females[1]),(males[1],females[0])] ) 32 | def test_match_exclude2(self): 33 | g1 = range(5) 34 | g2 = range(5) 35 | random.shuffle(g2) 36 | mf = blindermodel.match_exclude(g1,g2, lambda x,y: x != y) 37 | self.assertEqual(mf , [(0,0),(1,1),(2,2),(3,3),(4,4)] ) 38 | def test_random2sexer(self): 39 | s = blindermodel.random2sexer(10) 40 | for si in s: 41 | self.assert_(si in ['MM','MF','FM','FF']) 42 | ''' 43 | def test_ability(self): 44 | indiv = self.indivs[0] 45 | ability = agents.compute_ability_pestieau(indiv, 0.5, 2) 46 | #TODO 47 | def test_PestieauCohort(self): 48 | indivs = self.indivs 49 | cohort = agents.PestieauCohort(indivs) 50 | self.assertEqual(len(cohort),len(indivs)) 51 | for i in indivs: 52 | self.assert_(i.sex in "MF") 53 | def test_Fund(self): 54 | fund = agents.Fund(None) #usu want association w economy 55 | fund._accounts = [agents.FundAcct(fund, self.indivs[i], self.wealths[i]) for i in range(self.N)] 56 | for i in range(self.N): 57 | self.assertEqual(fund._accounts[i]._value, self.wealths[i]) 58 | 59 | if __name__=="__main__": 60 | unittest.main() 61 | 62 | -------------------------------------------------------------------------------- /tests/test_pytrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for pytrix. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | from __future__ import division 10 | 11 | __docformat__ = "restructuredtext en" 12 | __author__ = 'Alan G. Isaac (and others as specified)' 13 | 14 | import math, random, unittest 15 | from itertools import izip 16 | import numpy as np 17 | import numpy.linalg as la 18 | 19 | import simplest 20 | 21 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 22 | from econpy.pytrix.pytrix import Vector, Vplus, dot, norm, gcd_euclid 23 | from econpy.pytrix.pytrix import n_take_k, factorial 24 | from econpy.pytrix.pytrix import ordered_partitions, ordered_subpartitions 25 | from econpy.pytrix import fmath 26 | 27 | 28 | class testPytrix(unittest.TestCase): 29 | def setUp(self): 30 | self.list1 = range(3) 31 | self.list2 = [2, 4, 6] 32 | def test_norm(self): 33 | v1 = Vector(self.list1) 34 | n1 = np.fromiter(v1, int) 35 | p = random.choice([1,2,3]) 36 | self.assertEqual(v1.norm(p), la.norm(n1,p)) 37 | def test_dot(self): 38 | v1 = Vector(self.list1) 39 | v2 = Vector(self.list2) 40 | n1 = np.fromiter(v1, int) 41 | n2 = np.fromiter(v2, int) 42 | self.assertEqual(v1.dot(v2), np.dot(n1,n2)) 43 | def test_vector(self): 44 | v1 = Vector(self.list1) 45 | v2 = Vector(2*x for x in self.list1) 46 | self.assertEqual(2*v1, v2) 47 | n1 = np.fromiter(v1, int) 48 | n2 = np.fromiter(v2, int) 49 | self.assertEqual(v1.dot(v2), np.dot(n1,n2)) 50 | def test_vplus(self): 51 | v1 = Vplus(self.list2) #no zeros! 52 | v2 = Vplus(2*x for x in self.list2) 53 | self.assertEqual(2*v1, v2) 54 | mul1 = Vplus(x1*x2 for x1,x2 in izip(v1,v2)) 55 | self.assertEqual(v1 * v2, mul1) 56 | div1 = Vplus(x1/x2 for x1,x2 in izip(v1,v2)) 57 | self.assertEqual(v1 / v2, div1) 58 | def test_combinations(self): 59 | self.assertEqual(n_take_k(5,3), 10) 60 | self.assertEqual(n_take_k(10,3), 120) 61 | def test_gcd(self): 62 | self.assertEqual(8, gcd_euclid(8,16)) 63 | self.assertEqual(8, gcd_euclid(-8,16)) 64 | def test_factorial(self): 65 | n = random.randint(0,10) 66 | self.assertEqual(factorial(n), math.factorial(n)) 67 | def test_ordered_partitions(self): 68 | self.assertEqual(ordered_partitions(2,1),[[2]]) 69 | self.assertEqual(ordered_partitions(2,2),[[0,2],[1,1],[2,0]]) 70 | ap22 = map(tuple,ordered_subpartitions(2,2)) 71 | self.assertEqual(len(ap22),len(set(ap22))) 72 | self.assertEqual(ap22,[(0,0),(0,1),(1,0),(0,2),(1,1),(2,0)]) 73 | nbins = random.randint(1, 9) 74 | n = random.randint(1, 9) 75 | self.assertEqual(ordered_subpartitions(0,nbins),[[0]*nbins]) 76 | n = random.randint(1, 9) 77 | #the next test assumes both functions return in same order 78 | self.assertEqual(ordered_partitions(n,nbins), simplest.ordered_partitions(n,nbins)) 79 | self.assertEqual(len(ordered_partitions(3,5)), 35) 80 | 81 | 82 | ''' 83 | # tests for pnpoly 84 | from numpy.testing import NumpyTest, NumpyTestCase 85 | class test_poly(NumpyTestCase): 86 | def test_square(self): 87 | v = np.array([[0,0], [0,1], [1,1], [1,0]]) 88 | assert(pnpoly(v,[0.5,0.5])) 89 | assert(not pnpoly(v,[-0.1,0.1])) 90 | def test_triangle(self): 91 | v = np.array([[0,0], [1,0], [0.5,0.75]]) 92 | assert(pnpoly(v,[0.5,0.7])) 93 | assert(not pnpoly(v,[0.5,0.76])) 94 | assert(not pnpoly(v,[0.7,0.5])) 95 | ''' 96 | 97 | if __name__=="__main__": 98 | unittest.main() 99 | 100 | 101 | # vim: set expandtab:ts=4:sw=4 102 | -------------------------------------------------------------------------------- /tests/test_quadrature.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for the `quadrature` module. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import division 9 | from __future__ import absolute_import 10 | 11 | __docformat__ = "restructuredtext en" 12 | __author__ = 'Alan G. Isaac (and others as specified)' 13 | 14 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 15 | import unittest 16 | import math, random 17 | from econpy.pytrix import utilities, fmath 18 | from econpy.integrate import quadrature 19 | 20 | #TODO: add tests! 21 | # but here is a demo 22 | 23 | f = lambda x: (x-1)*(x-1) 24 | 25 | it = quadrature.IterativeTrapz(f, 0, 2, reportfreq=1) 26 | it.run() 27 | print it.report() 28 | -------------------------------------------------------------------------------- /tests/test_stat.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for the `pytrix.stat` module. 3 | 4 | :see: http://www.scipy.org/svn/numpy/trunk/numpy/core/tests/test_umath.py for numpy testing examples 5 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 6 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 7 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 8 | ''' 9 | from __future__ import division, absolute_import 10 | 11 | __docformat__ = "restructuredtext en" 12 | __author__ = 'Alan G. Isaac (and others as specified)' 13 | 14 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 15 | import unittest 16 | import numpy 17 | import random 18 | from econpy.pytrix import utilities, iterate, fmath 19 | from scipy import stats as Sstats 20 | 21 | class testDstat(numpy.testing.NumpyTestCase): 22 | data = numpy.random.standard_normal(30) 23 | def test_descriptive(self): 24 | from econpy.pytrix.stat import Dstat1 25 | x = numpy.array(self.data) 26 | d = Dstat1(x) 27 | self.assertEqual(d.nobs , x.size) 28 | self.assertAlmostEqual(d.sum , x.sum()) 29 | self.assertEqual(d.min , x.min()) 30 | self.assertEqual(d.max , x.max()) 31 | self.assertAlmostEqual(d.mean , x.mean()) 32 | #var: measure of the spread of the data set about the mean: unbiased 33 | self.assertAlmostEqual(d.m2 , numpy.var(x)) 34 | self.assertAlmostEqual(d.std , numpy.std(x)) 35 | #assertEqual(d.zscores , Sstats.zs(x)) 36 | self.assertAlmostEqual(d.median , Sstats.median(x)) 37 | ''' 38 | #mode: value(s) that appear(s) most often in the data set 39 | #range: difference between the largest and smallest value in the data set 40 | m2: measure of the spread of the data set about the mean: MLE 41 | std: standard deviation - measure of the dispersion of the data set based on var 42 | skew: sample skewness 43 | kurtosis: sample kurtosis 44 | jb: Jarque-Bera statistic 45 | jbpval: Jarque-Bera statistic's pvalue (Chi^2 df=2) 46 | ''' 47 | 48 | class testBiometry(numpy.testing.NumpyTestCase): 49 | def test_welchs_approximate_ttest(self): 50 | ''' 51 | :author: Angus McMorland 52 | :license: BSD_ 53 | 54 | .. BSD: http://www.opensource.org/licenses/bsd-license.php 55 | ''' 56 | from econpy.pytrix.stat import welchs_approximate_ttest 57 | chimpanzees = (37, 0.115, 0.017) # n, mean, sem 58 | gorillas = (6, 0.511, 0.144) 59 | case1 = welchs_approximate_ttest(chimpanzees[0], \ 60 | chimpanzees[1], \ 61 | chimpanzees[2], \ 62 | gorillas[0], \ 63 | gorillas[1], \ 64 | gorillas[2], \ 65 | 0.05) 66 | self.assertTrue( case1[0] ) 67 | self.assertAlmostEqual( case1[1], -2.73, 2 ) 68 | self.assertAlmostEqual( case1[2], 2.564, 2 ) 69 | 70 | female = (10, 8.5, n.sqrt(3.6)/n.sqrt(10)) 71 | male = (10, 4.8, n.sqrt(0.9)/n.sqrt(10)) 72 | case2 = welchs_approximate_ttest(female[0], \ 73 | female[1], \ 74 | female[2], \ 75 | male[0], \ 76 | male[1], \ 77 | male[2], 0.001) 78 | self.assertTrue( case2[0] ) 79 | self.assertAlmostEqual( case2[1], 5.52, 2 ) 80 | self.assertAlmostEqual( case2[2], 4.781, 2 ) 81 | 82 | if __name__ == "__main__": 83 | numpy.testing.NumpyTest().run() 84 | 85 | -------------------------------------------------------------------------------- /tests/test_text_utilities.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for econpy.utilities.text. 3 | 4 | ''' 5 | from __future__ import absolute_import 6 | from __future__ import division 7 | 8 | __docformat__ = "restructuredtext en" 9 | 10 | import unittest 11 | import random 12 | 13 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 14 | from econpy.utilities.text import SimpleTable 15 | 16 | mydata = [[11,12],[21,22]] 17 | myheaders = "Column 1", "Column 2" 18 | mystubs = "Row 1", "Row 2" 19 | txt_result=''' 20 | Title 21 | ======================= 22 | Column 1 Column 2 23 | ----------------------- 24 | Row 1 11 12 25 | Row 2 21 22 26 | ----------------------- 27 | ''' 28 | """ 29 | tbl = text.SimpleTable(mydata, myheaders, mystubs, title="Title") 30 | print( tbl ) 31 | print( tbl.as_html() ) 32 | # set column specific data formatting 33 | tbl = text.SimpleTable(mydata, myheaders, mystubs, 34 | fmt={'data_fmt':["%3.2f","%d"]}) 35 | print( tbl.as_csv() ) 36 | with open('c:/temp/temp.tex','w') as fh: 37 | fh.write( tbl.as_latex_tabular() ) 38 | """ 39 | 40 | class testUtilities(unittest.TestCase): 41 | def setUp(self): 42 | pass 43 | def test_simple_table_text(self): 44 | tbl = SimpleTable(mydata, myheaders, mystubs, title="Title") 45 | self.assertEqual(str(tbl), txt_result[1:]) 46 | 47 | if __name__=="__main__": 48 | unittest.main() 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /tests/test_tseries.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for tseries. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | from __future__ import division 10 | 11 | __docformat__ = "restructuredtext en" 12 | __author__ = 'Alan G. Isaac (and others as specified)' 13 | 14 | from itertools import izip 15 | import random 16 | import numpy as np 17 | import numpy.linalg as la 18 | import unittest 19 | 20 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 21 | from econpy.pytrix.tseries import varlags 22 | from econpy.pytrix import fmath 23 | 24 | 25 | class testTseries(unittest.TestCase): 26 | def test_varlags(self): 27 | x = np.arange(20).reshape((10,2)) 28 | xnew, xlags = varlags(x, 2) 29 | self.assert_((x[2:]==xnew).all()) 30 | self.assert_((xlags[:,:2]==x[1:-1]).all()) 31 | self.assert_((xlags[:,2:]==x[:-2]).all()) 32 | 33 | 34 | if __name__=="__main__": 35 | unittest.main() 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /tests/test_utilities.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests for utilities. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | __docformat__ = "restructuredtext en" 10 | __author__ = 'Alan G. Isaac (and others as specified)' 11 | 12 | import collections, random, unittest 13 | from typing import Callable, Sequence 14 | Function = Callable 15 | 16 | import numpy as np 17 | 18 | #import matplotlib.pyplot as plt 19 | 20 | from tests_config import econpy #tests_config.py modifies sys.path to find econpy 21 | from econpy.pytrix.utilities import n_each_rand, permutations, permutationsg 22 | from econpy.pytrix.utilities import cumsum, cumprod, unique 23 | from econpy.pytrix.utilities import gini, ginis, alt_gini #the main ones 24 | from econpy.pytrix.utilities import py_gini, py_gini, py_gini2 25 | from econpy.abm.utilities import gini2shares, gini2sharesPareto 26 | from econpy.pytrix import fmath 27 | from econpy.pytrix import stat 28 | 29 | 30 | 31 | class testUtilities(unittest.TestCase): 32 | def setUp(self): 33 | self.N = 5 34 | self.wealths = [random.random() for _ in range(2*self.N)] 35 | def test_n_each_rand(self): 36 | n = random.randrange(500) 37 | TF = n_each_rand(n, (True,False)) 38 | TFlist = list(TF) 39 | nT = TFlist.count(True) 40 | nF = TFlist.count(False) 41 | self.assertEqual(n, nT) 42 | self.assertEqual(n, nF) 43 | #print "n_each", n, nT, nF 44 | """ 45 | def test_gini2sharesvals(self): 46 | gini0 = random.random() 47 | nbrackets = random.randrange(5,500) 48 | shares = gini2shares(gini=gini0, nbrackets=nbrackets) 49 | shares02 = gini2shares02(gini=gini0, nbrackets=nbrackets) 50 | self.assertEqual(list(shares),list(shares02)) 51 | """ 52 | def test_gini2shares(self): 53 | gini0 = random.random() 54 | nbrackets = 10**random.randrange(3,5) 55 | shares01 = list(gini2shares(gini=gini0, nbrackets=nbrackets)) 56 | print("sum", sum(shares01)) 57 | gini1 = py_gini(shares01) 58 | #print "ginis:", gini0, gini1 TODO: better accuracy expected... 59 | self.assertTrue(fmath.feq(gini0, gini1, 1e-3)) #imposed and computed Gini shd be equal 60 | print("here") 61 | shares02 = list( gini2sharesPareto(gini=gini0, nbrackets=nbrackets) ) 62 | print("sum", sum(shares02)) 63 | gini2 = py_gini(shares02) 64 | #print "ginis:", gini0, gini1 TODO: better accuracy expected... 65 | self.assertTrue(fmath.feq(gini0, gini2, 1./nbrackets)) #imposed and computed Gini shd be equal 66 | """ 67 | print shares01[::100] 68 | print py_gini(shares01) 69 | print shares02[::100] 70 | print py_gini(shares02) 71 | fig, (ax1,ax2) = plt.subplots(1,2) 72 | ax1.plot(shares01) 73 | ax2.plot(np.cumsum(shares01)) 74 | ax2.plot(np.cumsum(shares02)) 75 | plt.show() 76 | exit() 77 | """ 78 | def test_cumreduce(self): 79 | self.assertEqual([0,1,3,6,10],cumsum(range(5))) 80 | self.assertEqual([0,0,0,0,0],cumprod(range(5))) 81 | def test_permutations(self): 82 | x = permutations([1,2]) 83 | y = permutations([0,1,2]) 84 | z = list( permutationsg([0,1,2]) ) 85 | self.assertEqual(x,[[1,2],[2,1]]) 86 | self.assertEqual(y,z) 87 | def test_math(self): 88 | print(fmath.get_float_radix()) 89 | print(fmath.get_machine_precision()) 90 | print(fmath.get_default_numerical_precision()) 91 | print(fmath.feq(1,2), fmath.feq(1e-9, 1e-10), fmath.feq(1e-16, 1e-17)) 92 | 93 | 94 | class testGinis(unittest.TestCase): 95 | def setUp(self): 96 | self.N = 5 97 | self.wealths = [10*random.random() for _ in range(2*self.N)] 98 | self.wealths02 = self.wealths[:] 99 | self.wealths02[-1] = np.nan 100 | def test_ginis(self): 101 | #test that two Gini formulae give same result 102 | g0 = gini(self.wealths) 103 | g1 = py_gini(self.wealths) 104 | g2 = py_gini2(self.wealths) 105 | g3 = alt_gini(self.wealths) 106 | g5, bad = ginis([self.wealths,self.wealths02]) 107 | #print "g1:%f, g2:%f"%(g1, g2) 108 | for gi in (g1,g2,g3,g5): 109 | self.assertTrue(fmath.feq(g0,gi)) 110 | print("g1={},g5={}, bad={}".format(g1, g5, bad)) 111 | def test_unique(self): 112 | xs = list(random.randrange(10) for _ in range(20)) 113 | us01 = unique(xs) 114 | us02 = list(np.unique(xs)) 115 | self.assertEqual(us01,us02) 116 | us01 = unique(xs, reverse=True) 117 | us02 = list(reversed(np.unique(xs))) 118 | self.assertEqual(us01,us02) 119 | 120 | #BEGIN:ecdf; 121 | def simplest_ecdf( 122 | xs: Sequence #real numbers (the data) 123 | ) -> Function: #the empirical cdf of xs 124 | nobs = float(len(xs)) 125 | def f(x): #the ecdf for the xs 126 | return sum(1 for xi in xs if xi <= x) / nobs 127 | return f 128 | #END:ecdf; 129 | 130 | def ecdf_np( 131 | xs: Sequence #real numbers (the data) 132 | ) -> Function: #the empirical cdf of xs 133 | xs = np.sort(xs) 134 | nobs = float(len(xs)) 135 | def f(x): #the ecdf for the xs 136 | # side='right' to get all xi in xs if xi <= x 137 | return np.searchsorted(xs, x, side='right') / nobs 138 | return f 139 | 140 | #chkchkchk compare to 141 | #from statsmodels.distributions.empirical_distribution import ECDF 142 | class testStatUtilities(unittest.TestCase): 143 | def test_ecdf(self): 144 | nobs = 100 145 | data = np.random.randint(100, size=(nobs,)) 146 | cts = collections.Counter(data) 147 | f1 = simplest_ecdf(data) 148 | f2 = stat.ecdf(sorted(data)) 149 | f3 = ecdf_np(data) 150 | 151 | for x in cts: 152 | self.assertAlmostEqual(f1(x), f2(x)) 153 | self.assertAlmostEqual(f1(x), f3(x)) 154 | 155 | 156 | 157 | if __name__=="__main__": 158 | unittest.main() 159 | 160 | 161 | # vim: set expandtab:ts=4:sw=4 162 | -------------------------------------------------------------------------------- /tests/tests_config.py: -------------------------------------------------------------------------------- 1 | '''Used by tests to find the econpy package, 2 | either as installed or relative to script location. 3 | ''' 4 | try: 5 | import econpy 6 | except ImportError: 7 | import os, sys 8 | package4tests = os.path.abspath(__file__) 9 | for _ in range(3): 10 | package4tests = os.path.split(package4tests)[0] 11 | sys.path.insert(0,package4tests) #need location of econpy 12 | import econpy 13 | 14 | -------------------------------------------------------------------------------- /tests/tests_config.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/tests/tests_config.pyc -------------------------------------------------------------------------------- /text/README: -------------------------------------------------------------------------------- 1 | Materials in this folder and its subfolders are licensed under the 2 | `Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License`_ 3 | except where explicitly released under a different license. 4 | 5 | 6 | .. `Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License`: 7 | http://creativecommons.org/licenses/by-nc-nd/3.0/ 8 | -------------------------------------------------------------------------------- /text/vimfiles/ai_texmenus.vim: -------------------------------------------------------------------------------- 1 | " MiKTeX MENUS for GVim: 2 | " In your _gvimrc file, source this file or copy its contents. 3 | 4 | " First set working directory to current directory 5 | " (needed to ensure .dvi and .aux files are in same director as .tex file): 6 | au BufEnter *.tex cd %:p:h 7 | "========================================================== 8 | " MiKTeX menus setup: 9 | " 1. set MIKTEXBIN to location of binaries 10 | let MIKTEXBIN='C:\Program Files\MiKTeX 2.9\miktex\bin\x64\' 11 | " 2. set GSPATH to full path to ghostscript\lib 12 | let GSPATH='C:\programs\gs\gs8.64\lib\' 13 | " 3. set GSVPATH to full path to ghostview32.exe 14 | let GSVPATH='C:\programs\Ghostgum\gsview\gsview64.exe' 15 | let PDFVIEWERPATH='D:\programs\SumatraPDF\SumatraPDF.exe' 16 | let ACROPATH='C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe' 17 | let NOTESPATH='C:\Users\aisaac\dpt\www\notes' 18 | "========================================================== 19 | silent amenu 90.10 &MiKTeX.Te&Xify :up:execute '!start "'.MIKTEXBIN.'texify.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'.tex"' 20 | silent amenu 90.20 &MiKTeX.View\ with\ PDF\ &Viewer :execute '!start "'.PDFVIEWERPATH.'" "'.fnamemodify(@%,':p:r').'.pdf"' 21 | silent amenu 90.30 &MiKTeX.View\ with\ &Acrobat :execute '!start "'.ACROPATH.'" "'.fnamemodify(@%,':p:r:gs?\\?/?').'.pdf"' 22 | silent amenu 90.35 &MiKTeX.View\ with\ &Yap :execute '!start "'.MIKTEXBIN.'yap.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'.dvi"' 23 | silent amenu 90.40 &MiKTeX.View\ with\ &GSview :execute '!start "'.GSVPATH.'" "'.fnamemodify(@%,':p:r:gs?\\?/?').'.ps"' 24 | silent amenu 90.50 &MiKTeX.View\ Web\ &Notes :execute '!start cmd /c "'.NOTESPATH.'\'.fnamemodify(@%,':r').'.html"' 25 | " silent amenu 90.50 &MiKTeX.&Run\ local\ batch :execute '!start "'.fnamemodify(@%,':p:r:gs?\\?/?').'.bat"' 26 | amenu 90.100 &MiKTeX.-SEP1- : 27 | silent amenu 90.110 &MiKTeX.&luatex :up:execute '!start "'.MIKTEXBIN.'lualatex.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 28 | silent amenu 90.120 &MiKTeX.&pdflatex :up:execute '!start "'.MIKTEXBIN.'pdflatex.exe" --shell-escape "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 29 | silent amenu 90.130 &MiKTeX.La&TeX :up:silent execute '!start "'.MIKTEXBIN.'latex.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 30 | silent amenu 90.140 &MiKTeX.&Biber :execute '!start "'.MIKTEXBIN.'biber.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 31 | silent amenu 90.145 &MiKTeX.&BibTeX :execute '!start "'.MIKTEXBIN.'bibtex.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 32 | " silent amenu 90.150 &MiKTeX.Make&Index :execute '!start "'.MIKTEXBIN.'makeindex.exe" "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 33 | silent amenu 90.150 &MiKTeX.Make&Index :execute '!start "'.MIKTEXBIN.'makeindex.exe" "'.fnamemodify(@%,':r:gs?\\?/?').'"' 34 | " amenu 90.200 &MiKTeX.-SEP2- : 35 | " silent amenu 90.210 &MiKTeX.dvip&s :execute '!start "'.MIKTEXBIN.'dvips.exe" -Ppdf "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 36 | " silent amenu 90.220 &MiKTeX.dvipdf&m :execute '!start "'.MIKTEXBIN.'dvipdfm.exe" -vv "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 37 | " silent amenu 90.230 &MiKTeX.dvipdfm(landscape) :execute '!start "'.MIKTEXBIN.'dvipdfm.exe" -l "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 38 | " silent amenu 90.240 &MiKTeX.dvipdfmx :execute '!start "'.MIKTEXBIN.'dvipdfmx.exe" -vv "'.fnamemodify(@%,':p:r:gs?\\?/?').'"' 39 | " silent amenu 90.260 &MiKTeX.ps&2pdf :execute '!start "'.GSPATH.'ps2pdf.bat" "'.fnamemodify(@%,':p:r:gs?\\?/?').'.ps"' 40 | -------------------------------------------------------------------------------- /text/vimfiles/aisaac/_gvimrc: -------------------------------------------------------------------------------- 1 | "set font (see options.txt) 2 | set guifont=andale_mono:h14,Lucida_Console:h14,courier_new:h14 3 | "set window size and positon 4 | set columns =120 5 | set lines =40 6 | winpos 100 100 7 | " turn on autoselect 8 | set guioptions+=a 9 | " ensure default for paste 10 | set nopaste 11 | 12 | "$VIMFILES should be set in _vimrc 13 | source $VIMFILES/ai_texmenus.vim 14 | -------------------------------------------------------------------------------- /text/vimfiles/aisaac/_vimrc: -------------------------------------------------------------------------------- 1 | "dump lingering autocommands (protects against resourcing this file) 2 | autocmd! 3 | 4 | if has("unix") 5 | let $VIMFILES = $HOME . "/.vim" 6 | else 7 | let $VIMFILES = $HOME . "/vimfiles" 8 | "http://stackoverflow.com/questions/94382/vim-with-powershell 9 | "set shell=powershell 10 | "set shellcmdflag=-ExecutionPolicy\ RemoteSigned\ -Command 11 | " shellxquote must be a literal space character. 12 | "set shellquote=\" 13 | "set shellxquote= 14 | endif 15 | 16 | set encoding=utf-8 17 | " keep these under git control (in econpy/text/vimfiles) 18 | source $VIMFILES\share_vimrc.vim 19 | source $VIMFILES\ai_vimrc.vim 20 | 21 | -------------------------------------------------------------------------------- /text/vimfiles/colors/bmichaelsen.vim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/text/vimfiles/colors/bmichaelsen.vim -------------------------------------------------------------------------------- /text/vimfiles/colors/breeze.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Tiza 3 | " Last Change: 2002/10/30 Wed 00:08. 4 | " version: 1.0 5 | " This color scheme uses a dark background. 6 | 7 | set background=dark 8 | hi clear 9 | if exists("syntax_on") 10 | syntax reset 11 | endif 12 | 13 | let colors_name = "breeze" 14 | 15 | hi Normal guifg=#ffffff guibg=#005c70 16 | 17 | " Search 18 | hi IncSearch gui=UNDERLINE guifg=#60ffff guibg=#6060ff 19 | hi Search gui=NONE guifg=#ffffff guibg=#6060ff 20 | 21 | " Messages 22 | hi ErrorMsg gui=BOLD guifg=#ffffff guibg=#ff40a0 23 | hi WarningMsg gui=BOLD guifg=#ffffff guibg=#ff40a0 24 | hi ModeMsg gui=NONE guifg=#60ffff guibg=NONE 25 | hi MoreMsg gui=NONE guifg=#ffc0ff guibg=NONE 26 | hi Question gui=NONE guifg=#ffff60 guibg=NONE 27 | 28 | " Split area 29 | hi StatusLine gui=NONE guifg=#000000 guibg=#d0d0e0 30 | hi StatusLineNC gui=NONE guifg=#606080 guibg=#d0d0e0 31 | hi VertSplit gui=NONE guifg=#606080 guibg=#d0d0e0 32 | hi WildMenu gui=NONE guifg=#000000 guibg=#00c8f0 33 | 34 | " Diff 35 | hi DiffText gui=UNDERLINE guifg=#ffff00 guibg=#000000 36 | hi DiffChange gui=NONE guifg=#ffffff guibg=#000000 37 | hi DiffDelete gui=NONE guifg=#60ff60 guibg=#000000 38 | hi DiffAdd gui=NONE guifg=#60ff60 guibg=#000000 39 | 40 | " Cursor 41 | hi Cursor gui=NONE guifg=#ffffff guibg=#d86020 42 | hi lCursor gui=NONE guifg=#ffffff guibg=#e000b0 43 | hi CursorIM gui=NONE guifg=#ffffff guibg=#e000b0 44 | 45 | " Fold 46 | hi Folded gui=NONE guifg=#ffffff guibg=#0088c0 47 | " hi Folded gui=NONE guifg=#ffffff guibg=#2080d0 48 | hi FoldColumn gui=NONE guifg=#60e0e0 guibg=#006c7f 49 | 50 | " Other 51 | hi Directory gui=NONE guifg=#00e0ff guibg=NONE 52 | hi LineNr gui=NONE guifg=#60a8bc guibg=NONE 53 | hi NonText gui=BOLD guifg=#00c0c0 guibg=#006276 54 | hi SpecialKey gui=NONE guifg=#e0a0ff guibg=NONE 55 | hi Title gui=BOLD guifg=#ffffff guibg=NONE 56 | hi Visual gui=NONE guifg=#ffffff guibg=#6060d0 57 | " hi VisualNOS gui=NONE guifg=#ffffff guibg=#6060d0 58 | 59 | " Syntax group 60 | hi Comment gui=NONE guifg=#c8d0d0 guibg=NONE 61 | hi Constant gui=NONE guifg=#60ffff guibg=NONE 62 | hi Error gui=BOLD guifg=#ffffff guibg=#ff40a0 63 | hi Identifier gui=NONE guifg=#cacaff guibg=NONE 64 | hi Ignore gui=NONE guifg=#006074 guibg=NONE 65 | hi PreProc gui=NONE guifg=#ffc0ff guibg=NONE 66 | hi Special gui=NONE guifg=#ffd074 guibg=NONE 67 | hi Statement gui=NONE guifg=#ffff80 guibg=NONE 68 | hi Todo gui=BOLD,UNDERLINE guifg=#ffb0b0 guibg=NONE 69 | hi Type gui=NONE guifg=#80ffa0 guibg=NONE 70 | hi Underlined gui=UNDERLINE guifg=#ffffff guibg=NONE 71 | -------------------------------------------------------------------------------- /text/vimfiles/colors/darkblue.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Bohdan Vlasyuk 3 | " Last Change: 2002 Mar 09 4 | 5 | " darkblue -- for those who prefer dark background 6 | " [note: looks bit uglier with come terminal palettes, 7 | " but is fine on default linux console palette.] 8 | 9 | set bg=dark 10 | hi clear 11 | if exists("syntax_on") 12 | syntax reset 13 | endif 14 | 15 | let colors_name = "darkblue" 16 | 17 | hi Normal guifg=#c0c0c0 guibg=#000040 ctermfg=gray ctermbg=black 18 | hi ErrorMsg guifg=#ffffff guibg=#287eff ctermfg=white ctermbg=lightblue 19 | hi Visual guifg=#8080ff guibg=fg gui=reverse ctermfg=lightblue ctermbg=fg cterm=reverse 20 | hi VisualNOS guifg=#8080ff guibg=fg gui=reverse,underline ctermfg=lightblue ctermbg=fg cterm=reverse,underline 21 | hi Todo guifg=#d14a14 guibg=#1248d1 ctermfg=red ctermbg=darkblue 22 | hi Search guifg=#90fff0 guibg=#2050d0 ctermfg=white ctermbg=darkblue cterm=underline term=underline 23 | hi IncSearch guifg=#b0ffff guibg=#2050d0 ctermfg=darkblue ctermbg=gray 24 | 25 | hi SpecialKey guifg=cyan ctermfg=darkcyan 26 | hi Directory guifg=cyan ctermfg=cyan 27 | hi Title guifg=magenta gui=none ctermfg=magenta cterm=bold 28 | hi WarningMsg guifg=red ctermfg=red 29 | hi WildMenu guifg=yellow guibg=black ctermfg=yellow ctermbg=black cterm=none term=none 30 | hi ModeMsg guifg=#22cce2 ctermfg=lightblue 31 | hi MoreMsg ctermfg=darkgreen ctermfg=darkgreen 32 | hi Question guifg=green gui=none ctermfg=green cterm=none 33 | hi NonText guifg=#0030ff ctermfg=darkblue 34 | 35 | hi StatusLine guifg=blue guibg=darkgray gui=none ctermfg=blue ctermbg=gray term=none cterm=none 36 | hi StatusLineNC guifg=black guibg=darkgray gui=none ctermfg=black ctermbg=gray term=none cterm=none 37 | hi VertSplit guifg=black guibg=darkgray gui=none ctermfg=black ctermbg=gray term=none cterm=none 38 | 39 | hi Folded guifg=#808080 guibg=#000040 ctermfg=darkgrey ctermbg=black cterm=bold term=bold 40 | hi FoldColumn guifg=#808080 guibg=#000040 ctermfg=darkgrey ctermbg=black cterm=bold term=bold 41 | hi LineNr guifg=#90f020 ctermfg=green cterm=none 42 | 43 | hi DiffAdd guibg=darkblue ctermbg=darkblue term=none cterm=none 44 | hi DiffChange guibg=darkmagenta ctermbg=magenta cterm=none 45 | hi DiffDelete ctermfg=blue ctermbg=cyan gui=bold guifg=Blue guibg=DarkCyan 46 | hi DiffText cterm=bold ctermbg=red gui=bold guibg=Red 47 | 48 | hi Cursor guifg=#000020 guibg=#ffaf38 ctermfg=bg ctermbg=brown 49 | hi lCursor guifg=#ffffff guibg=#000000 ctermfg=bg ctermbg=darkgreen 50 | 51 | 52 | hi Comment guifg=#80a0ff ctermfg=darkred 53 | hi Constant ctermfg=magenta guifg=#ffa0a0 cterm=none 54 | hi Special ctermfg=brown guifg=Orange cterm=none gui=none 55 | hi Identifier ctermfg=cyan guifg=#40ffff cterm=none 56 | hi Statement ctermfg=yellow cterm=none guifg=#ffff60 gui=none 57 | hi PreProc ctermfg=magenta guifg=#ff80ff gui=none cterm=none 58 | hi type ctermfg=green guifg=#60ff60 gui=none cterm=none 59 | hi Underlined cterm=underline term=underline 60 | hi Ignore guifg=bg ctermfg=bg 61 | 62 | 63 | -------------------------------------------------------------------------------- /text/vimfiles/colors/darker-robin.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Alexander Chaika 3 | " Last Change: October, 6,2006 4 | " Version: 0.1 5 | 6 | " This is a modification of robinhood color scheme, 7 | " _ created by Alex Schroede. 8 | 9 | set background=dark 10 | hi clear 11 | if exists("syntax_on") 12 | syntax reset 13 | endif 14 | 15 | 16 | """ Colors 17 | 18 | " GUI colors 19 | hi Cursor guifg=fg guibg=gray gui=none 20 | hi CursorIM guifg=NONE guibg=gray gui=none 21 | " hi Directory guifg=#ff0000 guibg=#00ffff gui=none 22 | " hi DiffAdd 23 | " hi DiffChange 24 | " hi DiffDelete 25 | " hi DiffText 26 | hi ErrorMsg guifg=White guibg=Red gui=none 27 | " hi Folded 28 | " hi FoldColumn 29 | " hi IncSearch 30 | " hi ModeMsg 31 | " hi MoreMsg 32 | hi NonText guifg=#000000 guibg=#101010 gui=none 33 | 34 | hi LineNr guifg=#909000 guibg=#101010 gui=none 35 | 36 | hi Normal guifg=#807057 guibg=#101010 gui=none 37 | " hi Question 38 | hi Search guifg=#000000 guibg=gray gui=none 39 | " hi SpecialKey 40 | hi StatusLine guifg=#000000 guibg=#606050 gui=none 41 | hi StatusLineNC guifg=#000001 guibg=#606050 gui=none 42 | " hi Title 43 | " hi Visual guifg=#ffff00 gui=none 44 | " hi VisualNOS guifg=Black gui=none 45 | hi WarningMsg guifg=White gui=none 46 | " hi WildMenu 47 | 48 | hi Comment guifg=#606099 gui=none 49 | 50 | hi Constant guifg=#8da0a0 gui=none 51 | hi String guifg=#a0644d gui=none 52 | hi Character guifg=#a0644d gui=none 53 | hi Number guifg=#8da0a0 gui=none 54 | hi Boolean guifg=#8da0a0 gui=none 55 | hi Float guifg=#8da0a0 gui=none 56 | 57 | hi Identifier guifg=#70b970 gui=none 58 | hi Function guifg=yellowgreen gui=none 59 | 60 | hi Statement guifg=#b05a50 gui=none 61 | hi Conditional guifg=#b05a50 gui=none 62 | hi Repeat guifg=#b05a50 gui=none 63 | hi Label guifg=#b05a50 gui=none 64 | hi Operator guifg=#c0ba98 gui=none 65 | hi Keyword guifg=#b05a50 gui=none 66 | hi Exception guifg=#b05a50 gui=none 67 | 68 | hi PreProc guifg=#70b970 gui=none 69 | hi Include guifg=#70b970 gui=none 70 | hi Define guifg=#70b970 gui=none 71 | hi Macro guifg=#70b970 gui=none 72 | hi PreCondit guifg=#70b970 gui=none 73 | 74 | 75 | hi Type guifg=#70b970 gui=none 76 | hi StorageClass guifg=#50a085 gui=none 77 | hi Structure guifg=#50a085 gui=none 78 | hi Typedef guifg=#50a085 gui=none 79 | 80 | hi Underlined gui=underline 81 | 82 | hi Ignore guifg=bg 83 | 84 | hi Error guifg=White guibg=Red gui=none 85 | 86 | hi Todo guifg=#900000 guibg=#909000 gui=none 87 | 88 | -------------------------------------------------------------------------------- /text/vimfiles/colors/darkerdesert.vim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/text/vimfiles/colors/darkerdesert.vim -------------------------------------------------------------------------------- /text/vimfiles/colors/darkslategray.vim: -------------------------------------------------------------------------------- 1 | " vim: set tw=0 sw=4 sts=4 et: 2 | 3 | " Vim color file 4 | " Maintainer: Tuomas Susi 5 | " Last Change: 2003 June 18 6 | " Version: 1.4 7 | " URI: http://www.hut.fi/~/tsusi/vim/darkslategray.vim 8 | 9 | " Emacs in RedHat Linux used to have (still does?) a kind of 'Wheat on 10 | " DarkSlateGray' color scheme by default. This color scheme is created in the 11 | " same spirit. 12 | " 13 | " Darkslategray is intended to be nice to your eyes (low contrast) and to take 14 | " advantage of syntax hilighting as much as possible. 15 | " 16 | " This color scheme is for the GUI only, I'm happy with default console colors. 17 | " Needs at least vim 6.0. 18 | 19 | 20 | """ Init stuff 21 | 22 | set background=dark 23 | hi clear 24 | if exists("syntax_on") 25 | syntax reset 26 | endif 27 | 28 | let g:colors_name = "darkslategray" 29 | 30 | 31 | """ Colors 32 | 33 | " GUI colors 34 | hi Cursor guifg=fg guibg=Orchid 35 | hi CursorIM guifg=NONE guibg=Orchid1 36 | hi Directory guifg=LightCyan 37 | hi DiffAdd guibg=DarkSlateGray4 38 | hi DiffChange guibg=Pink4 39 | hi DiffDelete gui=bold guifg=fg guibg=Black 40 | hi DiffText gui=bold guibg=SlateBlue3 41 | hi ErrorMsg gui=bold guifg=White guibg=Red 42 | hi VertSplit gui=bold guifg=DarkKhaki guibg=Black 43 | hi Folded guifg=Black guibg=DarkKhaki 44 | hi FoldColumn guifg=Black guibg=DarkKhaki 45 | hi IncSearch gui=bold guifg=Black guibg=White 46 | hi LineNr gui=bold guifg=DarkKhaki guibg=DarkSlateGray4 47 | hi ModeMsg gui=bold 48 | hi MoreMsg gui=bold guifg=LightSeaGreen 49 | hi NonText gui=bold guifg=White 50 | hi Normal guibg=DarkSlateGray guifg=Wheat 51 | hi Question gui=bold guifg=Tomato 52 | hi Search gui=bold guifg=Black guibg=Gold 53 | hi SpecialKey guifg=Cyan 54 | hi StatusLine gui=bold guifg=Khaki guibg=Black 55 | hi StatusLineNC guibg=DarkKhaki guifg=Gray25 56 | hi Title gui=bold guifg=Tomato 57 | hi Visual guifg=Black guibg=fg 58 | hi VisualNOS gui=bold guifg=Black guibg=fg 59 | hi WarningMsg guifg=White guibg=Tomato 60 | hi WildMenu gui=bold guifg=Black guibg=Yellow 61 | 62 | " I use GTK and don't wanna change these 63 | "hi Menu foobar 64 | "hi Scrollbar foobar 65 | "hi Tooltip foobar 66 | 67 | " Colors for syntax highlighting 68 | hi Comment guifg=Orchid 69 | 70 | hi Constant guifg=Aquamarine 71 | hi String guifg=Aquamarine 72 | hi Character guifg=Aquamarine 73 | hi Number guifg=LightBlue 74 | hi Boolean guifg=LightCyan 75 | hi Float guifg=LightBlue 76 | 77 | hi Identifier guifg=Thistle 78 | hi Function guifg=White 79 | 80 | hi Statement gui=bold guifg=LightSteelBlue 81 | hi Conditional gui=bold guifg=LightSteelBlue 82 | hi Repeat gui=bold guifg=SteelBlue 83 | hi Label gui=bold guifg=SteelBlue 84 | hi Operator gui=bold guifg=LightSteelBlue 85 | hi Keyword gui=bold guifg=LightSteelBlue 86 | hi Exception gui=bold guifg=LightSteelBlue 87 | 88 | hi PreProc guifg=Yellow2 89 | hi Include guifg=Yellow3 90 | hi Define guifg=Yellow2 91 | hi Macro guifg=Yellow2 92 | hi PreCondit gui=bold guifg=Yellow2 93 | 94 | hi Type gui=bold guifg=PaleGreen 95 | hi StorageClass guifg=Green 96 | hi Structure guifg=LightSeaGreen 97 | hi Typedef guifg=PaleTurquoise 98 | 99 | hi Special guifg=Tomato 100 | "Underline Character 101 | hi SpecialChar gui=underline guifg=Aquamarine 102 | hi Tag guifg=DarkKhaki 103 | "Statement 104 | hi Delimiter gui=bold guifg=LightSteelBlue 105 | "Bold comment (in Java at least) 106 | hi SpecialComment gui=bold guifg=Orchid 107 | hi Debug gui=bold guifg=Red 108 | 109 | hi Underlined gui=underline 110 | 111 | hi Ignore guifg=bg 112 | 113 | hi Error gui=bold guifg=White guibg=Red 114 | 115 | hi Todo gui=bold guifg=Black guibg=Orchid1 116 | 117 | -------------------------------------------------------------------------------- /text/vimfiles/colors/desert.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Hans Fugal 3 | " Last Change: $Date: 2003/06/02 19:28:15 $ 4 | " URL: http://hans.fugal.net/vim/colors/desert.vim 5 | 6 | " cool help screens 7 | " :he group-name 8 | " :he highlight-groups 9 | " :he cterm-colors 10 | 11 | set background=dark 12 | if version > 580 13 | " no guarantees for version 5.8 and below, but this makes it stop 14 | " complaining 15 | hi clear 16 | if exists("syntax_on") 17 | syntax reset 18 | endif 19 | endif 20 | let g:colors_name="desert" 21 | 22 | hi Normal guifg=White guibg=grey20 23 | 24 | " highlight groups 25 | hi Cursor guibg=khaki guifg=slategrey 26 | "hi CursorIM 27 | "hi Directory 28 | "hi DiffAdd 29 | "hi DiffChange 30 | "hi DiffDelete 31 | "hi DiffText 32 | "hi ErrorMsg 33 | hi VertSplit guibg=#c2bfa5 guifg=grey50 gui=none 34 | hi Folded guibg=grey30 guifg=gold 35 | hi FoldColumn guibg=grey30 guifg=tan 36 | hi IncSearch guifg=slategrey guibg=khaki 37 | "hi LineNr 38 | hi ModeMsg guifg=goldenrod 39 | hi MoreMsg guifg=SeaGreen 40 | hi NonText guifg=LightBlue guibg=grey30 41 | hi Question guifg=springgreen 42 | hi Search guibg=peru guifg=wheat 43 | hi SpecialKey guifg=yellowgreen 44 | hi StatusLine guibg=#c2bfa5 guifg=black gui=none 45 | hi StatusLineNC guibg=#c2bfa5 guifg=grey50 gui=none 46 | hi Title guifg=indianred 47 | hi Visual gui=none guifg=khaki guibg=olivedrab 48 | "hi VisualNOS 49 | hi WarningMsg guifg=salmon 50 | "hi WildMenu 51 | "hi Menu 52 | "hi Scrollbar 53 | "hi Tooltip 54 | 55 | " syntax highlighting groups 56 | hi Comment guifg=SkyBlue 57 | hi Constant guifg=#ffa0a0 58 | hi Identifier guifg=palegreen 59 | hi Statement guifg=khaki 60 | hi PreProc guifg=indianred 61 | hi Type guifg=darkkhaki 62 | hi Special guifg=navajowhite 63 | "hi Underlined 64 | hi Ignore guifg=grey40 65 | "hi Error 66 | hi Todo guifg=orangered guibg=yellow2 67 | 68 | " color terminal definitions 69 | hi SpecialKey ctermfg=darkgreen 70 | hi NonText cterm=bold ctermfg=darkblue 71 | hi Directory ctermfg=darkcyan 72 | hi ErrorMsg cterm=bold ctermfg=7 ctermbg=1 73 | hi IncSearch cterm=NONE ctermfg=yellow ctermbg=green 74 | hi Search cterm=NONE ctermfg=grey ctermbg=blue 75 | hi MoreMsg ctermfg=darkgreen 76 | hi ModeMsg cterm=NONE ctermfg=brown 77 | hi LineNr ctermfg=3 78 | hi Question ctermfg=green 79 | hi StatusLine cterm=bold,reverse 80 | hi StatusLineNC cterm=reverse 81 | hi VertSplit cterm=reverse 82 | hi Title ctermfg=5 83 | hi Visual cterm=reverse 84 | hi VisualNOS cterm=bold,underline 85 | hi WarningMsg ctermfg=1 86 | hi WildMenu ctermfg=0 ctermbg=3 87 | hi Folded ctermfg=darkgrey ctermbg=NONE 88 | hi FoldColumn ctermfg=darkgrey ctermbg=NONE 89 | hi DiffAdd ctermbg=4 90 | hi DiffChange ctermbg=5 91 | hi DiffDelete cterm=bold ctermfg=4 ctermbg=6 92 | hi DiffText cterm=bold ctermbg=1 93 | hi Comment ctermfg=darkcyan 94 | hi Constant ctermfg=brown 95 | hi Special ctermfg=5 96 | hi Identifier ctermfg=6 97 | hi Statement ctermfg=3 98 | hi PreProc ctermfg=5 99 | hi Type ctermfg=2 100 | hi Underlined cterm=underline ctermfg=5 101 | hi Ignore ctermfg=darkgrey 102 | hi Error cterm=bold ctermfg=7 ctermbg=1 103 | 104 | 105 | "vim: sw=4 106 | -------------------------------------------------------------------------------- /text/vimfiles/colors/download_script.php: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Alexander Chaika 3 | " Last Change: October, 6,2006 4 | " Version: 0.1 5 | 6 | " This is a modification of robinhood color scheme, 7 | " _ created by Alex Schroede. 8 | 9 | set background=dark 10 | hi clear 11 | if exists("syntax_on") 12 | syntax reset 13 | endif 14 | 15 | 16 | """ Colors 17 | 18 | " GUI colors 19 | hi Cursor guifg=fg guibg=gray gui=none 20 | hi CursorIM guifg=NONE guibg=gray gui=none 21 | " hi Directory guifg=#ff0000 guibg=#00ffff gui=none 22 | " hi DiffAdd 23 | " hi DiffChange 24 | " hi DiffDelete 25 | " hi DiffText 26 | hi ErrorMsg guifg=White guibg=Red gui=none 27 | " hi Folded 28 | " hi FoldColumn 29 | " hi IncSearch 30 | " hi ModeMsg 31 | " hi MoreMsg 32 | hi NonText guifg=#000000 guibg=#101010 gui=none 33 | 34 | hi LineNr guifg=#909000 guibg=#101010 gui=none 35 | 36 | hi Normal guifg=#807057 guibg=#101010 gui=none 37 | " hi Question 38 | hi Search guifg=#000000 guibg=gray gui=none 39 | " hi SpecialKey 40 | hi StatusLine guifg=#000000 guibg=#606050 gui=none 41 | hi StatusLineNC guifg=#000001 guibg=#606050 gui=none 42 | " hi Title 43 | " hi Visual guifg=#ffff00 gui=none 44 | " hi VisualNOS guifg=Black gui=none 45 | hi WarningMsg guifg=White gui=none 46 | " hi WildMenu 47 | 48 | hi Comment guifg=#606099 gui=none 49 | 50 | hi Constant guifg=#8da0a0 gui=none 51 | hi String guifg=#a0644d gui=none 52 | hi Character guifg=#a0644d gui=none 53 | hi Number guifg=#8da0a0 gui=none 54 | hi Boolean guifg=#8da0a0 gui=none 55 | hi Float guifg=#8da0a0 gui=none 56 | 57 | hi Identifier guifg=#70b970 gui=none 58 | hi Function guifg=yellowgreen gui=none 59 | 60 | hi Statement guifg=#b05a50 gui=none 61 | hi Conditional guifg=#b05a50 gui=none 62 | hi Repeat guifg=#b05a50 gui=none 63 | hi Label guifg=#b05a50 gui=none 64 | hi Operator guifg=#c0ba98 gui=none 65 | hi Keyword guifg=#b05a50 gui=none 66 | hi Exception guifg=#b05a50 gui=none 67 | 68 | hi PreProc guifg=#70b970 gui=none 69 | hi Include guifg=#70b970 gui=none 70 | hi Define guifg=#70b970 gui=none 71 | hi Macro guifg=#70b970 gui=none 72 | hi PreCondit guifg=#70b970 gui=none 73 | 74 | 75 | hi Type guifg=#70b970 gui=none 76 | hi StorageClass guifg=#50a085 gui=none 77 | hi Structure guifg=#50a085 gui=none 78 | hi Typedef guifg=#50a085 gui=none 79 | 80 | hi Underlined gui=underline 81 | 82 | hi Ignore guifg=bg 83 | 84 | hi Error guifg=White guibg=Red gui=none 85 | 86 | hi Todo guifg=#900000 guibg=#909000 gui=none 87 | 88 | -------------------------------------------------------------------------------- /text/vimfiles/colors/dusk.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Ajit J. Thakkar (ajit AT unb DOT ca) 3 | " Last Change: 2003 Sep. 02 4 | " Version: 1.0 5 | " URL: http://www.unb.ca/chem/ajit/vim.htm 6 | 7 | " This GUI-only color scheme has a blue-black background 8 | 9 | set background=dark 10 | hi clear 11 | if exists("syntax_on") 12 | syntax reset 13 | endif 14 | 15 | let colors_name = "dusk" 16 | 17 | hi Normal guifg=ivory guibg=#1f3048 18 | 19 | " Groups used in the 'highlight' and 'guicursor' options default value. 20 | hi ErrorMsg gui=NONE guifg=Red guibg=Linen 21 | hi IncSearch gui=NONE guibg=LightGreen guifg=Black 22 | hi ModeMsg gui=NONE guifg=fg guibg=bg 23 | hi StatusLine gui=NONE guifg=DarkBlue guibg=Grey 24 | hi StatusLineNC gui=NONE guifg=Grey50 guibg=Grey 25 | hi VertSplit gui=NONE guifg=Grey guibg=Grey 26 | hi Visual gui=reverse guifg=fg guibg=LightSkyBlue4 27 | hi VisualNOS gui=underline guifg=fg guibg=bg 28 | hi DiffText gui=NONE guifg=Yellow guibg=LightSkyBlue4 29 | hi Cursor guibg=Green guifg=Black 30 | hi lCursor guibg=Cyan guifg=Black 31 | hi Directory guifg=LightGreen guibg=bg 32 | hi LineNr guifg=MistyRose3 guibg=bg 33 | hi MoreMsg gui=NONE guifg=SeaGreen guibg=bg 34 | hi NonText gui=NONE guifg=Cyan4 guibg=#102848 35 | hi Question gui=NONE guifg=LimeGreen guibg=bg 36 | hi Search gui=NONE guifg=SkyBlue4 guibg=Bisque 37 | hi SpecialKey guifg=Cyan guibg=bg 38 | hi Title gui=NONE guifg=Yellow2 guibg=bg 39 | hi WarningMsg guifg=Tomato3 guibg=Linen 40 | hi WildMenu gui=NONE guifg=SkyBlue4 guibg=Bisque 41 | hi Folded guifg=MistyRose2 guibg=bg 42 | hi FoldColumn guifg=DarkBlue guibg=Grey 43 | hi DiffAdd gui=NONE guifg=Blue guibg=LightCyan 44 | hi DiffChange gui=NONE guifg=white guibg=LightCyan4 45 | hi DiffDelete gui=NONE guifg=LightBlue guibg=LightCyan 46 | 47 | " Colors for syntax highlighting 48 | hi Constant gui=NONE guifg=MistyRose3 guibg=bg 49 | hi String gui=NONE guifg=LightBlue3 guibg=bg 50 | hi Special gui=NONE guifg=GoldenRod guibg=bg 51 | hi Statement gui=NONE guifg=khaki guibg=bg 52 | "hi Statement gui=NONE guifg=#d7cd7b guibg=bg 53 | hi Operator gui=NONE guifg=Chartreuse guibg=bg 54 | hi Ignore gui=NONE guifg=bg guibg=bg 55 | hi ToDo gui=NONE guifg=DodgerBlue guibg=bg 56 | hi Error gui=NONE guifg=Red guibg=Linen 57 | hi Comment gui=NONE guifg=SlateGrey guibg=bg 58 | hi Comment gui=NONE guifg=Lavender guibg=bg 59 | hi Identifier gui=NONE guifg=BlanchedAlmond guibg=bg 60 | hi PreProc gui=NONE guifg=#ffa0a0 guibg=bg 61 | hi Type gui=NONE guifg=NavajoWhite guibg=bg 62 | hi Underlined gui=underline guifg=fg guibg=bg 63 | 64 | " vim: sw=2 65 | -------------------------------------------------------------------------------- /text/vimfiles/colors/greyblue.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " 3 | 4 | set background=dark 5 | hi clear 6 | if exists("syntax_on") 7 | syntax reset 8 | endif 9 | 10 | let colors_name = "greyblue" 11 | 12 | hi Normal ctermfg=NONE ctermbg=NONE gui=NONE guifg=#b7af9f guibg=#090909 13 | 14 | " Search 15 | hi IncSearch ctermfg=NONE ctermbg=NONE gui=NONE guifg=#7800ff guibg=#e0d8ff 16 | hi Search ctermfg=NONE ctermbg=NONE gui=NONE guifg=#7800ff guibg=#e0d8ff 17 | 18 | " Messages 19 | hi ErrorMsg ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffffff guibg=NONE 20 | hi WarningMsg ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffffff guibg=NONE 21 | hi ModeMsg ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffffff guibg=NONE 22 | hi MoreMsg ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffffff guibg=NONE 23 | hi Question ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffffff guibg=NONE 24 | 25 | " Split area 26 | hi StatusLine ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#070707 guibg=#cfcfbf 27 | hi StatusLineNC ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#5f5f4f guibg=#cfcfbf 28 | hi VertSplit ctermfg=NONE ctermbg=NONE gui=NONE guifg=#070707 guibg=#cfcfbf 29 | hi WildMenu ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#070707 guibg=#ff5533 30 | 31 | " Diff 32 | hi DiffText ctermfg=NONE ctermbg=NONE gui=NONE guifg=#07cfef guibg=#00151f 33 | hi DiffChange ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ff97ff guibg=#2f002f 34 | hi DiffDelete ctermfg=NONE ctermbg=NONE gui=NONE guifg=#dfdf00 guibg=#370d15 35 | hi DiffAdd ctermfg=NONE ctermbg=NONE gui=NONE guifg=#dfdf00 guibg=#370d15 36 | 37 | " Cursor 38 | hi Cursor ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffff00 guibg=#7fff00 39 | hi lCursor ctermfg=NONE ctermbg=NONE gui=NONE guifg=#070707 guibg=#7fff00 40 | hi CursorIM ctermfg=NONE ctermbg=NONE gui=NONE guifg=#070707 guibg=#7fff00 41 | 42 | " Fold 43 | hi Folded ctermfg=NONE ctermbg=NONE gui=NONE guifg=#87ff00 guibg=#1f2700 44 | hi FoldColumn ctermfg=NONE ctermbg=NONE gui=NONE guifg=#559f00 guibg=#0f0f0b 45 | 46 | " Other 47 | hi Directory ctermfg=NONE ctermbg=NONE gui=NONE guifg=#aaaaba guibg=NONE 48 | hi LineNr ctermfg=NONE ctermbg=NONE gui=NONE guifg=#7f7f5f guibg=NONE 49 | hi NonText ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#211d1a guibg=#211d1a 50 | hi SpecialKey ctermfg=NONE ctermbg=NONE gui=NONE guifg=#378fff guibg=NONE 51 | hi Title ctermfg=NONE ctermbg=NONE gui=NONE guifg=#ffbf9f guibg=#370f07 52 | hi Visual ctermfg=NONE ctermbg=NONE gui=reverse guifg=#a5a5a5 guibg=#353535 53 | 54 | " Syntax group 55 | hi Comment ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#555565 guibg=NONE 56 | hi Constant ctermfg=NONE ctermbg=NONE gui=NONE guifg=#d1bfb1 guibg=#151515 57 | hi Error ctermfg=NONE ctermbg=NONE gui=NONE guifg=#00ffff guibg=NONE 58 | hi Identifier ctermfg=NONE ctermbg=NONE gui=NONE guifg=#aaaaba guibg=NONE 59 | hi Ignore ctermfg=NONE ctermbg=NONE gui=NONE guifg=NONE guibg=NONE 60 | hi PreProc ctermfg=NONE ctermbg=NONE gui=NONE guifg=NONE guibg=NONE 61 | hi Special ctermfg=NONE ctermbg=NONE gui=NONE guifg=#aa1565 guibg=NONE 62 | hi Statement ctermfg=NONE ctermbg=NONE gui=bold guifg=#d1bfb1 guibg=NONE 63 | hi Todo ctermfg=NONE ctermbg=NONE gui=NONE guifg=NONE guibg=NONE 64 | hi Type ctermfg=NONE ctermbg=NONE gui=BOLD guifg=#d1bfb1 guibg=NONE 65 | hi Underlined ctermfg=NONE ctermbg=NONE gui=UNDERLINE guifg=NONE guibg=NONE 66 | 67 | " HTML 68 | hi htmlLink gui=UNDERLINE guifg=#ffff00 guibg=NONE 69 | hi htmlBold gui=BOLD 70 | hi htmlBoldItalic gui=BOLD,ITALIC 71 | hi htmlBoldUnderline gui=BOLD,UNDERLINE 72 | hi htmlBoldUnderlineItalic gui=BOLD,UNDERLINE,ITALIC 73 | hi htmlItalic gui=ITALIC 74 | hi htmlUnderline gui=UNDERLINE 75 | hi htmlUnderlineItalic gui=UNDERLINE,ITALIC 76 | -------------------------------------------------------------------------------- /text/vimfiles/colors/hhazure.vim: -------------------------------------------------------------------------------- 1 | " Vim color file {{{1 2 | " Maintainer: hira@users.sourceforge.jp 3 | " Last Change: 2003/11/29 (Sat) 13:28:25. 4 | " Version: 1.2 5 | " This color scheme uses a dark background. 6 | 7 | " Happy Hacking color scheme {{{1 8 | set background=dark 9 | hi clear 10 | if exists("syntax_on") 11 | syntax reset 12 | endif 13 | let colors_name = expand(":t:r") 14 | let html_my_rendering = 1 15 | 16 | 17 | " frame & title & message (theme) {{{1 18 | hi VertSplit gui=underline guifg=bg guibg=#051525 19 | hi StatusLine gui=underline guifg=fg guibg=#051525 20 | hi StatusLineNC gui=underline guifg=#2c3c45 guibg=#051525 21 | hi LineNr gui=underline guifg=#54657d guibg=#051525 22 | hi Folded gui=none guifg=#54657d guibg=bg 23 | hi FoldColumn gui=none guifg=#54657d guibg=bg 24 | " title 25 | hi Title gui=underline guifg=fg guibg=#34455d 26 | " message 27 | hi MoreMsg gui=underline guifg=bg guibg=#329858 28 | hi Question gui=underline guifg=bg guibg=#329858 29 | 30 | hi Normal gui=none guifg=#7990a4 guibg=#152535 31 | hi NonText gui=underline guifg=#1d2d30 32 | hi NonText guibg=#1d2d30 33 | 34 | " cursor {{{1 35 | hi WildMenu gui=underline guifg=bg guibg=#99ccb5 36 | hi Cursor gui=underline guifg=bg guibg=#99ccb5 37 | hi IncSearch gui=underline guifg=bg guibg=#99ccb5 38 | hi CursorIM gui=underline guifg=fg guibg=#006188 39 | hi Search gui=underline guifg=bg guibg=#33669a 40 | hi Visual gui=underline guifg=bg guibg=#667888 41 | 42 | 43 | " message {{{1 44 | hi ErrorMsg gui=underline guifg=bg guibg=#8cdd66 45 | hi WarningMsg gui=underline guifg=bg guibg=#66cc6a 46 | hi ModeMsg gui=underline guifg=bg guibg=#339599 47 | 48 | 49 | " inner {{{1 50 | hi Ignore gui=none guifg=bg guibg=bg 51 | hi Todo gui=underline guifg=bg guibg=#66cc6a 52 | hi Error gui=underline guifg=fg guibg=#884422 53 | hi Special gui=none guifg=#66bbb6 guibg=bg 54 | hi SpecialKey gui=none guifg=#6695cc guibg=bg 55 | hi Identifier gui=none guifg=#69be97 guibg=bg 56 | hi Constant gui=none guifg=#22887b guibg=bg 57 | hi Statement gui=none guifg=#74aa66 guibg=bg 58 | hi Comment gui=none guifg=#006188 guibg=bg 59 | hi Underlined gui=underline guifg=#826699 guibg=bg 60 | hi Directory gui=none guifg=#447760 guibg=bg 61 | hi PreProc gui=none guifg=#557767 guibg=bg 62 | hi Type gui=none guifg=#429999 guibg=bg 63 | 64 | 65 | " diff {{{1 66 | hi DiffText gui=underline guifg=bg guibg=#99ffd0 67 | hi DiffChange gui=underline guifg=bg guibg=#55aa83 68 | hi DiffDelete gui=none guifg=bg guibg=#22a5aa 69 | hi DiffAdd gui=underline guifg=bg guibg=#2ccc22 70 | 71 | 72 | " html {{{1 73 | hi htmlLink gui=underline guifg=#6696aa guibg=bg 74 | hi htmlBold gui=underline guifg=bg guibg=#74aa66 75 | hi htmlBoldUnderline gui=underline guifg=#74aa66 guibg=bg 76 | hi htmlItalic gui=underline guifg=bg guibg=#44ccc0 77 | hi htmlUnderlineItalic gui=underline guifg=#44ccc0 guibg=bg 78 | hi htmlBoldItalic gui=underline guifg=bg guibg=#33aa40 79 | hi htmlBoldUnderlineItalic gui=underline guifg=#33aa40 guibg=bg 80 | hi htmlUnderline gui=underline guifg=fg guibg=bg 81 | 82 | "}}}1 83 | " vim:set nowrap foldmethod=marker expandtab: 84 | -------------------------------------------------------------------------------- /text/vimfiles/colors/hhteal.vim: -------------------------------------------------------------------------------- 1 | " Vim color file {{{1 2 | " Maintainer: hira@users.sourceforge.jp 3 | " Last Change: 2003/11/29 (Sat) 13:28:25. 4 | " Version: 1.2 5 | " This color scheme uses a dark background. 6 | 7 | " Happy Hacking color scheme {{{1 8 | set background=dark 9 | hi clear 10 | if exists("syntax_on") 11 | syntax reset 12 | endif 13 | let colors_name = expand(":t:r") 14 | let html_my_rendering = 1 15 | 16 | 17 | " frame & title & message (theme) {{{1 18 | hi LineNr gui=underline guifg=#647564 guibg=#101c10 19 | hi Folded gui=none guifg=#647564 guibg=bg 20 | hi FoldColumn gui=none guifg=#647564 guibg=bg 21 | " title 22 | hi Title gui=underline guifg=fg guibg=#445544 23 | " message 24 | hi MoreMsg gui=underline guifg=bg guibg=#439832 25 | hi Question gui=underline guifg=bg guibg=#439832 26 | 27 | hi NonText gui=underline guifg=#202c20 guibg=#202c20 28 | hi VertSplit gui=underline guifg=bg guibg=#101c10 29 | hi StatusLine gui=underline guifg=fg guibg=#101c10 30 | hi StatusLineNC gui=underline guifg=#2c3c2c guibg=#101c10 31 | 32 | " cursor {{{1 33 | hi WildMenu gui=underline guifg=bg guibg=#99cc99 34 | hi Cursor gui=underline guifg=bg guibg=#99cc99 35 | hi IncSearch gui=underline guifg=bg guibg=#99cc99 36 | hi CursorIM gui=underline guifg=fg guibg=#008866 37 | hi Search gui=underline guifg=bg guibg=#339933 38 | hi Visual gui=underline guifg=bg guibg=#668866 39 | 40 | 41 | " message {{{1 42 | hi ErrorMsg gui=underline guifg=bg guibg=#ccdd66 43 | hi WarningMsg gui=underline guifg=bg guibg=#99cc66 44 | hi ModeMsg gui=underline guifg=bg guibg=#339966 45 | 46 | 47 | "TODO 48 | " inner {{{1 49 | hi Normal gui=none guifg=#88bb88 guibg=#223322 50 | hi Ignore gui=none guifg=bg guibg=bg 51 | hi Todo gui=underline guifg=bg guibg=#99cc66 52 | hi Error gui=underline guifg=fg guibg=#993333 53 | hi Special gui=none guifg=#66bb88 guibg=bg 54 | hi SpecialKey gui=none guifg=#66cccc guibg=bg 55 | hi Identifier gui=none guifg=#69be69 guibg=bg 56 | hi Constant gui=none guifg=#228844 guibg=bg 57 | hi Statement gui=none guifg=#99aa66 guibg=bg 58 | hi Comment gui=none guifg=#008866 guibg=bg 59 | hi Underlined gui=underline guifg=#666699 guibg=bg 60 | hi Directory gui=none guifg=#447744 guibg=bg 61 | hi PreProc gui=none guifg=#557755 guibg=bg 62 | hi Type gui=none guifg=#22bb66 guibg=bg 63 | 64 | 65 | " diff {{{1 66 | hi DiffText gui=underline guifg=bg guibg=#99ff99 67 | hi DiffChange gui=underline guifg=bg guibg=#55aa55 68 | hi DiffDelete gui=none guifg=bg guibg=#22aa66 69 | hi DiffAdd gui=underline guifg=bg guibg=#88cc22 70 | 71 | 72 | " html {{{1 73 | hi htmlLink gui=underline guifg=#66aa99 guibg=bg 74 | hi htmlBold gui=underline guifg=bg guibg=#99aa66 75 | hi htmlBoldUnderline gui=underline guifg=#99aa66 guibg=bg 76 | hi htmlItalic gui=underline guifg=bg guibg=#44cc77 77 | hi htmlUnderlineItalic gui=underline guifg=#44cc77 guibg=bg 78 | hi htmlBoldItalic gui=underline guifg=bg guibg=#66aa33 79 | hi htmlBoldUnderlineItalic gui=underline guifg=#66aa33 guibg=bg 80 | hi htmlUnderline gui=underline guifg=fg guibg=bg 81 | 82 | "}}}1 83 | " vim:set nowrap foldmethod=marker expandtab: 84 | -------------------------------------------------------------------------------- /text/vimfiles/colors/metacosm.vim: -------------------------------------------------------------------------------- 1 | " Vim color file 2 | " Maintainer: Robert Melton ( vim at metacosm dot dhs dot org ) 3 | " Last Change: 2004 June 19th 4 | 5 | 6 | " ----------------------------------------------------------------------------- 7 | " This color scheme uses a dark grey background. 8 | " This theme, based on evening (with some input from Torte) is designed to 9 | " seperate active text (code) from background/line numbers/folds/listchars by 10 | " having different background colors on the non-code and the code (just 11 | " slightly). If you look at the screenshot below, you will get the idea. 12 | " All non-code(include indents) and string literals have a black background 13 | " while code has a very dark grey background. 14 | " ----------------------------------------------------------------------------- 15 | set background=dark 16 | hi clear 17 | if exists("syntax_on") 18 | syntax reset 19 | endif 20 | 21 | let colors_name = "metacosm" 22 | 23 | 24 | " ----------------------------------------------------------------------------- 25 | " Primary (hyper/selected/colored background) 26 | " ----------------------------------------------------------------------------- 27 | " Search 28 | hi IncSearch guibg=black guifg=cyan 29 | hi Search guibg=black guifg=cyan 30 | 31 | " Visual 32 | hi Visual guibg=black guifg=yellow 33 | hi VisualNOS guibg=black guifg=yellow gui=underline 34 | 35 | " Borders 36 | hi StatusLine guibg=black guifg=white 37 | hi StatusLineNC guibg=grey22 guifg=grey45 38 | hi VertSplit guibg=black guifg=grey45 39 | 40 | " Cursors 41 | hi Cursor guibg=white guifg=black 42 | hi lCursor guibg=white guifg=black 43 | 44 | " Diff 45 | hi DiffText guibg=red guifg=white gui=bold 46 | hi DiffAdd guibg=darkblue guifg=white 47 | hi DiffChange guibg=darkmagenta guifg=white 48 | hi DiffDelete guibg=darkcyan guifg=blue gui=bold 49 | 50 | " Misc 51 | hi Title guifg=magenta gui=bold 52 | hi Question guibg=black guifg=green gui=bold 53 | hi Todo guibg=black guifg=cyan 54 | hi Error guibg=red guifg=white 55 | hi WildMenu guibg=cyan guifg=black 56 | 57 | 58 | " ----------------------------------------------------------------------------- 59 | " Primary (active/code/text/grey background) 60 | " ----------------------------------------------------------------------------- 61 | " Normal 62 | hi Normal guibg=grey22 guifg=white 63 | 64 | " Constants 65 | hi Constant guibg=grey22 guifg=#ffa0a0 66 | hi String guibg=grey22 guifg=#ffa0a0 67 | hi Character guibg=grey22 guifg=#ffa0a0 68 | hi Number guibg=grey22 guifg=#ffa0a0 69 | hi Boolean guibg=grey22 guifg=#ffa0a0 70 | hi Float guibg=grey22 guifg=#ffa0a0 71 | 72 | " Identifier 73 | hi Identifier guibg=grey22 guifg=#40ffff 74 | hi Function guibg=grey22 guifg=#40ffff 75 | 76 | " Statement 77 | hi Statement guibg=grey22 guifg=#ffff60 78 | hi Conditional guibg=grey22 guifg=#ffff60 79 | hi Repeat guibg=grey22 guifg=#ffff60 80 | hi Label guibg=grey22 guifg=#ffff60 81 | hi Operator guibg=grey22 guifg=#ffff60 82 | hi Keyword guibg=grey22 guifg=#ffff60 83 | hi Exception guibg=grey22 guifg=#ffff60 84 | 85 | " PreProc 86 | hi PreProc guibg=grey22 guifg=#ff80ff 87 | hi Include guibg=grey22 guifg=#ff80ff 88 | hi Define guibg=grey22 guifg=#ff80ff 89 | hi Macro guibg=grey22 guifg=#ff80ff 90 | hi PreCondit guibg=grey22 guifg=#ff80ff 91 | 92 | " Type 93 | hi Type guibg=grey22 guifg=#60ff60 94 | hi StorageClass guibg=grey22 guifg=#60ff60 95 | hi Structure guibg=grey22 guifg=#60ff60 96 | hi Typedef guibg=grey22 guifg=#60ff60 97 | 98 | " Special 99 | hi Special guibg=grey22 guifg=orange 100 | hi SpecialChar guibg=grey22 guifg=orange 101 | hi Tag guibg=grey22 guifg=orange 102 | hi Delimiter guibg=grey22 guifg=orange 103 | hi Debug guibg=grey22 guifg=orange 104 | 105 | " Misc 106 | hi Underlined guibg=grey22 guifg=#ffff60 gui=underline 107 | 108 | 109 | " ----------------------------------------------------------------------------- 110 | " Secondary (inactive/black background) 111 | " ----------------------------------------------------------------------------- 112 | " Comments 113 | hi Comment guibg=black guifg=#80a0ff 114 | hi SpecialComment guibg=black guifg=#80a0ff gui=underline 115 | 116 | " Messages 117 | hi ModeMsg guibg=black guifg=white gui=bold 118 | hi MoreMsg guibg=black guifg=seagreen gui=bold 119 | hi WarningMsg guibg=black guifg=blue gui=bold 120 | hi ErrorMsg guibg=black guifg=red gui=bold 121 | 122 | " Folding 123 | hi Folded guibg=black guifg=grey45 124 | hi FoldColumn guibg=black guifg=grey45 125 | 126 | " Misc 127 | hi Ignore guibg=black guifg=grey45 128 | hi NonText guibg=black guifg=grey45 129 | hi LineNr guibg=black guifg=grey45 130 | hi SpecialKey guibg=black guifg=grey45 131 | hi SignColumn guibg=black guifg=grey45 132 | hi Directory guibg=black guifg=cyan 133 | -------------------------------------------------------------------------------- /text/vimfiles/colors/navajo-night.vim: -------------------------------------------------------------------------------- 1 | " Vim colour file 2 | " Maintainer: Matthew Hawkins 3 | " Last Change: Mon, 22 Apr 2002 15:28:04 +1000 4 | " URI: http://mh.dropbear.id.au/vim/navajo-night.png 5 | " 6 | " This colour scheme uses a "navajo-black" background 7 | " I have added colours for the statusbar and for spell checking 8 | " as taken from Cream (http://cream.sf.net/) 9 | 10 | 11 | set background=dark 12 | hi clear 13 | if exists("syntax_on") 14 | syntax reset 15 | endif 16 | 17 | let g:colors_name = "navajo-night" 18 | 19 | " This is the list of colour changes from Navajo that 20 | " weren't a simple mathematical subtraction from 0xffffff 21 | " DarkBlue -> #ffff74 22 | " DarkRed -> #74ffff 23 | " DarkGreen -> #ff9bff 24 | " DarkCyan -> #ff7474 25 | " DarkMagenta -> #74ff74 26 | " DarkYellow -> #7474ff 27 | " DarkGray -> #565656 28 | " Blue -> Yellow 29 | " Red -> Cyan 30 | " Yellow -> Blue 31 | " Gray -> #414141 32 | " Brown -> #5ad5d5 33 | " #ff8060 -> #007f9f 34 | " #f6e8d0 -> #09172f 35 | " #edb5cd -> #124a32 36 | " #c0c0c0 -> #3f3f3f 37 | " #907050 -> #6f8faf 38 | " #808080 -> #7f7f7f 39 | " #707070 -> #8f8f8f 40 | " SeaGreen -> #d174a8 41 | " LightRed (assuming #ee9090) -> #116f6f 42 | " LightBlue -> #522719 43 | 44 | hi Normal ctermfg=White guifg=White guibg=#35536f 45 | 46 | hi SpecialKey term=bold ctermfg=darkblue guifg=Yellow 47 | hi NonText term=bold ctermfg=darkblue cterm=bold gui=bold guifg=#7f7f7f 48 | hi Directory term=bold ctermfg=darkblue guifg=Yellow 49 | hi ErrorMsg term=standout ctermfg=grey ctermbg=darkred cterm=bold gui=bold guifg=Black guibg=Cyan 50 | hi IncSearch term=reverse cterm=reverse gui=reverse 51 | hi Search term=reverse ctermbg=White ctermfg=Black cterm=reverse guibg=Black guifg=Yellow 52 | hi MoreMsg term=bold ctermfg=green gui=bold guifg=#d174a8 53 | hi ModeMsg term=bold cterm=bold gui=bold 54 | hi LineNr term=underline ctermfg=darkcyan ctermbg=grey guibg=#7f7f7f gui=bold guifg=White 55 | hi Question term=standout ctermfg=darkgreen gui=bold guifg=#d174a8 56 | hi StatusLine term=bold,reverse cterm=bold,reverse gui=bold guifg=Black guibg=White 57 | hi StatusLineNC term=reverse cterm=reverse gui=bold guifg=#116f6f guibg=#8f8f8f 58 | hi VertSplit term=reverse cterm=reverse gui=bold guifg=Black guibg=#8f8f8f 59 | hi Title term=bold ctermfg=green gui=bold guifg=#74ff74 60 | "+++ Cream: 61 | "hi Visual term=reverse cterm=reverse gui=reverse guifg=#3f3f3f guibg=White 62 | "+++ 63 | hi VisualNOS term=bold,underline cterm=bold,underline gui=reverse guifg=#414141 guibg=Black 64 | hi WarningMsg term=standout ctermfg=darkred gui=bold guifg=Cyan 65 | hi WildMenu term=standout ctermfg=White ctermbg=darkyellow guifg=White guibg=Blue 66 | hi Folded term=standout ctermfg=darkblue ctermbg=grey guifg=White guibg=NONE guifg=#afcfef 67 | hi FoldColumn term=standout ctermfg=darkblue ctermbg=grey guifg=#ffff74 guibg=#3f3f3f 68 | hi DiffAdd term=bold ctermbg=darkblue guibg=Black 69 | hi DiffChange term=bold ctermbg=darkmagenta guibg=#124a32 70 | hi DiffDelete term=bold ctermfg=darkblue ctermbg=blue cterm=bold gui=bold guifg=#522719 guibg=#09172f 71 | hi DiffText term=reverse ctermbg=darkblue cterm=bold gui=bold guibg=#007f9f 72 | hi Cursor gui=reverse guifg=#bfbfef guibg=Black 73 | hi lCursor guifg=fg guibg=bg 74 | hi Match term=bold,reverse ctermbg=Blue ctermfg=Yellow cterm=bold,reverse gui=bold,reverse guifg=Blue guibg=Yellow 75 | 76 | 77 | " Colours for syntax highlighting 78 | hi Comment term=bold ctermfg=darkblue guifg=#e7e77f 79 | hi Constant term=underline ctermfg=darkred guifg=#3fffa7 80 | hi Special term=bold ctermfg=darkgreen guifg=#bfbfef 81 | hi Identifier term=underline ctermfg=darkcyan cterm=NONE guifg=#ef9f9f 82 | hi Statement term=bold ctermfg=darkred cterm=bold gui=bold guifg=#5ad5d5 83 | hi PreProc term=underline ctermfg=darkmagenta guifg=#74ff74 84 | hi Type term=underline ctermfg=green gui=bold guifg=#d174a8 85 | hi Ignore ctermfg=grey cterm=bold guifg=bg 86 | 87 | hi Error term=reverse ctermfg=grey ctermbg=darkred cterm=bold gui=bold guifg=Black guibg=Cyan 88 | hi Todo term=standout ctermfg=darkblue ctermbg=Blue guifg=Yellow guibg=Blue 89 | 90 | "+++ Cream: statusbar 91 | " Colours for statusbar 92 | "hi User1 gui=bold guifg=#565656 guibg=#0c0c0c 93 | "hi User2 gui=bold guifg=White guibg=#0c0c0c 94 | "hi User3 gui=bold guifg=Yellow guibg=#0c0c0c 95 | "hi User4 gui=bold guifg=Cyan guibg=#0c0c0c 96 | highlight User1 gui=bold guifg=#999933 guibg=#45637f 97 | highlight User2 gui=bold guifg=#e7e77f guibg=#45637f 98 | highlight User3 gui=bold guifg=Black guibg=#45637f 99 | highlight User4 gui=bold guifg=#33cc99 guibg=#45637f 100 | "+++ 101 | 102 | "+++ Cream: selection 103 | highlight Visual gui=bold guifg=Black guibg=#aacc77 104 | "+++ 105 | 106 | "+++ Cream: bookmarks 107 | highlight Cream_ShowMarksHL ctermfg=blue ctermbg=lightblue cterm=bold guifg=Black guibg=#aacc77 gui=bold 108 | "+++ 109 | 110 | "+++ Cream: spell check 111 | " Colour misspelt words 112 | "hi BadWord ctermfg=White ctermbg=darkred cterm=bold guifg=Yellow guibg=#522719 gui=bold 113 | " mathematically correct: 114 | "highlight BadWord ctermfg=black ctermbg=lightblue gui=NONE guifg=White guibg=#003333 115 | " adjusted: 116 | highlight BadWord ctermfg=black ctermbg=lightblue gui=NONE guifg=#ff9999 guibg=#003333 117 | "+++ 118 | 119 | 120 | -------------------------------------------------------------------------------- /text/vimfiles/colors/sienna.vim: -------------------------------------------------------------------------------- 1 | " Vim colour scheme 2 | " Maintainer: Georg Dahn 3 | " Last Change: 2 July 2005 4 | " Version: 1.3.1 5 | " 6 | " This color scheme has both light and dark styles with harmonic colors 7 | " easy to distinguish. Terminals are not supported, therefore you should 8 | " only try it if you use the GUI version of Vim. 9 | " 10 | " You can choose the style by adding one of the following lines to your 11 | " vimrc or gvimrc file before sourcing the color scheme: 12 | " 13 | " let g:sienna_style = 'dark' 14 | " let g:sienna_style = 'light' 15 | " 16 | " If none of above lines is given, the light style is choosen. 17 | " 18 | " You can switch between these styles by using the :Colo command, like 19 | " :Colo dark or :Colo light (many thanks to Pan Shizhu). 20 | 21 | if exists("g:sienna_style") 22 | let s:sienna_style = g:sienna_style 23 | else 24 | let s:sienna_style = 'light' 25 | endif 26 | 27 | execute "command! -nargs=1 Colo let g:sienna_style = \"\" | colo sienna" 28 | 29 | if s:sienna_style == 'dark' 30 | set background=dark 31 | elseif s:sienna_style == 'light' 32 | set background=light 33 | else 34 | finish 35 | endif 36 | 37 | hi clear 38 | if exists("syntax_on") 39 | syntax reset 40 | endif 41 | 42 | let g:colors_name = 'sienna' 43 | 44 | if s:sienna_style == 'dark' 45 | hi Normal gui=none guifg=Grey85 guibg=Grey25 46 | 47 | hi Cursor guifg=Black guibg=White 48 | hi FoldColumn gui=none guifg=Black guibg=Wheat3 49 | hi Folded gui=none guifg=White guibg=Wheat4 50 | hi IncSearch gui=none guifg=Grey25 guibg=Grey85 51 | hi LineNr gui=none guifg=Grey65 guibg=Grey25 52 | hi MoreMsg gui=bold guifg=PaleGreen3 53 | hi NonText gui=bold guifg=Grey65 guibg=Grey30 54 | hi Question gui=bold guifg=PaleGreen3 55 | hi SpecialKey gui=none guifg=RosyBrown3 56 | hi StatusLine gui=bold guifg=White guibg=DarkGray 57 | hi StatusLineNC gui=none guifg=White guibg=Black 58 | hi Title gui=bold guifg=White 59 | hi VertSplit gui=none guifg=White guibg=DimGray 60 | hi Visual gui=none guifg=Black guibg=LightSkyBlue1 61 | hi WarningMsg gui=bold guifg=Red 62 | hi Wildmenu gui=bold guifg=Black guibg=Yellow 63 | 64 | hi Comment gui=none guifg=LightSkyBlue3 65 | hi Constant gui=none guifg=PaleGreen3 66 | hi Identifier gui=none guifg=RosyBrown2 67 | hi Special gui=none guifg=RosyBrown3 68 | hi Statement gui=bold guifg=RosyBrown2 69 | hi Todo gui=bold,underline guifg=Black guibg=Yellow 70 | hi Type gui=bold guifg=LightSkyBlue2 71 | hi PreProc gui=none guifg=LightSkyBlue2 72 | elseif s:sienna_style == 'light' 73 | hi Normal gui=none guifg=Black guibg=White 74 | 75 | hi Cursor guifg=White guibg=RoyalBlue3 76 | hi FoldColumn gui=none guifg=Black guibg=Wheat2 77 | hi Folded gui=none guifg=Black guibg=Wheat1 78 | hi IncSearch gui=none guifg=White guibg=Black 79 | hi LineNr gui=none guifg=DarkGray guibg=White 80 | hi MoreMsg gui=bold guifg=ForestGreen 81 | hi NonText gui=bold guifg=DarkGray guibg=Grey95 82 | hi Question gui=bold guifg=ForestGreen 83 | hi SpecialKey gui=none guifg=Sienna3 84 | hi StatusLine gui=bold guifg=White guibg=Black 85 | hi StatusLineNC gui=none guifg=White guibg=DarkGray 86 | hi Title gui=bold guifg=Black 87 | hi VertSplit gui=none guifg=White guibg=DimGray 88 | hi Visual gui=none guifg=Black guibg=Sienna1 89 | hi WarningMsg gui=bold guifg=Red 90 | hi Wildmenu gui=bold guifg=Black guibg=Yellow 91 | 92 | hi Comment gui=none guifg=RoyalBlue3 93 | hi Constant gui=none guifg=ForestGreen 94 | hi Identifier gui=none guifg=Sienna4 95 | hi Special gui=none guifg=Sienna3 96 | hi Statement gui=bold guifg=Sienna4 97 | hi Todo gui=bold,underline guifg=Black guibg=Yellow 98 | hi Type gui=bold guifg=RoyalBlue4 99 | hi PreProc gui=none guifg=RoyalBlue4 100 | hi Underlined gui=underline guifg=Blue 101 | endif 102 | -------------------------------------------------------------------------------- /text/vimfiles/colors/timchase.vim: -------------------------------------------------------------------------------- 1 | " local syntax file - set colors on a per-machine basis: 2 | " Vim color file 3 | " Maintainer: Tim Chase 4 | " Last Change: 2003 Jan 23 5 | 6 | set background=dark 7 | hi clear 8 | if exists("syntax_on") 9 | syntax reset 10 | endif 11 | let g:colors_name = "timchase" 12 | hi Cursor guifg=Black guibg=White 13 | hi Visual guifg=gray guibg=Black 14 | hi FoldColumn guifg=#88ff88 guibg=#3c3c3c gui=bold 15 | hi Folded guifg=#88ff88 guibg=#3c3c3c gui=bold 16 | hi Normal guifg=gray guibg=black 17 | hi Comment term=bold ctermfg=DarkGray gui=italic guifg=DarkGray 18 | hi Constant term=underline ctermfg=white guifg=white 19 | hi Special term=bold ctermfg=DarkMagenta guifg=Red 20 | hi Identifier term=underline cterm=bold ctermfg=gray guifg=gray 21 | hi Statement term=bold ctermfg=Yellow gui=bold guifg=Yellow 22 | hi PreProc term=underline ctermfg=LightBlue guifg=#8888ff gui=bold 23 | hi Type term=underline ctermfg=Magenta guifg=purple 24 | hi Function term=bold ctermfg=White guifg=White 25 | hi Operator ctermfg=green guifg=green 26 | hi Ignore ctermfg=black guifg=bg 27 | hi String term=bold ctermfg=Cyan guifg=Cyan 28 | hi Error term=reverse ctermbg=Red ctermfg=White guibg=Red guifg=Yellow 29 | hi Todo ctermbg=Yellow ctermfg=Black guifg=Blue guibg=Yellow 30 | hi Number ctermfg=white guifg=white 31 | 32 | " Common groups that link to default highlighting. 33 | " You can specify other highlighting easily. 34 | hi link Character String 35 | hi link Boolean Constant 36 | hi link Float Number 37 | hi link Conditional Statement 38 | hi link Label Statement 39 | hi link Keyword Statement 40 | hi link Repeat Keyword 41 | hi link Exception Statement 42 | hi link Include PreProc 43 | hi link Define PreProc 44 | hi link Macro PreProc 45 | hi link PreCondit PreProc 46 | hi link StorageClass Type 47 | hi link Structure Type 48 | hi link Typedef Type 49 | hi link Tag Special 50 | hi link SpecialChar Operator 51 | hi link Delimiter Operator 52 | hi link SpecialComment Special 53 | hi link Debug Special 54 | -------------------------------------------------------------------------------- /text/vimfiles/filetype.vim: -------------------------------------------------------------------------------- 1 | " my filetype file 2 | if exists("did_load_filetypes") 3 | finish 4 | endif 5 | augroup filetype 6 | au! BufRead,BufNewFile *.prg setfiletype eviews 7 | au! BufRead,BufNewFile *.gau setfiletype gauss 8 | au! BufRead,BufNewFile *.mma setfiletype mma 9 | au! BufRead,BufNewFile *.nlogo setfiletype netlogo 10 | au! BufRead,BufNewFile *.nlogo3d setfiletype netlogo 11 | au! BufRead,BufNewFile *.nls setfiletype netlogo 12 | augroup END 13 | 14 | -------------------------------------------------------------------------------- /text/vimfiles/ftplugin/mail_ai.vim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/text/vimfiles/ftplugin/mail_ai.vim -------------------------------------------------------------------------------- /text/vimfiles/ftplugin/python_ai.vim: -------------------------------------------------------------------------------- 1 | " Only do this when not done yet for this buffer 2 | if exists("b:loaded_python_ai") 3 | finish 4 | endif 5 | 6 | setlocal formatoptions-=t formatoptions+=rol 7 | setlocal tabstop=4 shiftwidth=4 smarttab expandtab autoindent backspace=indent,eol,start 8 | setlocal iskeyword=a-z,A-Z,48-57,_ 9 | -------------------------------------------------------------------------------- /text/vimfiles/ftplugin/rst_ai.vim: -------------------------------------------------------------------------------- 1 | " reStructuredText filetype plugin file 2 | " Language: reStructuredText 3 | " Maintainer: Alan Isaac 4 | " Last Modified: 15th June 2009 5 | 6 | " Only do this when not done yet for this buffer 7 | if exists("b:loaded_rst_ai") 8 | finish 9 | endif 10 | " Don't reload plugin for this buffer 11 | let b:loaded_rst_ai=1 12 | 13 | setl fileencoding=utf-8 14 | colorscheme koehler 15 | 16 | " add suffixes to gf searches 17 | set suffixesadd=.rst 18 | 19 | setl shiftwidth=3 20 | setl tabstop=3 21 | 22 | "section motion for .rst files (redefines section commands) 23 | " (keeppattern prevent altering the search history) 24 | nmap [[ k$:keeppattern ?^=\+$k 25 | nmap ]] j$:keeppattern /^=\+$k 26 | vmap [[ k$?^=\+$k 27 | vmap ]] j$/^=\+$k 28 | 29 | -------------------------------------------------------------------------------- /text/vimfiles/ftplugin/tex_ai.vim: -------------------------------------------------------------------------------- 1 | " Vim filetype plugin file 2 | " Language: LaTeX 3 | " Maintainer: Alan Isaac 4 | " Last Modified: 15th October 2002 5 | 6 | " Only do this when not done yet for this buffer 7 | if exists("b:loaded_tex_ai") 8 | finish 9 | endif 10 | " Don't reload plugin for this buffer 11 | let b:loaded_tex_ai=1 12 | 13 | let s:cpo_save=&cpo 14 | set cpo&vim 15 | colorscheme koehler 16 | 17 | " add suffixes to gf searches 18 | set suffixesadd=.tex 19 | 20 | " LaTeX comment formatting 21 | setlocal comments=b:% 22 | "setlocal formatoptions-=t formatoptions+=rol 23 | setlocal formatoptions=q 24 | 25 | " Define patterns for the matchit macro 26 | if !exists("b:match_words") 27 | let b:match_ignorecase = 0 28 | let b:match_words = '\begin:\end' 29 | endif 30 | 31 | set cpo-=C 32 | set cpo+=B 33 | 34 | " Define patterns for the browse file filter 35 | if has("gui_win32") && !exists("b:browsefilter") 36 | let b:browsefilter = "LaTeX Files (*.tex)\t*.tex\n" . 37 | \ "Aux Files (*.aux)\t*.aux\n" . 38 | \ "Log Files (*.log)\t*.log\n" . 39 | \ "BibTeX Files (*.bib)\t*.bib\n" . 40 | \ "BibTeX Log Files (*.blg)\t*.blg\n" . 41 | \ "All Files (*.*)\t*.*\n" 42 | endif 43 | 44 | 45 | " ************* LaTeX environments ****************** 46 | imap ;be ciw\begin{}\end{}"-Pk$"-Po 47 | imap *be ciw\begin{}\end{}"-Pi*k$"-Pi*o 48 | imap ;bm \begin{bmatrix}\end{bmatrix}O\\I 49 | imap ;en \begin{enumerate}\end{enumerate}kO\item 50 | imap ;al \begin{align}\\\end{align}kO&= 51 | imap *al \begin{align*}\\\end{align*}kO&= 52 | imap ;eq \begin{equation}\end{equation}O 53 | imap *eq \begin{equation*}\end{equation*}O 54 | imap ;sp \begin{split}\end{split}O&= 55 | imap ;ml \begin{multline}\end{multline}O 56 | imap *ml \begin{multline*}\end{multline*}O 57 | imap ;ga \begin{gather}\end{gather}O 58 | imap *ga \begin{gather*}\end{gather*}O 59 | imap ;fn %\footnote{%}%-i 60 | vmap ;fn "xc%\footnote{%}%-"xP 61 | imap ;it \begin{itemize}\end{itemize}kO\item 62 | imap ;tr \begin{tabular}{cc}\hline\hline\hline\end{tabular}kkkO 63 | imap ;th \begin{theorem}\end{theorem}\begin{mbProof}\end{mbProof}3kO 64 | 65 | "Greek letters 66 | map! 'ga \alpha 67 | map! 'gb \beta 68 | map! 'gc \chi 69 | map! 'gC \Chi 70 | map! 'gd \delta 71 | map! 'gD \Delta 72 | map! 'ge \varepsilon 73 | map! 'gf \phi 74 | map! 'gF \Phi 75 | map! 'gg \gamma 76 | map! 'gG \Gamma 77 | map! 'gh \eta 78 | map! 'gi \iota 79 | map! 'gj \varphi 80 | map! 'gk \kappa 81 | map! 'gl \lambda 82 | map! 'gL \Lambda 83 | map! 'gm \mu 84 | map! 'gn \nu 85 | " map! 'go \omicron 86 | map! 'gp \pi 87 | map! 'gP \Pi 88 | map! 'gq \theta 89 | map! 'gr \rho 90 | map! 'gR \Rho 91 | map! 'gs \sigma 92 | map! 'gS \Sigma 93 | map! 'gt \tau 94 | map! 'gu \upsilon 95 | map! 'gw \omega 96 | map! 'gW \Omega 97 | map! 'gx \xi 98 | map! 'gX \Xi 99 | map! 'gy \psi 100 | map! 'gY \Psi 101 | map! 'gz \zeta 102 | map! 'gZ \Zeta 103 | 104 | " LaTeX math 105 | imap ;ht ="\\hat{".input("hat:")."}" 106 | vmap ;ht "xc\hat{}"xP 107 | imap ;br ="\\bar{".input("bar:")."}" 108 | imap ;dt ="\\dot{".input("dot:")."}" 109 | imap ;bf ="\\mathbf{".input("bold:")."}" 110 | vmap ;bf "xc\mathbf{}"xP 111 | map! ;fa \forall 112 | map! ;sm \setminus 113 | map! ;ex \exists 114 | map! ;cd \centerdot 115 | map! ;im \implies 116 | map! ;pa \partial 117 | " sum with limits 118 | imap ;sl ="\\sum_{".input("from:")."}^{".input("to:")."}" 119 | " sum with lower limit 120 | imap ;s_ ="\\sum_{".input("from:")."}" 121 | imap ;_ ="_{".input("sub:")."}" 122 | imap ="_{".input("sub:")."}" 123 | imap ;^ ="^{".input("sup:")."}" 124 | imap ="^{".input("sup:")."}" 125 | imap ;fr ="\\frac{".input("top:")."}{".input("bot:")."}" 126 | vmap ;fr "xc\frac{}"xPla{}i 127 | imap ;em ="\\emph{".input("emphasized text: ")."}" 128 | nmap ;em "xciw\emph{}"xP 129 | vmap ;em "xc\emph{}"xP 130 | imap ;mc ="\\mathcal{".input("caligraphic text: ")."}" 131 | vmap ;rm "xc\mathrm{}"xP 132 | imap ;tt ="\\texttt{".input("text: ")."}" 133 | nmap ;tt "xciw\texttt{}"xP 134 | vmap ;tt "xc\texttt{}"xP 135 | cmap ;tt \texttt{ 136 | imap ;qq \qquad 137 | imap ;a} /}a 138 | imap ;ch ="\\chapter{".input("chapter title: ")."}" 139 | imap ;sec ="\\section{".input("section title: ")."}" 140 | imap ;ssec ="\\subsection{".input("subsection title: ")."}" 141 | imap ;sssec ="\\subsubsection{".input("subsubsection title: ")."}" 142 | imap ;la ="\\label{".input("label name: ")."}" 143 | 144 | " centering better than center env., which adds vertical space 145 | imap ;fgr \begin{figure}[tbp]\centering\includegraphics[width=\textwidth]{}\caption{}\label{f:}\end{figure} 146 | imap ;tbl \begin{table}[btp]\caption{}\label{t:}\centering\begin{tabular}{cc}\toprule\bottomrule\end{tabular}\end{table}?:a 147 | 148 | "section motion for .tex files (redefines the usual section commands) 149 | map [[ k$?\\\(sub\)*section[[{] 150 | map ]] /\\\(sub\)*section[[{] 151 | 152 | if exists("g:loaded_global_tex_ai") 153 | let &cpo = s:cpo_save 154 | finish 155 | endif 156 | let g:loaded_global_tex_ai = 1 157 | 158 | 159 | let &cpo = s:cpo_save 160 | sy region aitexComment matchgroup=aitexComment start=/\\begin{comment}/ end=/\\end{comment})/ contained 161 | hi aitexComment ctermfg=gray guifg=gray 162 | "EOF 163 | 164 | -------------------------------------------------------------------------------- /text/vimfiles/share_vimrc.vim: -------------------------------------------------------------------------------- 1 | " NOTE: 2 | " If you like these settings, proceed as follows. 3 | " i. copy this file into your vimfiles folder 4 | " (which was created upon installation), and 5 | " ii. source this file from your _vimrc file 6 | " E.g., add the following line to your _vimrc file: 7 | " source $VIM/vimfiles/share_vimrc 8 | 9 | "act like Vim not like vi 10 | set nocompatible 11 | 12 | " **IF** you love Windows behavior 13 | " uncomment the next line (*if* it's not already in your _vimrc) 14 | "source $VIMRUNTIME/mswin.vim 15 | "remap keys for MS mouse behavior 16 | behave mswin 17 | set keymodel=startsel 18 | " Switch syntax highlighting on, when the terminal has colors 19 | if &t_Co > 2 || has("gui_running") 20 | syntax on 21 | endif 22 | 23 | "set working directory to current directory 24 | set autochdir 25 | "au BufNewFile,BufEnter * silent! lcd %:p:h 26 | " if you prefer to do this manually, here is a map to 27 | " change to directory of current buffer (see :help filename-modifiers) 28 | " map ,cd :cd %:p:h 29 | 30 | " allow cursor wrapping except with h and l 31 | set whichwrap=b,s<,>,[,] 32 | " display last-line even if long (vs. seeing @@) 33 | set display=lastline 34 | "set valid characters for filenames 35 | set isf=@,48-57,/,\\,.,-,_,+,,,$,%,[,],:,@-@,!,~,= 36 | "disable maximum linewidth 37 | set textwidth=0 38 | "set long lines to wrap, breaking at whitespace 39 | set wrap linebreak 40 | " turn off automatic highlighting during search 41 | set nohls 42 | " allow backspacing over everything in insert mode 43 | set backspace=indent,eol,start 44 | set history=50 " keep 50 lines of command line history 45 | set ruler " show the cursor position all the time 46 | set cmdheight=2 47 | " allow hidden windows 48 | set hidden 49 | " maintain indent on new lines 50 | filetype indent off 51 | set autoindent 52 | " ignore case for searches *unless* type caps (smartcase) 53 | set ignorecase 54 | set smartcase 55 | " set file browser directory 56 | set browsedir=buffer 57 | " Make p in Visual mode replace the selected text with the "" register. 58 | vnoremap p :let current_reg = @"gvs=current_reg 59 | " When editing a file, always jump to the last known cursor position. 60 | " Don't do it when the position is invalid or when inside an event handler 61 | " (happens when dropping a file on gvim). 62 | autocmd BufReadPost * 63 | \ if line("'\"") > 0 && line("'\"") <= line("$") | 64 | \ exe "normal g`\"" | 65 | \ endif 66 | 67 | -------------------------------------------------------------------------------- /text/vimfiles/spell/en.latin1.add: -------------------------------------------------------------------------------- 1 | assortative 2 | vivos 3 | Gini 4 | -------------------------------------------------------------------------------- /text/vimfiles/spell/en.latin1.add.spl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/text/vimfiles/spell/en.latin1.add.spl -------------------------------------------------------------------------------- /text/vimfiles/spell/en.utf-8.add: -------------------------------------------------------------------------------- 1 | Eswaran 2 | Kotwal 3 | redistributive 4 | tradeoff 5 | agro-industrial 6 | monopsony 7 | monopsonistic 8 | oligopsonistic 9 | parameterization 10 | differentiable 11 | maximizers 12 | parameterizing 13 | Gini 14 | maximand 15 | nonnegativity 16 | maximizer 17 | nonnegative 18 | parameterized 19 | numpy 20 | SciPy 21 | MINPACK's 22 | parameterizations 23 | subfigure 24 | misallocation 25 | counterintuitive 26 | intramarginal 27 | underperforming 28 | monopsonist's 29 | Inframarginal 30 | Macal 31 | NetLogo 32 | Sugarscape 33 | NetLogo's 34 | BehaviorSpace 35 | Railsback 36 | Calibri 37 | monospaced 38 | Andale 39 | Axtell 40 | endogenize 41 | Axelrod 42 | Todaro 43 | Wilensky 44 | wealths 45 | agentset 46 | sublist 47 | PNG 48 | Verhulst 49 | harvestable 50 | harvestability 51 | iterable 52 | disconfirming 53 | Tesfatsion 54 | stochasticity 55 | Tukey 56 | nonmonotonic 57 | agri-food 58 | nonmonotonicity 59 | monopsonist 60 | delisting 61 | intermediation 62 | replicability 63 | pseudocode 64 | presentational 65 | jobseekers 66 | Kalecki 67 | microfoundations 68 | Econophysics 69 | macromodel 70 | econophysics 71 | macromodels 72 | macroeconomy 73 | Econophysicists 74 | macroeconomists 75 | microstate 76 | macrostate 77 | lognormal 78 | detrended 79 | lognormally 80 | neoclassically 81 | U6 82 | prima 83 | facie 84 | UML 85 | serodiscordant 86 | homophily 87 | seroconversions 88 | polygyny 89 | propogation/! 90 | epdiemic/! 91 | Protectivity 92 | protectivity 93 | Matplotlib 94 | DropBox 95 | agentsets 96 | Kirman 97 | JSTOR 98 | #ireFox 99 | FireFox/! 100 | Farol 101 | LeBaron 102 | Gode 103 | Solow 104 | EViews 105 | Stata 106 | gretl 107 | interquartile 108 | durations 109 | seroconversion 110 | seropositive 111 | quartiles 112 | intertemporal 113 | Jarque-Bera 114 | assortative 115 | redistributional 116 | Piketty 117 | fractile 118 | nonparametric 119 | TOML 120 | INI 121 | parsers 122 | prised 123 | lingua franca 124 | nonprogrammers 125 | octothorpe 126 | reproducibility 127 | programmatically 128 | multiline 129 | univariate 130 | YAML 131 | JSON 132 | superset 133 | syntaxes 134 | writability 135 | MONIAC 136 | decumulation 137 | tradable 138 | nullcline 139 | nullclines 140 | probhibitively/! 141 | redistributionist 142 | perdure 143 | perdures 144 | preannounced 145 | exogeneity 146 | temporality 147 | nonlocal 148 | nonlinearity 149 | hardcoding 150 | dropdown 151 | hardcoded 152 | -------------------------------------------------------------------------------- /text/vimfiles/spell/en.utf-8.add.spl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alan-isaac/econpy/f63cfe582888274aa1d7eaf40af13aeee792604e/text/vimfiles/spell/en.utf-8.add.spl -------------------------------------------------------------------------------- /text/vimfiles/syntax/eviews.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " Language: EViews 3 | " Maintainer: Alan Isaac 4 | " URL: http://www.american.edu/econ/notes/eviews.vim 5 | " Last Change: 2002 March 30 6 | 7 | 8 | " Remove any old syntax stuff hanging around 9 | syn clear 10 | syn case ignore 11 | 12 | if !exists("main_syntax") 13 | let main_syntax = 'eviews' 14 | endif 15 | 16 | let b:current_syntax = "eviews" 17 | 18 | sy region eVrPar3 matchgroup=eVrPar3 start=/(/ end=/)/ contains=ALLBUT,eVmParenError contained 19 | sy region eVrPar2 matchgroup=eVrPar2 start=/(/ end=/)/ contains=eVrPar3,eVmOperator,eVmCtr,eVmStringVar,eVrBraces contained 20 | sy region eVrPar1 matchgroup=eVrPar1 start=/(/ end=/)/ contains=eVrPar2,eVmOperator,eVmCtr,eVmStringVar,eVrBraces 21 | hi eVrPar1 ctermfg=darkgreen guifg=darkgreen 22 | hi eVrPar2 ctermfg=blue guifg=blue 23 | hi eVrPar3 ctermfg=red guifg=red 24 | 25 | syn match eVmLineComment "'.*$" 26 | syn match eVmNumber "=\=\s*-\=\d\+\.\=\d*" 27 | syn match eVmOperator "[*/+-><^]" 28 | syn match eVmStringVar "%[a-zA-Z0-9]\+" 29 | syn match eVmCtr "{\=![a-zA-Z0-9]\+}\=" 30 | syn region eVRepeat start="for\s\+" skip="'.*$" end="next" contains=ALL 31 | syn region eVStringD start=+"+ skip=+\\\\\|\\"+ end=+"+ 32 | syn region eVStringL matchgroup=eVrPar1 start='[dt]([^-]*)' end=+$+ contains=eVmLineComment,eVmOperator,eVkOperator keepend 33 | syn keyword eVkConditional if then else endif 34 | syn keyword eVkRepeat while wend for to next exitloop 35 | syn keyword eVkOperator and or 36 | syn keyword eVkFunction subroutine 37 | syn keyword eVkBoolean true false 38 | 39 | " catch errors caused by wrong parenthesis 40 | syn region eVrParen transparent start="(" end=")" contains=ALLBUT,eVmParenError 41 | syn match eVmParenError ")" 42 | syn region eVrBraces transparent start="{" end="}" contains=ALLBUT,eVmBracesError 43 | syn match eVmBracesError "}" 44 | syn region eVrBracket transparent start="[[]" end="]" contains=ALLBUT,eVmBracketError 45 | syn match eVmBracketError "]" 46 | 47 | syn keyword eVkObject graph group matrix pool table series scalar var vector text equation workfile sym 48 | hi eVkObject ctermfg=blue guifg=red 49 | syn keyword eVkUnitHeader call function program local subroutine 50 | syn keyword eVkStatement return stop 51 | 52 | syn keyword eVkStatement add align append ar arch archtest auto 53 | syn keyword eVkStatement bar 54 | syn keyword eVkStatement cause ccopy cd cdfplot ceiling censored cfetch chow clabel close coef coefcov coint copy cor correl correlsq count cov cross cusum 55 | syn keyword eVkStatement dbcopy dbcreate dbdelete dbopen dbpack dbrebuild dbrename dbrepair decomp define delete describe driconvert drop dtable 56 | syn keyword eVkStatement ec endog expand 57 | syn keyword eVkStatement fetch fill fiml fit freeze freq 58 | syn keyword eVkStatement garch genr gmm 59 | syn keyword eVkStatement hconvert hilo hist hpf 60 | syn keyword eVkStatement impulse include 61 | syn keyword eVkStatement kdensity kerfit 62 | syn keyword eVkStatement label line linefit ls lstyle 63 | syn keyword eVkStatement ma makeendog makegarch makegroup makelimit makemodel makeregs makeresid makestat makestate makesystem metafile ml model mtos 64 | syn keyword eVkStatement name nnfit nrnd 65 | syn keyword eVkStatement option ordered 66 | syn keyword eVkStatement param pdl pi pie poff pon predict print 67 | syn keyword eVkStatement qqplot 68 | syn keyword eVkStatement range rename reset residcor residcov resids results rls rnd rndint rndseed 69 | syn keyword eVkStatement sar scale scat scatmat seas set setcell setcolwidth setconvert setelem setline shade sheet show sma smooth smpl solve sort spec sspace statby state stats statusline stom stomna sur 70 | syn keyword eVkStatement testadd testbtw testby testdrop testfit teststat tsls 71 | syn keyword eVkStatement uroot 72 | syn keyword eVkStatement wald white wls write wtsls 73 | syn keyword eVkStatement x11 xy 74 | syn keyword eVkStatement @aic @all @cchisq @coefcov @coefs @count @dw @f @first @jstat @last @left @logl @meandep @ncoef @obs @qchisq @r2 @rbar2 @regobs @right @schwarz @sddep @se @seriesname @ssr @stderrs @str @strlen @sysncoef @trend @tstats 75 | syn keyword eVkStatement addtext call create displayname exit legend load merge new open read run sample save step stop store system 76 | syn keyword eVkOperator d log dlog 77 | syn keyword eVkOption dat mult na skiprow rect t 78 | 79 | syn match eVkUnitHeader "end\s*sub" 80 | 81 | if !exists("did_eviews_syntax_inits") 82 | let did_eviews_syntax_inits = 1 83 | hi link eVmLineComment Comment 84 | hi link eVStringD String 85 | hi link eVStringL String 86 | hi link eVStringA String 87 | hi link eVmNumber eVValue 88 | hi link eVkConditional Conditional 89 | hi link eVkRepeat Repeat 90 | hi link eVkBranch Conditional 91 | hi link eVkOperator Operator 92 | hi link eVmOperator Operator 93 | hi link eVmStringVar Identifier 94 | hi link eVmCtr Identifier 95 | hi link eVkType Type 96 | hi link eVkStatement Statement 97 | hi link eVkFunction Function 98 | hi link eVrBraces Function 99 | hi link eVrBracket Function 100 | hi link eVError Error 101 | hi link eVmParenError eVError 102 | hi link eVmBracesError eVError 103 | hi link eVmBracketError eVError 104 | hi link eVInParen eVError 105 | hi link eVBoolean Boolean 106 | endif 107 | 108 | let b:current_syntax = "eviews" 109 | if main_syntax == 'eviews' 110 | unlet main_syntax 111 | endif 112 | 113 | " vim: ts=8 114 | -------------------------------------------------------------------------------- /text/vimfiles/syntax/gauss.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " Language: GAUSS 3 | " Maintainer: Alan Isaac 4 | " URL: http://www.american.edu/econ/notes/gauss.vim 5 | " Last Change: 2002 March 30 6 | 7 | 8 | " Remove any old syntax stuff hanging around 9 | syn clear 10 | syn case ignore 11 | 12 | if !exists("main_syntax") 13 | let main_syntax = 'gauss' 14 | endif 15 | 16 | 17 | 18 | 19 | 20 | " StringEsc = \ 21 | 22 | 23 | 24 | sy region GAUrPar3 matchgroup=GAUrPar3 start=/(/ end=/)/ contains=ALLBUT,GAUmParenError contained 25 | sy region GAUrPar2 matchgroup=GAUrPar2 start=/(/ end=/)/ contains=GAUrPar3,GAUmOperator,GAUmCtr,GAUmStringVar,GAUrBraces contained 26 | sy region GAUrPar1 matchgroup=GAUrPar1 start=/(/ end=/)/ contains=GAUrPar2,GAUmOperator,GAUmCtr,GAUmStringVar,GAUrBraces 27 | hi GAUrPar1 ctermfg=darkgreen guifg=darkgreen 28 | hi GAUrPar2 ctermfg=blue guifg=blue 29 | hi GAUrPar3 ctermfg=red guifg=red 30 | 31 | 32 | " won't work because of operators; see c.vim 33 | syntax region GAUmComment matchgroup=CommentStart start="/\*" matchgroup=NONE end="\*/" 34 | syntax region GAUmComment2 matchgroup=CommentStart start="@" matchgroup=NONE end="@" 35 | syntax match GAUmPreProc "#\S\+" 36 | syn match GAUmNumber "=\=\s*-\=\d\+\.\=\d*" 37 | syn match GAUmOperator "[*/+-><^!~%^&|=.:;,$?]" 38 | syn region GAURepeat start="for\s*(" skip="'.*$" end="endfor" contains=ALL 39 | syn region GAUStringD start=+"+ skip=+\\\\\|\\"+ end=+"+ 40 | syn keyword GAUkConditional if then else endif elseif 41 | syn keyword GAUkRepeat while for do endo endfor 42 | syn keyword GAUkOperator and or .and .or 43 | 44 | " catch errors caused by wrong parenthesis 45 | syn region GAUrParen transparent start="(" end=")" contains=ALLBUT,GAUmParenError 46 | syn match GAUmParenError ")" 47 | syn region GAUrBraces transparent start="{" end="}" contains=ALLBUT,GAUmBracesError 48 | syn match GAUmBracesError "}" 49 | syn region GAUrBracket transparent start="[[]" end="]" contains=ALLBUT,GAUmBracketError 50 | syn match GAUmBracketError "]" 51 | 52 | syn keyword GAUkDeclare call fn proc local 53 | syn keyword GAUkStatement return stop 54 | 55 | syn keyword GAUkStatement _daypryr _dstatd _dstatx _isleap 56 | syn keyword GAUkStatement abs arccos arcsin arctan arctan2 asclabel atan atan2 axmargin 57 | syn keyword GAUkStatement balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar base10 begwind besselj bessely box break 58 | syn keyword GAUkStatement call cdfbeta cdfbvn cdfbvn2 cdfbvn2e cdfchic cdfchii cdfchinc cdffc cdffnc cdfgam cdfmvn cdfn cdfn2 cdfnc cdfni cdftc cdftci cdftnc cdftvn cdir ceil cfft cffti ChangeDir chdir chol choldn cholsol cholup chrs cint clear clearg close closeall cls cmadd cmcplx cmcplx2 cmdiv cmemult cmimag cminv cmmult cmreal cmsoln cmsub cmtrans code color cols colsf comlog compile complex con cond conj cons continue contour conv coreleft corrm corrvc corrx cos cosh counts countwts create crossprd crout croutp csrcol csrlin csrtype cumprodc cumsumc 59 | syn keyword GAUkStatement datalist date datestr datestring datestrymd dayinyr debug declare delete delif denseSubmat design det detl dfft dffti dfree diag diagrv disable dlibrary dllcall dos doswin DOSWinCloseall DOSWinOpen draw dstat dummy dummybr dummydn 60 | syn keyword GAUkStatement ed edit editm eig eigcg eigcg2 eigch eigch2 eigh eighv eigrg eigrg2 eigrs eigrs2 eigv enable end endp endwind envget eof eqSolve erf erfc error errorlog etdays ethsec etstr exctsmpl exec exp export exportf external eye 61 | syn keyword GAUkStatement fcheckerr fclearerr feq fflush fft ffti fftm fftmi fftn fge fgets fgetsa fgetsat fgetst fgt fileinfo files filesa fix fle floor flt fmod fne fonts fopen for format formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos 62 | syn keyword GAUkStatement gamma gammaii gausset getf getname getnr getpath getwind gosub goto gradp graph graphprt graphset 63 | syn keyword GAUkStatement hardcopy hasimag header hess hessp hist histf histp hsec 64 | syn keyword GAUkStatement if imag import importf indcv indexcat indices indices2 indnv int intgrat2 intgrat3 intquad1 intquad2 intquad3 intrleav intrsect intsimp inv invpd invswp iscplx iscplxf ismiss isSparse 65 | syn keyword GAUkStatement key keyw keyword 66 | syn keyword GAUkStatement lag1 lagn let lib library line ln lncdfbvn lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lnpdfmvn lnpdfn load loadd loadf loadk loadm loadp loads loadwind local locate loess log loglog logx logy lower lowmat lowmat1 lpos lprint lpwidth lshow ltrisol lu lusol 67 | syn keyword GAUkStatement makevars makewind margin maxc maxindc maxvec mbesselei mbesselei0 mbesselei1 mbesseli mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc miss missex missrv moment momentd msym 68 | syn keyword GAUkStatement nametype ndpchk ndpclex ndpcntrl new nextn nextnevn nextwind null null1 69 | syn keyword GAUkStatement ols olsqr olsqr2 ones open optn optnevn orth output outwidth 70 | syn keyword GAUkStatement packr parse pause pdfn pi pinv plot plotsym polar polychar polyeval polyint polymake polymat polymult polyroot pop pqgwin prcsn print printdos printfm printfmt prodc putf 71 | syn keyword GAUkStatement QProg qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep 72 | syn keyword GAUkStatement rank rankindx readr real recode recserar recsercp recserrc replay rerun reshape retp rev rfft rffti rfftip rfftn rfftnp rfftp rndbeta rndcon rndgam rndmod rndmult rndn rndnb rndns rndp rndseed rndu rndus rndvm rotater round rows rowsf rref run 73 | syn keyword GAUkStatement save saveall saved savewind scale scale3d scalerr scalmiss schtoc schur screen scroll seekr selif seqa seqm setcnvrt setdif setvars setvmode setwind shell shiftr show sin sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind sortindc sortmc sparseCols sparseEye sparseFD sparseFP sparseHConcat sparseNZE sparseOnes sparseRows sparseSolve sparseSubmat sparseTD sparseTrTD sparseVConcat spline1D spline2D sqpSolve sqrt stdc stof strindx strlen strput strrindx strsect submat subscat substute sumc surface svd svd1 svd2 svdcusv svds svdusv sysstate system 74 | syn keyword GAUkStatement tab tan tanh tempname time timestr title toeplitz token trace trap trapchk trim trimr trunc type typecv typef 75 | syn keyword GAUkStatement union uniqindx unique until upmat upmat1 upper use utrisol 76 | syn keyword GAUkStatement vals varget vargetl varput varputl vartype vcm vcx vec vech vecr vget view viewxyz vlist vnamecv volume vput vread vtypecv 77 | syn keyword GAUkStatement wait waitc window writer 78 | syn keyword GAUkStatement xlabel xpnd xtics xy xyz 79 | syn keyword GAUkStatement ylabel ytics 80 | syn keyword GAUkStatement zeros zlabel ztics 81 | 82 | syn keyword GAUkStatement co coset coprt gradre gradfd gradcd cml cmlset cmlprt cmlclprt cmltlimits cmlhist cmldensity cmlboot cmlblimits cmlclimits cmlprofile cmlbayes cmlpflclimits 83 | 84 | 85 | " if !exists("did_gauss_syntax_inits") 86 | let did_gauss_syntax_inits = 1 87 | hi link GAUmComment Comment 88 | hi link GAUmComment2 Comment 89 | hi link GAUStringD String 90 | hi link GAUmNumber Float 91 | hi link GAUkRepeat Repeat 92 | hi link GAUkBranch Conditional 93 | hi link GAUkConditional Conditional 94 | hi link GAUkOperator Operator 95 | hi link GAUmOperator Operator 96 | hi link GAUmStringVar Identifier 97 | hi link GAUmCtr Identifier 98 | hi link GAUkType Type 99 | hi link GAUkStatement Statement 100 | hi link GAUmPreProc PreProc 101 | hi link GAUkDeclare Statement 102 | hi link GAUrBraces Function 103 | hi link GAUrBracket Function 104 | hi link GAUError Error 105 | hi link GAUmParenError GAUError 106 | hi link GAUmBracesError GAUError 107 | hi link GAUmBracketError GAUError 108 | hi link GAUInParen GAUError 109 | hi link GAUBoolean Boolean 110 | hi link CommentStart Special 111 | " endif 112 | 113 | 114 | let b:current_syntax = "gauss" 115 | if main_syntax == 'gauss' 116 | unlet main_syntax 117 | endif 118 | 119 | " vim: ts=8 120 | -------------------------------------------------------------------------------- /text/vimfiles/syntax/rest.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " Language: reStructuredText Documentation Format 3 | " Maintainer: Estienne Swart 4 | " URL: http://www.sanbi.ac.za/~estienne/vim/syntax/rest.vim 5 | " Latest Revision: 2004-04-26 6 | " 7 | " A reStructuredText syntax highlighting mode for vim. 8 | " (derived somewhat from Nikolai Weibull's 9 | " source) 10 | 11 | "TODO: 12 | " 0. Make sure that no syntax highlighting bleeding occurs! 13 | " 1. Need to fix up clusters and contains. 14 | " 2. Need to validate against restructured.txt.gz and tools/test.txt. 15 | " 3. Fixup superfluous matching. 16 | " 4. I need to figure out how to keep a running tally of the indentation in order 17 | " to enable block definitions, i.e. a block ends when its indentation drops 18 | " below that of the existing one. 19 | " 5. Define folding patterns for sections, etc. 20 | " 6. Setup a completion mode for target references to hyperlinks 21 | 22 | " Remove any old syntax stuff that was loaded (5.x) or quit when a syntax file 23 | " was already loaded (6.x). 24 | if version < 600 25 | syntax clear 26 | elseif exists("b:current_syntax") 27 | finish 28 | endif 29 | 30 | "syn match rstJunk "\\_" 31 | 32 | "ReStructuredText Text Inline Markup: 33 | syn region rstEmphasis start=+\*[^*]+ end=+\*+ 34 | syn region rstStrongEmphasis start=+\*\*[^*]+ end=+\*\*+ 35 | syn region rstInterpretedText start=+`[^`]+ end=+`+ contains=rstURL 36 | syn region rstInlineLiteral start="``" end="``" contains=rstURL 37 | "Using a syn region here causes too much to be highlighted. 38 | 39 | syn region rstSubstitutionReference start=+|\w+ end=+\w|+ skip=+\\|+ 40 | "I'm forcing matching of word characters before and after '|' in order to 41 | "prevent table matching (this causes messy highlighting) 42 | 43 | syn region rstGridTable start=/\n\n\s*+\([-=]\|+\)\+/ms=s+2 end=/+\([-=]\|+\)\+\n\s*\n/me=e-2 44 | 45 | syn match rstRuler "\(=\|-\|+\)\{3,120}" 46 | 47 | " syn match rstInlineInternalTarget "_`\_.\{-}`" 48 | syn region rstInlineInternalHyperlink start=+_`+ end=+`+ contains=rsturl 49 | " this messes up with InterpretedText 50 | 51 | syn match rstFootnoteReference "\[\%([#*]\|[0-9]\+\|#[a-zA-Z0-9_.-]\+\)\]_" 52 | "syn region rstCitationReference start=+\[+ end=+\]_+ 53 | "syn match rstCitationReferenceNothing +\[.*\]+ 54 | "TODO: fix Citation reference - patterns defined still cause "bleeding" 55 | "if end doesn't get matched, catch it first with another pattern - this is ugly??? 56 | syn match rstURL "\(acap\|cid\|data\|dav\|fax\|file\|ftp\|gopher\|http\|https\|imap\|ldap\|mailto\|mid\|modem\|news\|nfs\|nntp\|pop\|prospero\|rtsp\|service\|sip\|tel\|telnet\|tip\|urn\|vemmi\|wais\):[-./[:alnum:]_~@]\+" 57 | "I need a better regexp for URLs here. This doesn't cater for URLs that are 58 | "broken across lines 59 | 60 | " hyperlinks 61 | syn match rstHyperlinks /`[^`]\+`_/ 62 | "syn region rstHyperlinks start="`\w" end="`_" 63 | syn match rstExternalHyperlinks "\w\+_\w\@!" 64 | "This seems to overlap with the ReStructuredText comment?!? 65 | 66 | "ReStructuredText Sections: 67 | syn match rstTitle ".\{2,120}\n\(\.\|=\|-\|=\|`\|:\|'\|\"\|\~\|\^\|_\|\*\|+\|#\|<\|>\)\{3,120}" 68 | " [-=`:'"~^_*+#<>] 69 | "for some strange reason this only gets highlighted upon refresh 70 | 71 | "syn match rstTitle "\w.*\n\(=\|-\|+\)\{2,120}" 72 | 73 | "ReStructuredText Lists: 74 | syn match rstEnumeratedList "^\s*\d\{1,3}\.\s" 75 | 76 | syn match rstBulletedList "^\s*\([+-]\|\*\)\s" 77 | " syn match rstBulletedList "^\s*[+-]\|\*\s" 78 | "I'm not sure how to include "*" within a range []?!? 79 | " this seems to match more than it should :-( 80 | 81 | 82 | syn match rstFieldList ":[^:]\+:\s"me=e-1 contains=rstBibliographicField 83 | "still need to add rstDefinitionList rstOptionList 84 | 85 | "ReStructuredText Preformatting: 86 | syn match rstLiteralBlock "::\s*\n" contains=rstGridTable 87 | "syn region rstLiteralBlock start=+\(contents\)\@ 2 | 3 | 7 | 8 | -------------------------------------------------------------------------------- /text/vimfiles/template/template.xhs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | -------------------------------------------------------------------------------- /utilities/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /utilities/test_table.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Unit tests table.py. 3 | 4 | :see: http://docs.python.org/lib/minimal-example.html for an intro to unittest 5 | :see: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html 6 | :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305292 7 | ''' 8 | from __future__ import absolute_import 9 | import unittest 10 | 11 | try: 12 | import numpy as np 13 | has_numpy = True 14 | except ImportError: 15 | has_numpy = False 16 | 17 | __docformat__ = "restructuredtext en" 18 | 19 | from table import Cell, Row, SimpleTable 20 | from table import default_latex_fmt 21 | from table import default_html_fmt 22 | 23 | ltx_fmt1 = default_latex_fmt.copy() 24 | html_fmt1 = default_html_fmt.copy() 25 | 26 | txt_fmt1 = dict( 27 | data_fmts = ['%0.2f', '%d'], 28 | empty_cell = ' ', 29 | colwidths = 1, 30 | colsep=' * ', 31 | row_pre = '* ', 32 | row_post = ' *', 33 | table_dec_above='*', 34 | table_dec_below='*', 35 | header_dec_below='*', 36 | header_fmt = '%s', 37 | stub_fmt = '%s', 38 | title_align='r', 39 | header_align = 'r', 40 | data_aligns = "r", 41 | stubs_align = "l", 42 | fmt = 'txt' 43 | ) 44 | cell0data = 0.0000 45 | cell1data = 1 46 | row0data = [cell0data, cell1data] 47 | row1data = [2, 3.333] 48 | table1data = [ row0data, row1data ] 49 | test1stubs = ('stub1', 'stub2') 50 | test1header = ('header1', 'header2') 51 | #test1header = ('header1\nheader1a', 'header2\nheader2a') 52 | tbl = SimpleTable(table1data, test1header, test1stubs, 53 | txt_fmt=txt_fmt1, ltx_fmt=ltx_fmt1, html_fmt=html_fmt1) 54 | 55 | 56 | def custom_labeller(cell): 57 | if cell.data is np.nan: 58 | return 'missing' 59 | 60 | 61 | 62 | class test_Cell(unittest.TestCase): 63 | def test_celldata(self): 64 | celldata = cell0data, cell1data, row1data[0], row1data[1] 65 | cells = [Cell(datum, datatype=i%2) for i, datum in enumerate(celldata)] 66 | for cell, datum in zip(cells, celldata): 67 | self.assertEqual(cell.data, datum) 68 | 69 | class test_SimpleTable(unittest.TestCase): 70 | def test_txt_fmt1(self): 71 | """Limited test of custom txt_fmt""" 72 | desired = """ 73 | ***************************** 74 | * * header1 * header2 * 75 | ***************************** 76 | * stub1 * 0.00 * 1 * 77 | * stub2 * 2.00 * 3 * 78 | ***************************** 79 | """ 80 | actual = '\n%s\n' % tbl.as_text() 81 | #print('actual') 82 | #print(actual) 83 | #print('desired') 84 | #print(desired) 85 | self.assertEqual(actual, desired) 86 | def test_ltx_fmt1(self): 87 | """Limited test of custom ltx_fmt""" 88 | desired = r""" 89 | \begin{tabular}{lcc} 90 | \toprule 91 | & \textbf{header1} & \textbf{header2} \\ 92 | \midrule 93 | \textbf{stub1} & 0.0 & 1 \\ 94 | \textbf{stub2} & 2 & 3.333 \\ 95 | \bottomrule 96 | \end{tabular} 97 | """ 98 | actual = '\n%s\n' % tbl.as_latex_tabular() 99 | #print(actual) 100 | #print(desired) 101 | self.assertEqual(actual, desired) 102 | def test_html_fmt1(self): 103 | """Limited test of custom html_fmt""" 104 | desired = """ 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 |
header1 header2
stub1 0.0 1
stub2 2 3.333
116 | """ 117 | actual = '\n%s\n' % tbl.as_html() 118 | #print(actual) 119 | #print(desired) 120 | self.assertEqual(actual, desired) 121 | def test_customlabel(self): 122 | """Limited test of custom custom labeling""" 123 | if has_numpy: 124 | tbl = SimpleTable(table1data, test1header, test1stubs, txt_fmt=txt_fmt1) 125 | tbl[1][1].data = np.nan 126 | tbl.label_cells(custom_labeller) 127 | print([[c.datatype for c in row] for row in tbl]) 128 | desired = """ 129 | ***************************** 130 | * * header1 * header2 * 131 | ***************************** 132 | * stub1 * -- * 1 * 133 | * stub2 * 2.00 * 3 * 134 | ***************************** 135 | """ 136 | actual = '\n%s\n' % tbl.as_text(missing='--') 137 | print(actual) 138 | print(desired) 139 | self.assertEqual(actual, desired) 140 | def test_csv01(self): 141 | mydata = [[11,12],[21,22]] 142 | myheaders = [ "Column 1", "Column 2" ] 143 | mystubs = [ "Row 1", "Row 2" ] 144 | tbl = SimpleTable(mydata, myheaders, mystubs, title="Title") 145 | actual = '%s' % tbl.as_csv().strip() 146 | desired = """ 147 | Title 148 | ,Column 1,Column 2 149 | Row 1,11 ,12 150 | Row 2,21 ,22 151 | """.strip() 152 | self.assertEqual(actual, desired) 153 | 154 | if __name__=="__main__": 155 | unittest.main() 156 | 157 | -------------------------------------------------------------------------------- /utilities/wordfreq.py: -------------------------------------------------------------------------------- 1 | """ 2 | Produce word counts for input file. 3 | 4 | Sample use: 5 | 6 | wordfreq.py filename 7 | 8 | TODO: use collections.Counter (Python 3+) 9 | """ 10 | 11 | from __future__ import division, with_statement 12 | import sys, string 13 | from itertools import cycle, ifilter, izip 14 | from collections import defaultdict 15 | 16 | class WordFreq: 17 | """Summarize text file word counts. 18 | """ 19 | def __init__(self, filename, **kw): 20 | self.filename = filename 21 | self.params = kw 22 | self.word_hash = None 23 | self.ct_words = 0 24 | self.ct_longwords = 0 25 | #might want, e.g., start_after = ".. begin wordcount", 26 | self.start_after = '' 27 | self.wordsize_min = 3 28 | self.freq_min = 1 29 | self.describe() 30 | def describe(self): 31 | """ 32 | Return None. 33 | """ 34 | start_after = self.start_after 35 | wordsize_min = self.wordsize_min 36 | chars2strip = string.punctuation 37 | ct_words = 0 38 | ct_longwords = 0 39 | word_hash = defaultdict(int) 40 | with open(self.filename,'r') as fh: 41 | for line in fh: 42 | while start_after: 43 | if line.startswith(start_after): 44 | start_after = False 45 | continue 46 | line.strip() 47 | for word in line.split(): 48 | word = word.strip(chars2strip) 49 | if word: 50 | ct_words += 1 51 | if len(word) >= wordsize_min: 52 | ct_longwords += 1 53 | word_hash[word] += 1 54 | self.word_hash=word_hash 55 | self.ct_words=ct_words 56 | self.ct_longwords=ct_longwords 57 | def summarize(self): 58 | freq_min = self.freq_min 59 | word_hash = self.word_hash 60 | summary = dict( 61 | word_hash=word_hash, 62 | ct_words=self.ct_words, 63 | ct_longwords=self.ct_longwords, 64 | wordsize_min=self.wordsize_min 65 | ) 66 | fmt = "\n%24s %6d" 67 | #create word list in alpha order 68 | acceptable = ((k,v) for k,v in word_hash.iteritems() if v>=freq_min) 69 | summary['alpha'] = ''.join( fmt%(k,v) for k,v in sorted(acceptable) ) 70 | #create word list in occurrence order 71 | acceptable = ((k,v) for k,v in word_hash.iteritems() if v>=freq_min) 72 | summary['occur'] = ''.join( 73 | fmt%(k,v) 74 | for k,v in sorted(acceptable, key = lambda x: (-x[1], x[0]) )) 75 | result = """ 76 | Results for 'longer' words (length >= %(wordsize_min)d): 77 | 78 | ================================================= 79 | =============== WORD COUNT ====================== 80 | ================================================= 81 | Total number of words: %(ct_words)d 82 | Total number of 'longer' words : %(ct_longwords)d 83 | 84 | 85 | ================================================= 86 | =============== ALPHA ORDER ===================== 87 | ================================================= 88 | %(alpha)s 89 | 90 | 91 | ================================================= 92 | ============ OCCURRENCE ORDER =================== 93 | ================================================= 94 | %(occur)s 95 | """ 96 | return result%summary 97 | 98 | def main(): 99 | filename = sys.argv[1] 100 | wf = WordFreq(filename) 101 | print( wf.summarize() ) 102 | 103 | if __name__ == '__main__': 104 | main() 105 | 106 | --------------------------------------------------------------------------------