dangvinh77 commited on
Commit
b04beb1
·
1 Parent(s): 67e5415

Upload 14 files

Browse files
pystata/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, print_function
2
+
3
+ import sys
4
+
5
+ def _check_python_version():
6
+ if not sys.version_info >= (3, 4) and not sys.version_info >= (2, 7):
7
+ raise ImportError("""
8
+ pystata only supports Python 2.7 and 3.4+.
9
+ """)
10
+
11
+ _check_python_version()
12
+ del _check_python_version
13
+
14
+ from .version import version as __version__
15
+ from .version import author as __author__
16
+
17
+ from . import config
pystata/config.py ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This module is used to configure the system and display current system information
3
+ and settings.
4
+ '''
5
+ from __future__ import absolute_import, print_function
6
+ from ctypes import cdll, c_char_p, c_int, POINTER
7
+ import os
8
+ from os.path import dirname
9
+ import sys
10
+ import platform
11
+ from pystata.stexception import IPythonError, IPyKernelError
12
+ import codecs
13
+ import atexit
14
+
15
+ def _find_lib(st_home, edition, os_system):
16
+ lib_name = ""
17
+ if os_system == 'Windows':
18
+ lib_name += (edition + '-64')
19
+ lib_name += '.dll'
20
+ lib_path = os.path.join(st_home, lib_name)
21
+ if os.path.isfile(lib_path):
22
+ return lib_path
23
+ elif os_system == 'Darwin':
24
+ lib_name += 'libstata'
25
+ lib_name += ('-' + edition)
26
+ lib_name += '.dylib'
27
+
28
+ if edition == 'be':
29
+ lib_name = os.path.join("StataBE.app/Contents/MacOS", lib_name)
30
+ elif edition == "se":
31
+ lib_name = os.path.join("StataSE.app/Contents/MacOS", lib_name)
32
+ else:
33
+ lib_name = os.path.join("StataMP.app/Contents/MacOS", lib_name)
34
+
35
+ lib_path = os.path.join(st_home, lib_name)
36
+ if os.path.isfile(lib_path):
37
+ return lib_path
38
+ else:
39
+ lib_name += 'libstata'
40
+
41
+ if edition != 'be':
42
+ lib_name += ('-' + edition)
43
+
44
+ lib_name += '.so'
45
+ lib_path = os.path.join(st_home, lib_name)
46
+ if os.path.isfile(lib_path):
47
+ return lib_path
48
+
49
+ lib_path = os.path.join('../distn/linux64', lib_name)
50
+ lib_path = os.path.join(st_home, lib_path)
51
+ if os.path.isfile(lib_path):
52
+ return lib_path
53
+
54
+ lib_path = os.path.join('../distn/linux.64p', lib_name)
55
+ lib_path = os.path.join(st_home, lib_path)
56
+ if os.path.isfile(lib_path):
57
+ return lib_path
58
+
59
+ lib_path = os.path.join('../distn/linux.64', lib_name)
60
+ lib_path = os.path.join(st_home, lib_path)
61
+ if os.path.isfile(lib_path):
62
+ return lib_path
63
+
64
+ return None
65
+
66
+
67
+ def _get_lib_path(st_home, edition):
68
+ if st_home is None:
69
+ raise ValueError('Stata home directory is None')
70
+ else:
71
+ if not os.path.isdir(st_home):
72
+ raise ValueError('Stata home directory is invalid')
73
+
74
+ os_system = platform.system()
75
+ if edition not in ['be','se','mp']:
76
+ raise ValueError('Stata edition must be one of be, se, or mp')
77
+
78
+ lib_path = _find_lib(st_home, edition, os_system)
79
+ if lib_path is not None:
80
+ return lib_path
81
+
82
+ raise FileNotFoundError('The system cannot find the shared library within the specified path: %s', st_home)
83
+
84
+
85
+ def _RaiseSystemException(msg):
86
+ raise SystemError(msg)
87
+
88
+
89
+ stlib = None
90
+ stversion = ''
91
+ stedition = ''
92
+ stinitialized = False
93
+ sfiinitialized = False
94
+ stlibpath = None
95
+ stipython = 0
96
+ stoutputf = None
97
+
98
+ stconfig = {
99
+ "grwidth": ['default', 'in'],
100
+ "grheight": ['default', 'in'],
101
+ "grformat": 'svg',
102
+ "grshow": True,
103
+ "streamout": 'on'
104
+ }
105
+
106
+ pyversion = sys.version_info[0:3]
107
+
108
+
109
+ def _check_duplicate_kmp(edition):
110
+ os_system = platform.system()
111
+
112
+ if edition is None or edition=='mp':
113
+ if os_system == 'Darwin':
114
+ os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
115
+
116
+
117
+ def _get_stata_edition(edition):
118
+ if edition is None:
119
+ return 'MP'
120
+ elif edition=='mp':
121
+ return 'MP'
122
+ elif edition=='se':
123
+ return 'SE'
124
+ else:
125
+ return 'BE'
126
+
127
+
128
+ def get_encode_str(s):
129
+ return s.encode('utf-8')
130
+
131
+
132
+ def _print_greeting_message(msg):
133
+ global pyversion
134
+
135
+ try:
136
+ print(msg, end='')
137
+ except UnicodeEncodeError:
138
+ if pyversion[0] < 3:
139
+ print(s.encode('utf-8'), end='')
140
+ else:
141
+ print(s.encode('utf-8').decode(sys.stdout.encoding), end='')
142
+
143
+
144
+ def backslashreplace_py2(err):
145
+ s = err.object
146
+ start = err.start
147
+ end = err.end
148
+
149
+ def backslashreplace_repr(c):
150
+ if isinstance(c,int):
151
+ return c
152
+ else:
153
+ return ord(c)
154
+
155
+ return u''.join('\\x{:x}'.format(backslashreplace_repr(c)) for c in s[start:end]),end
156
+
157
+
158
+ def get_decode_str(s):
159
+ try:
160
+ return s.decode('utf-8', 'backslashreplace')
161
+ except:
162
+ codecs.register_error('backslashreplace_py2', backslashreplace_py2)
163
+ return s.decode('utf-8', 'backslashreplace_py2')
164
+
165
+
166
+ def _get_st_home():
167
+ pypath = os.path.normpath(os.path.abspath(__file__))
168
+ d_utilities = dirname(dirname(pypath))
169
+
170
+ if os.path.basename(d_utilities).lower()=="utilities":
171
+ return dirname(d_utilities)
172
+ else:
173
+ _RaiseSystemException("failed to load Stata's shared library")
174
+
175
+
176
+ def _get_executable_path():
177
+ sys_exec_path = sys.executable
178
+ if os.path.isfile(sys_exec_path):
179
+ return sys_exec_path
180
+
181
+ os_system = platform.system()
182
+ if os_system!="Windows":
183
+ sys_exec_path_non_windows = os.path.join(os.__file__.split('lib/')[0], 'bin', 'python')
184
+ if os.path.isfile(sys_exec_path_non_windows):
185
+ return sys_exec_path_non_windows
186
+
187
+ return sys_exec_path
188
+
189
+
190
+ def _init_stata():
191
+ stlib.StataSO_Main.restype = c_int
192
+ stlib.StataSO_Main.argtypes = (c_int, POINTER(c_char_p))
193
+
194
+ libpath = ['-pyexec', _get_executable_path()]
195
+ sarr = (c_char_p * len(libpath))()
196
+ sarr[:] = [get_encode_str(s) for s in libpath]
197
+
198
+ rc = stlib.StataSO_Main(2, sarr)
199
+
200
+ return(rc)
201
+
202
+
203
+ def init(edition):
204
+ """
205
+ Initialize Stata's environment within Python.
206
+
207
+ Parameters
208
+ ----------
209
+ edition : str
210
+ The Stata edition to be used. It can be one of **mp**, **se**, or **be**.
211
+ """
212
+ global stinitialized
213
+ global sfiinitialized
214
+ global stlibpath
215
+ global stlib
216
+ global stedition
217
+ global stipython
218
+ if stinitialized is False:
219
+ st_home = _get_st_home()
220
+ os.environ['SYSDIR_STATA'] = st_home
221
+ lib_path = os.path.normpath(_get_lib_path(st_home, edition))
222
+ stlibpath = lib_path
223
+ stedition = _get_stata_edition(edition)
224
+
225
+ try:
226
+ stlib = cdll.LoadLibrary(lib_path)
227
+ except:
228
+ _RaiseSystemException("failed to load Stata's shared library")
229
+
230
+ if stlib is None:
231
+ _RaiseSystemException("failed to load Stata's shared library")
232
+
233
+ sfiinitialized = True
234
+ rc = _init_stata()
235
+ msg = get_output()
236
+ if rc < 0:
237
+ if rc==-7100:
238
+ sfiinitialized = False
239
+ else:
240
+ _RaiseSystemException("failed to initialize Stata"+'\n'+msg)
241
+ else:
242
+ _print_greeting_message(msg)
243
+
244
+ stinitialized = True
245
+ _load_system_config()
246
+
247
+ stipython = 0
248
+ try:
249
+ import pystata.ipython.stpymagic
250
+ if stipython == 0:
251
+ stipython = 5
252
+ except IPythonError:
253
+ pass
254
+ except IPyKernelError:
255
+ pass
256
+ except:
257
+ stipython = 5
258
+
259
+ if sys.version_info[0] < 3:
260
+ reload(sys)
261
+ sys.setdefaultencoding('utf-8')
262
+
263
+ _check_duplicate_kmp(edition)
264
+
265
+
266
+ def check_initialized():
267
+ if stinitialized is False:
268
+ _RaiseSystemException('''
269
+ Note: Stata environment has not been initialized yet.
270
+ To proceed, you must call init() function in the config module as follows:
271
+
272
+ from pystata import config
273
+ config.init()''')
274
+
275
+
276
+ @atexit.register
277
+ def shutdown():
278
+ global stlib
279
+ global stinitialized
280
+
281
+ if stinitialized:
282
+ try:
283
+ stlib.StataSO_Shutdown.restype = None
284
+ stlib.StataSO_Shutdown()
285
+ except:
286
+ raise
287
+
288
+
289
+ def is_stata_initialized():
290
+ """
291
+ Check whether Stata has been initialized.
292
+
293
+ Returns
294
+ -------
295
+ bool
296
+ True if Stata has been successfully initialized.
297
+ """
298
+ global stinitialized
299
+ return stinitialized
300
+
301
+
302
+ def _get_python_version_str():
303
+ global pyversion
304
+ s = [str(i) for i in pyversion]
305
+ return ".".join(s)
306
+
307
+
308
+ def _get_stata_version_str():
309
+ global stversion
310
+ global stedition
311
+ if stversion=='':
312
+ return stedition
313
+ else:
314
+ return 'Stata ' + stversion + ' (' + stedition + ')'
315
+
316
+
317
+ def get_graph_size_str(info):
318
+ global stconfig
319
+ if info=='gw':
320
+ grwidth = stconfig['grwidth']
321
+ if grwidth[0]=='default':
322
+ return 'default'
323
+ else:
324
+ return str(grwidth[0])+grwidth[1]
325
+ else:
326
+ grheight = stconfig['grheight']
327
+ if grheight[0]=='default':
328
+ return 'default'
329
+ else:
330
+ return str(grheight[0])+grheight[1]
331
+
332
+
333
+ def status():
334
+ """
335
+ Display current system information and settings.
336
+ """
337
+ if stinitialized is False:
338
+ print('Stata environment has not been initialized yet')
339
+ else:
340
+ print(' System information')
341
+ print(' Python version %s' % _get_python_version_str())
342
+ print(' Stata version %s' % _get_stata_version_str())
343
+ print(' Stata library path %s' % stlibpath)
344
+ print(' Stata initialized %s' % str(stinitialized))
345
+ print(' sfi initialized %s\n' % str(sfiinitialized))
346
+ print(' Settings')
347
+ print(' graphic display ', stconfig['grshow'])
348
+ print(' graphic size ', ' width = ', get_graph_size_str('gw'), ', height = ', get_graph_size_str('gh'), sep='')
349
+ print(' graphic format ', stconfig['grformat'])
350
+
351
+
352
+ def get_output():
353
+ stlib.StataSO_GetOutputBuffer.restype = c_char_p
354
+ foo = stlib.StataSO_GetOutputBuffer()
355
+
356
+ mystr = get_decode_str(c_char_p(foo).value)
357
+ return mystr
358
+
359
+
360
+ def get_stipython():
361
+ global stipython
362
+ return stipython
363
+
364
+
365
+ def set_graph_format(gformat, perm=False):
366
+ """
367
+ Set the file format used to export and display graphs. By default,
368
+ graphs generated by Stata are exported and displayed as SVG files.
369
+
370
+ The supported formats are **svg**, **png**, and **pdf**. If **svg** or
371
+ **png** is specified, the graph is embedded. If **pdf** is specified, the
372
+ graph is exported to a PDF file in the current working directory with a
373
+ numeric name, such as 0.pdf, 1.pdf, 2.pdf, etc. This is useful when you
374
+ try to export a notebook to a PDF via LaTex and you want the graph to be
375
+ embedded.
376
+
377
+ Parameters
378
+ ----------
379
+ gformat : str
380
+ The graph format. It can be **svg**, **png**, or **pdf**.
381
+
382
+ perm : bool, optional
383
+ When set to True, in addition to making the change right now,
384
+ the setting will be remembered and become the default
385
+ setting when you invoke Stata. Default is False.
386
+ """
387
+ global stconfig
388
+
389
+ if perm is not True and perm is not False:
390
+ raise ValueError("perm must be a boolean value")
391
+
392
+ if gformat=='svg':
393
+ stconfig['grformat'] = 'svg'
394
+ elif gformat=="png":
395
+ stconfig['grformat'] = 'png'
396
+ elif gformat=='pdf':
397
+ stconfig['grformat'] = 'pdf'
398
+ else:
399
+ raise ValueError("invalid graph format")
400
+
401
+ if perm:
402
+ _save_system_config("grformat", stconfig['grformat'])
403
+
404
+
405
+ def _get_figure_size_info(ustr):
406
+ finfo = []
407
+ ustr = ustr.strip()
408
+ if ustr.lower() == 'default':
409
+ finfo.append('default')
410
+ finfo.append('in')
411
+ else:
412
+ try:
413
+ figsize = round(float(ustr))
414
+ finfo.append(figsize)
415
+ finfo.append('in')
416
+ except ValueError:
417
+ if ustr[-2:] == 'px':
418
+ figsize = ustr[:-2].strip()
419
+ if figsize.lower()!='default':
420
+ try:
421
+ figsize = int(round(float(figsize)))
422
+ except ValueError:
423
+ figsize = -1
424
+
425
+ finfo.append(figsize)
426
+ finfo.append('px')
427
+ elif ustr[-2:] == 'in':
428
+ figsize = ustr[:-2].strip()
429
+ if figsize.lower()!='default':
430
+ try:
431
+ figsize = float(figsize)
432
+ except ValueError:
433
+ figsize = -1
434
+
435
+ finfo.append(figsize)
436
+ finfo.append('in')
437
+ elif ustr[-2:] == 'cm':
438
+ figsize = ustr[:-2].strip()
439
+ if figsize.lower()!='default':
440
+ try:
441
+ figsize = float(figsize)
442
+ except ValueError:
443
+ figsize = -1
444
+
445
+ finfo.append(round(figsize, 3))
446
+ else:
447
+ finfo.append(figsize)
448
+
449
+ finfo.append('cm')
450
+ else:
451
+ finfo.append(-1)
452
+ finfo.append('in')
453
+
454
+ return finfo
455
+
456
+
457
+ def _add_java_home_to_path():
458
+ os_system = platform.system()
459
+ if os_system=="Windows":
460
+ import sfi
461
+ javahome = sfi.Macro.getGlobal('c(java_home)')
462
+ if javahome!='':
463
+ javahome = os.path.join(javahome, 'bin')
464
+ ospath = os.environ['PATH']
465
+
466
+ if ospath not in ospath.split(';'):
467
+ os.environ['PATH'] = os.environ.get('PATH') + ";" + javahome
468
+
469
+
470
+ def _load_system_config():
471
+ if sfiinitialized:
472
+ try:
473
+ import sfi
474
+ grwidth_pref = sfi.Preference.getSavedPref('pystata', 'grwidth', '')
475
+ grheight_pref = sfi.Preference.getSavedPref('pystata', 'grheight', '')
476
+
477
+ if grwidth_pref!="" and grheight_pref!="":
478
+ set_graph_size(width=grwidth_pref, height=grheight_pref)
479
+ elif grwidth_pref!="":
480
+ set_graph_size(width=grwidth_pref)
481
+ elif grheight_pref!="":
482
+ set_graph_size(height=grheight_pref)
483
+
484
+ grformat_pref = sfi.Preference.getSavedPref('pystata', 'grformat', '')
485
+ if grformat_pref!="":
486
+ set_graph_format(gformat=grformat_pref)
487
+
488
+ grshow_pref = sfi.Preference.getSavedPref('pystata', 'grshow', '')
489
+ if grshow_pref!="":
490
+ if grshow_pref=="1":
491
+ set_graph_show(show=True)
492
+ else:
493
+ set_graph_show(show=False)
494
+
495
+ streamout_pref = sfi.Preference.getSavedPref('pystata', 'streamout', '')
496
+ if streamout_pref!="":
497
+ if streamout_pref=="on":
498
+ set_streaming_output_mode(flag='on')
499
+ else:
500
+ set_streaming_output_mode(flag='off')
501
+
502
+ global stversion
503
+ stversion = str(sfi.Scalar.getValue('c(stata_version)'))
504
+
505
+ _add_java_home_to_path()
506
+ except:
507
+ print('''
508
+ Warning: failed to load the system default configuration. The following
509
+ settings will be applied:
510
+ ''')
511
+ status()
512
+
513
+
514
+ def _save_system_config(key, value):
515
+ if sfiinitialized:
516
+ try:
517
+ import sfi
518
+ sfi.Preference.setSavedPref("pystata", key, value)
519
+ except:
520
+ _RaiseSystemException("failed to store the specified setting")
521
+
522
+
523
+ def set_graph_size(width=None, height=None, perm=False):
524
+ """
525
+ Set the graph size for images to be exported and displayed. By default,
526
+ the graphs generated by Stata are exported using a dimension of 5.5 inches
527
+ for the width by 4 inches for the height. Either the width or height must
528
+ be specified, and both may be specified. If only one is specified, the
529
+ other one is calculated from the aspect ratio.
530
+
531
+ The width or height can be specified as a floating-point number, a string
532
+ with a floating-point number and its unit, or **default**. The supported
533
+ units are inches (**in**), pixels (**px**), or centimeters (**cm**). If
534
+ no unit is specified, **in** is assumed. For example, **width = 3** sets
535
+ the width to 3 inches, which is the same as specifying **width = 3in**.
536
+ And **width = 300px** sets the width to 300 pixels.
537
+
538
+ Parameters
539
+ ----------
540
+ width : float or str
541
+ The graph width.
542
+
543
+ height: float or str
544
+ The graph height.
545
+
546
+ perm : bool, optional
547
+ When set to True, in addition to making the change right now,
548
+ the setting will be remembered and become the default
549
+ setting when you invoke Stata. Default is False.
550
+ """
551
+ if width is None and height is None:
552
+ raise ValueError('one of width and height must be specified')
553
+
554
+ if perm is not True and perm is not False:
555
+ raise ValueError("perm must be a boolean value")
556
+
557
+ if width:
558
+ gwidth = _get_figure_size_info(str(width))
559
+ if gwidth[0] != 'default' and gwidth[0] < 0:
560
+ raise ValueError('graph width is invalid')
561
+
562
+ gr_width = gwidth[0]
563
+ gr_width_unit = gwidth[1]
564
+ else:
565
+ gr_width = 'default'
566
+ gr_width_unit = 'in'
567
+
568
+ if height:
569
+ gheight = _get_figure_size_info(str(height))
570
+ if gheight[0] != 'default' and gheight[0] < 0:
571
+ raise ValueError('graph height is invalid')
572
+
573
+ gr_height = gheight[0]
574
+ gr_height_unit = gheight[1]
575
+ else:
576
+ gr_height = 'default'
577
+ gr_height_unit = 'in'
578
+
579
+ global stconfig
580
+ grwidth = []
581
+ grheight = []
582
+ if width and height:
583
+ grwidth.append(gr_width)
584
+ grwidth.append(gr_width_unit)
585
+ grheight.append(gr_height)
586
+ grheight.append(gr_height_unit)
587
+ elif width:
588
+ grwidth.append(gr_width)
589
+ grwidth.append(gr_width_unit)
590
+ grheight.append('default')
591
+ grheight.append(gr_width_unit)
592
+ elif height:
593
+ grwidth.append('default')
594
+ grwidth.append(gr_height_unit)
595
+ grheight.append(gr_height)
596
+ grheight.append(gr_height_unit)
597
+ else:
598
+ grwidth.append(gr_width)
599
+ grwidth.append(gr_width_unit)
600
+ grheight.append(gr_height)
601
+ grheight.append(gr_height_unit)
602
+
603
+ stconfig['grwidth'] = grwidth
604
+ stconfig['grheight'] = grheight
605
+
606
+ if perm:
607
+ _save_system_config("grwidth", str(grwidth[0])+grwidth[1])
608
+ _save_system_config("grheight", str(grheight[0])+grheight[1])
609
+
610
+
611
+ def set_graph_show(show, perm=False):
612
+ """
613
+ Set whether the graphs generated by Stata are to be exported and
614
+ displayed. By default, the graphs are exported and displayed
615
+ in the output. If `show` is set to False, graphs will not be
616
+ exported and displayed.
617
+
618
+ Parameters
619
+ ----------
620
+ show : bool
621
+ Export and display Stata-generated graphs in the output.
622
+
623
+ perm : bool, optional
624
+ When set to True, in addition to making the change right now,
625
+ the setting will be remembered and become the default
626
+ setting when you invoke Stata. Default is False.
627
+ """
628
+ global stconfig
629
+
630
+ if perm is not True and perm is not False:
631
+ raise ValueError("perm must be a boolean value")
632
+
633
+ if show is True:
634
+ stconfig['grshow'] = True
635
+ elif show is False:
636
+ stconfig['grshow'] = False
637
+ else:
638
+ raise TypeError("show must be a boolean value")
639
+
640
+ if perm:
641
+ if show:
642
+ _save_system_config("grshow", "1")
643
+ else:
644
+ _save_system_config("grshow", "0")
645
+
646
+
647
+ def set_streaming_output_mode(flag, perm=False):
648
+ global stconfig
649
+
650
+ if perm is not True and perm is not False:
651
+ raise ValueError("perm must be a boolean value")
652
+
653
+ if flag == "on":
654
+ stconfig['streamout'] = 'on'
655
+ elif flag == "off":
656
+ stconfig['streamout'] = 'off'
657
+ else:
658
+ raise ValueError("The value for output mode must be either on or off. Default is on.")
659
+
660
+ if perm:
661
+ _save_system_config("streamout", stconfig['streamout'])
662
+
663
+
664
+ def set_output_file(filename, replace=False):
665
+ """
666
+ Write Stata output to a text file. By default, Stata output is printed on
667
+ the screen. The file extension may be **.txt** or **.log**. You must
668
+ supply a file extension if you want one because none is assumed.
669
+
670
+ Parameters
671
+ ----------
672
+ filename : str
673
+ Name of the text file.
674
+
675
+ replace : bool, optional
676
+ Replace the output file if it exists. Default is False.
677
+ """
678
+ global pyversion
679
+ global stoutputf
680
+
681
+ if os.path.isfile(filename):
682
+ if not replace:
683
+ raise OSError(filename + ' already exists')
684
+
685
+ os.remove(filename)
686
+
687
+ if pyversion[0] < 3:
688
+ f = open(filename, 'ab')
689
+ else:
690
+ f = open(filename, 'a', newline='\n', encoding='utf-8')
691
+
692
+ stoutputf = f
693
+
694
+
695
+ def close_output_file():
696
+ """
697
+ Stop writing Stata output to a text file. This function should be used
698
+ after having used :meth:`~pystata.config.set_output_file`. If it returns
699
+ without an error, any Stata output that follows will instead be printed
700
+ on the screen.
701
+ """
702
+ global stoutputf
703
+ if stoutputf is not None:
704
+ stoutputf.close()
705
+
pystata/core/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from pystata.config import check_initialized
2
+
3
+ check_initialized()
pystata/core/numpy2mata.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sfi
2
+ import numpy as np
3
+
4
+ def array_from_mata(mat):
5
+ return np.array(sfi.Mata.get(mat))
6
+
7
+
8
+ def array_to_mata(arr, mat):
9
+ if not isinstance(arr, np.ndarray):
10
+ raise TypeError("An NumPy array is required.")
11
+
12
+ ndim = len(arr.shape)
13
+ if ndim < 1 or ndim >= 3:
14
+ raise TypeError("Dimension of array must not be greater than 2.")
15
+
16
+ nobs = len(arr)
17
+ if nobs == 0:
18
+ return None
19
+
20
+ dtype = arr.dtype.name
21
+ if dtype in ['bool_', 'bool8', 'byte']:
22
+ dtypestr = 'real'
23
+ elif dtype in ['short', 'intc', 'int8', 'int16', 'int32', 'ubyte', 'ushort', 'uintc', 'uint8', 'uint16']:
24
+ dtypestr = 'real'
25
+ elif dtype in ['int_', 'longlong', 'intp', 'int64', 'uint', 'ulonglong', 'uint32', 'uint64']:
26
+ dtypestr = 'real'
27
+ elif dtype in ['half', 'single', 'float16', 'float32']:
28
+ dtypestr = 'real'
29
+ elif dtype in ['double', 'float_', 'longfloat', 'float64', 'float96', 'float128']:
30
+ dtypestr = 'real'
31
+ elif dtype in ['csingle', 'cdouble', 'clongdouble', 'complex64', 'complex128', 'complex_']:
32
+ dtypestr = 'complex'
33
+ else:
34
+ dtypestr = 'string'
35
+
36
+ if ndim == 1:
37
+ if dtypestr=='real':
38
+ sfi.Mata.create(mat, 1, arr.shape[0], sfi.Missing.getValue())
39
+ elif dtypestr=='complex':
40
+ sfi.Mata.create(mat, 1, arr.shape[0], 0j)
41
+ else:
42
+ sfi.Mata.create(mat, 1, arr.shape[0], '')
43
+
44
+ sfi.Mata.store(mat, arr)
45
+ else:
46
+ if dtypestr=='real':
47
+ sfi.Mata.create(mat, arr.shape[0], arr.shape[1], sfi.Missing.getValue())
48
+ elif dtypestr=='complex':
49
+ sfi.Mata.create(mat, arr.shape[0], arr.shape[1], 0j)
50
+ else:
51
+ sfi.Mata.create(mat, arr.shape[0], arr.shape[1], '')
52
+
53
+ sfi.Mata.store(mat, arr)
pystata/core/numpy2stata.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sfi
2
+ import numpy as np
3
+
4
+ def _get_varname(arr):
5
+ return [str(e) for e in arr]
6
+
7
+
8
+ def _add_var(name, type, stfr=None):
9
+ if stfr is None:
10
+ if type=="byte":
11
+ sfi.Data.addVarByte(name)
12
+ elif type=="int":
13
+ sfi.Data.addVarInt(name)
14
+ elif type=="long":
15
+ sfi.Data.addVarLong(name)
16
+ elif type=="float":
17
+ sfi.Data.addVarFloat(name)
18
+ elif type=="double":
19
+ sfi.Data.addVarDouble(name)
20
+ else:
21
+ sfi.Data.addVarStr(name, 9)
22
+ else:
23
+ if type=="byte":
24
+ stfr.addVarByte(name)
25
+ elif type=="int":
26
+ stfr.addVarInt(name)
27
+ elif type=="long":
28
+ stfr.addVarLong(name)
29
+ elif type=="float":
30
+ stfr.addVarFloat(name)
31
+ elif type=="double":
32
+ stfr.addVarDouble(name)
33
+ else:
34
+ stfr.addVarStr(name, 9)
35
+
36
+
37
+ def array_to_stata(arr, stfr, prefix):
38
+ if not isinstance(arr, np.ndarray):
39
+ raise TypeError("An NumPy array is required.")
40
+
41
+ ndim = len(arr.shape)
42
+ if ndim < 1 or ndim >= 3:
43
+ raise TypeError("Dimension of array must not be greater than 2.")
44
+
45
+ nobs = len(arr)
46
+ if nobs == 0:
47
+ return None
48
+
49
+ vtype = arr.dtype.name
50
+ if vtype in ['bool_', 'bool8', 'byte']:
51
+ vtypestr = 'byte'
52
+ elif vtype in ['short', 'intc', 'int8', 'int16', 'int32', 'ubyte', 'ushort', 'uintc', 'uint8', 'uint16']:
53
+ vtypestr = 'int'
54
+ elif vtype in ['int_', 'longlong', 'intp', 'int64', 'uint', 'ulonglong', 'uint32', 'uint64']:
55
+ vtypestr = 'long'
56
+ elif vtype in ['half', 'single', 'float16', 'float32']:
57
+ vtypestr = 'float'
58
+ elif vtype in ['double', 'float_', 'longfloat', 'float64', 'float96', 'float128']:
59
+ vtypestr = 'double'
60
+ else:
61
+ vtypestr = 'str'
62
+
63
+ if stfr is None:
64
+ sfi.Data.setObsTotal(nobs)
65
+ if ndim == 1:
66
+ _add_var(prefix+"1", vtypestr)
67
+ sfi.Data.store(0, None, arr)
68
+ else:
69
+ ncol = arr.shape[1]
70
+ for col in range(ncol):
71
+ _add_var(prefix+str(col+1), vtypestr)
72
+ dta = arr[:,col]
73
+ sfi.Data.store(col, None, dta)
74
+ else:
75
+ fr = sfi.Frame.create(stfr)
76
+ fr.setObsTotal(nobs)
77
+
78
+ if ndim == 1:
79
+ _add_var(prefix+"1", vtypestr, fr)
80
+ fr.store(0, None, arr)
81
+ else:
82
+ ncol = arr.shape[1]
83
+ for col in range(ncol):
84
+ _add_var(prefix+str(col+1), vtypestr, fr)
85
+ dta = arr[:,col]
86
+ fr.store(col, None, dta)
87
+
88
+
89
+ def array_from_stata(stfr, var, obs, selectvar, valuelabel, missingval):
90
+ if stfr is None:
91
+ nobs = sfi.Data.getObsTotal()
92
+ if nobs <= 0:
93
+ return None
94
+
95
+ if missingval is None:
96
+ return(np.array(sfi.Data.get(var, obs, selectvar, valuelabel)))
97
+ else:
98
+ return(np.array(sfi.Data.get(var, obs, selectvar, valuelabel, missingval)))
99
+ else:
100
+ fr = sfi.Frame.connect(stfr)
101
+ nobs = fr.getObsTotal()
102
+ if nobs <= 0:
103
+ return None
104
+
105
+ if missingval is None:
106
+ return(np.array(fr.get(var, obs, selectvar, valuelabel)))
107
+ else:
108
+ return(np.array(fr.get(var, obs, selectvar, valuelabel, missingval)))
109
+
110
+
111
+ def array_from_matrix(stmat):
112
+ return np.array(stmat)
pystata/core/pandas2stata.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sfi
2
+ import pandas as pd
3
+
4
+ def _make_indexed_name(index, stnames, pdnames):
5
+ count = 0
6
+ varn = "v" + str(index+count)
7
+ while True:
8
+ if varn in stnames or varn in pdnames:
9
+ count = count + 1
10
+ varn = "v" + str(index+count)
11
+ else:
12
+ break
13
+
14
+ return varn
15
+
16
+
17
+ def _make_varname(s, index, stnames, pdnames):
18
+ s = str(s)
19
+ if sfi.SFIToolkit.isValidVariableName(s):
20
+ stnames.append(s)
21
+ return(s)
22
+ else:
23
+ try:
24
+ varn = sfi.SFIToolkit.makeVarName(s, True)
25
+ if varn in stnames or varn in pdnames:
26
+ varn = _make_indexed_name(index, stnames, pdnames)
27
+ except:
28
+ varn = _make_indexed_name(index, stnames, pdnames)
29
+
30
+ stnames.append(varn)
31
+ return varn
32
+
33
+
34
+ def _add_var(name, type, stfr=None):
35
+ if stfr is None:
36
+ if type=="byte":
37
+ sfi.Data.addVarByte(name)
38
+ elif type=="int":
39
+ sfi.Data.addVarInt(name)
40
+ elif type=="long":
41
+ sfi.Data.addVarLong(name)
42
+ elif type=="float":
43
+ sfi.Data.addVarFloat(name)
44
+ elif type=="double":
45
+ sfi.Data.addVarDouble(name)
46
+ else:
47
+ sfi.Data.addVarStr(name, 9)
48
+ else:
49
+ if type=="byte":
50
+ stfr.addVarByte(name)
51
+ elif type=="int":
52
+ stfr.addVarInt(name)
53
+ elif type=="long":
54
+ stfr.addVarLong(name)
55
+ elif type=="float":
56
+ stfr.addVarFloat(name)
57
+ elif type=="double":
58
+ stfr.addVarDouble(name)
59
+ else:
60
+ stfr.addVarStr(name, 9)
61
+
62
+
63
+ def dataframe_to_stata(df, stfr):
64
+ if not isinstance(df, pd.DataFrame):
65
+ raise TypeError("A Pandas dataframe is required.")
66
+
67
+ nobs = len(df)
68
+ if nobs == 0:
69
+ return None
70
+
71
+ colnames = list(df.columns)
72
+ stnames = []
73
+
74
+ if stfr is None:
75
+ sfi.Data.setObsTotal(nobs)
76
+ var = 0
77
+ for col in colnames:
78
+ vtype = df.dtypes[col].name
79
+ dta = df[col]
80
+ col = _make_varname(col, var+1, stnames, colnames)
81
+ if vtype=="int_" or vtype=="int8" or vtype=="int16" or vtype=="int32" or \
82
+ vtype=="uint8" or vtype=="uint16":
83
+ _add_var(col, "int")
84
+ sfi.Data.store(var, None, dta)
85
+ elif vtype=="int64" or vtype=='uint32':
86
+ _add_var(col, "long")
87
+ sfi.Data.store(var, None, dta)
88
+ elif vtype=="float_" or vtype=="float16" or vtype=="float32":
89
+ _add_var(col, "float")
90
+ sfi.Data.store(var, None, dta)
91
+ elif vtype=="float64":
92
+ _add_var(col, "double")
93
+ sfi.Data.store(var, None, dta)
94
+ elif vtype=="bool":
95
+ _add_var(col, "byte")
96
+ sfi.Data.store(var, None, dta)
97
+ else:
98
+ _add_var(col, "str")
99
+ sfi.Data.store(var, None, dta.astype(str))
100
+
101
+ var = var + 1
102
+ else:
103
+ fr = sfi.Frame.create(stfr)
104
+ fr.setObsTotal(nobs)
105
+ var = 0
106
+ for col in colnames:
107
+ vtype = df.dtypes[col].name
108
+ dta = df[col]
109
+ col = _make_varname(col, var+1, stnames, colnames)
110
+ if vtype=="int_" or vtype=="int8" or vtype=="int16" or vtype=="int32" or \
111
+ vtype=="uint8" or vtype=="uint16":
112
+ _add_var(col, "int", fr)
113
+ fr.store(var, None, dta)
114
+ elif vtype=="int64" or vtype=='uint32':
115
+ _add_var(col, "long", fr)
116
+ fr.store(var, None, dta)
117
+ elif vtype=="float_" or vtype=="float16" or vtype=="float32":
118
+ _add_var(col, "float", fr)
119
+ fr.store(var, None, dta)
120
+ elif vtype=="float64":
121
+ _add_var(col, "double", fr)
122
+ fr.store(var, None, dta)
123
+ elif vtype=="bool":
124
+ _add_var(col, "byte", fr)
125
+ fr.store(var, None, dta)
126
+ else:
127
+ _add_var(col, "str", fr)
128
+ fr.store(var, None, dta.astype(str))
129
+
130
+ var = var + 1
131
+
132
+
133
+ def dataframe_from_stata(stfr, var, obs, selectvar, valuelabel, missingval):
134
+ if stfr is None:
135
+ nobs = sfi.Data.getObsTotal()
136
+ if nobs <= 0:
137
+ return None
138
+
139
+ if missingval is None:
140
+ df = pd.DataFrame(sfi.Data.getAsDict(var, obs, selectvar, valuelabel))
141
+ else:
142
+ df = pd.DataFrame(sfi.Data.getAsDict(var, obs, selectvar, valuelabel, missingval))
143
+
144
+ return(df)
145
+ else:
146
+ fr = sfi.Frame.connect(stfr)
147
+ nobs = fr.getObsTotal()
148
+ if nobs <= 0:
149
+ return None
150
+
151
+ if missingval is None:
152
+ df = pd.DataFrame(fr.getAsDict(var, obs, selectvar, valuelabel))
153
+ else:
154
+ df = pd.DataFrame(fr.getAsDict(var, obs, selectvar, valuelabel, missingval))
155
+
156
+ return(df)
pystata/core/stout.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+ from __future__ import unicode_literals
3
+ from pystata import config
4
+ import sys
5
+ import threading
6
+ import time
7
+
8
+ def output_get_interactive_result(output, real_cmd, colon, mode):
9
+ try:
10
+ if mode==2:
11
+ if colon:
12
+ fmt_str1 = ". mata:\n"
13
+ else:
14
+ fmt_str1 = ". mata\n"
15
+ else:
16
+ if colon:
17
+ fmt_str1 = ". python:\n"
18
+ else:
19
+ fmt_str1 = ". python\n"
20
+
21
+ pos1 = output.index(fmt_str1)
22
+ pos1 = pos1 + len(fmt_str1)
23
+ except:
24
+ pos1 = 0
25
+
26
+ output = output[pos1:]
27
+
28
+ try:
29
+ if mode==2:
30
+ fmt_str2 = "-"*49 + " mata (type end to exit) "
31
+ else:
32
+ fmt_str2 = "-"*47 + " python (type end to exit) "
33
+
34
+ pos2 = output.index(fmt_str2)
35
+ pos2 = output.index("\n") + 1
36
+ except:
37
+ pos2 = 0
38
+
39
+ output = output[pos2:]
40
+
41
+ try:
42
+ fmt_str3 = real_cmd
43
+ pos3 = output.index(fmt_str3)
44
+ if pos3 != 0:
45
+ pos3 = 0
46
+ else:
47
+ pos3 = pos3 + len(fmt_str3)
48
+ except:
49
+ pos3 = 0
50
+
51
+ output = output[pos3:]
52
+
53
+ try:
54
+ if mode==2:
55
+ fmt_str4 = ": end\n"
56
+ else:
57
+ fmt_str4 = ">>> end\n"
58
+ pos4 = output.rindex(fmt_str4)
59
+ except:
60
+ pos4 = 0
61
+
62
+ return output[:pos4]
63
+
64
+
65
+ class StataDisplay:
66
+ def write(self, text):
67
+ textList = text.split("\n")
68
+ for t in textList[:-1]:
69
+ config.stlib.StataSO_AppendOutputBuffer(config.get_encode_str(t))
70
+ config.stlib.StataSO_AppendOutputBuffer(config.get_encode_str("\n"))
71
+ config.stlib.StataSO_AppendOutputBuffer(config.get_encode_str(textList[-1]))
72
+
73
+ def flush(self):
74
+ pass
75
+
76
+
77
+ class StataError:
78
+ def write(self, text):
79
+ config.stlib.StataSO_AppendOutputBuffer(config.get_encode_str(text))
80
+
81
+ def flush(self):
82
+ pass
83
+
84
+
85
+ class RedirectOutput:
86
+ """context manager for redirecting stdout/err"""
87
+
88
+ def __init__(self, stdout='', stderr=''):
89
+ self.stdout = stdout
90
+ self.stderr = stderr
91
+
92
+ def __enter__(self):
93
+ self.sys_stdout = sys.stdout
94
+ self.sys_stderr = sys.stderr
95
+
96
+ if self.stdout:
97
+ sys.stdout = self.stdout
98
+ if self.stderr:
99
+ if self.stderr == self.stdout:
100
+ sys.stderr = sys.stdout
101
+ else:
102
+ sys.stderr = self.stderr
103
+
104
+ def __exit__(self, exc_type, exc_value, traceback):
105
+ sys.stdout = self.sys_stdout
106
+ sys.stderr = self.sys_stderr
107
+
108
+ def _print_streaming_output(output, newline):
109
+ if config.pyversion[0] >= 3:
110
+ if newline:
111
+ print(output, flush=True, file=config.stoutputf)
112
+ else:
113
+ print(output, end='', flush=True, file=config.stoutputf)
114
+ else:
115
+ if newline:
116
+ print(config.get_encode_str(output), file=config.stoutputf)
117
+ else:
118
+ print(config.get_encode_str(output), end='', file=config.stoutputf)
119
+
120
+ sys.stdout.flush()
121
+
122
+
123
+ class RepeatTimer(threading.Thread):
124
+ def __init__(self, tname, otype, queue, interval, real_cmd, colon, mode):
125
+ threading.Thread.__init__(self, name=tname)
126
+ self.q = queue
127
+ self.otype = otype
128
+ self.interval = interval
129
+ self.is_done = False
130
+ self.old_stdout = sys.stdout
131
+ self.old_stderr = sys.stderr
132
+ self.real_cmd = real_cmd
133
+ self.colon = colon
134
+ self.mode = mode
135
+
136
+ def done(self):
137
+ sys.stdout = self.old_stdout
138
+ sys.stderr = self.old_stderr
139
+ self.is_done = True
140
+
141
+ def run(self):
142
+ while not self.is_done:
143
+ self.sys_stdout = sys.stdout
144
+ self.sys_stderr = sys.stderr
145
+ sys.stdout = self.old_stdout
146
+ sys.stderr = self.old_stderr
147
+ output = config.get_output()
148
+ if self.q.empty():
149
+ if len(output)!=0:
150
+ if self.mode!=1 and self.otype==2:
151
+ output = output_get_interactive_result(output, self.real_cmd, self.colon, self.mode)
152
+
153
+ _print_streaming_output(output, False)
154
+ else:
155
+ rc = self.q.get()
156
+ self.done()
157
+ if rc == 0:
158
+ if self.otype==1:
159
+ if len(output)!=0:
160
+ _print_streaming_output(output, False)
161
+ else:
162
+ if self.mode!=1:
163
+ output = output_get_interactive_result(output, self.real_cmd, self.colon, self.mode)
164
+ _print_streaming_output(output, False)
165
+ else:
166
+ _print_streaming_output(output, True)
167
+ else:
168
+ if self.otype==1:
169
+ raise SystemError(output)
170
+ else:
171
+ if rc!=3000:
172
+ if self.mode!=1:
173
+ output = output_get_interactive_result(output, self.real_cmd, self.colon, self.mode)
174
+ _print_streaming_output(output, False)
175
+ else:
176
+ raise SystemError(output)
177
+
178
+ sys.stdout = self.sys_stdout
179
+ sys.stderr = self.sys_stderr
180
+ time.sleep(self.interval)
pystata/ipython/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pystata.config import check_initialized
2
+
3
+ check_initialized()
4
+
5
+ from . import stpymagic
pystata/ipython/grdisplay.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pystata.config import stlib, stconfig, get_encode_str
2
+ from IPython.display import SVG, display, Image
3
+ from pystata.ipython.ipy_utils import get_ipython_stata_cache_dir
4
+ import sfi
5
+ import os
6
+
7
+ pdf_counter = 0
8
+
9
+ def _get_graphs_info():
10
+ stlib.StataSO_Execute(get_encode_str("qui _gr_list list"), False)
11
+ gnamelist = sfi.Macro.getGlobal("r(_grlist)")
12
+
13
+ graphs_info = []
14
+ for gname in gnamelist.split():
15
+ graphs_info.append(gname)
16
+
17
+ return graphs_info
18
+
19
+
20
+ class _Pdf_Display_Obj:
21
+ def __init__(self, pdf, width, height):
22
+ self.pdf = pdf
23
+ self.width = width
24
+ self.height = height
25
+
26
+ def _repr_html_(self):
27
+ return '<iframe src={0} width={1} height={2} frameBorder="0"></iframe>'.format(self.pdf, self.width, self.height)
28
+
29
+ def _repr_latex_(self):
30
+ return r'\includegraphics[width=1.0\textwidth,keepaspectratio]{{{0}}}'.format(self.pdf)
31
+
32
+ def __repr__(self):
33
+ return '(file ' + self.pdf + ' written in PDF format)'
34
+
35
+
36
+ def display_stata_graph():
37
+ global pdf_counter
38
+
39
+ grformat = stconfig['grformat']
40
+ grwidth = stconfig['grwidth']
41
+ grheight = stconfig['grheight']
42
+ if grformat=="svg":
43
+ if grwidth[0]=='default':
44
+ gwidth_str = ""
45
+ else:
46
+ if grwidth[1]=='cm':
47
+ gwidth_str = str(round(grwidth[0]/2.54, 3)) + 'in'
48
+ else:
49
+ gwidth_str = str(grwidth[0]) + grwidth[1]
50
+
51
+ if grheight[0]=='default':
52
+ gheight_str = ""
53
+ else:
54
+ if grheight[1]=='cm':
55
+ gheight_str = str(round(grheight[0]/2.54, 3)) + 'in'
56
+ else:
57
+ gheight_str = str(grheight[0]) + grheight[1]
58
+ elif grformat=="png":
59
+ if grwidth[0]=='default':
60
+ gwidth_str = ""
61
+ else:
62
+ if grwidth[1]=='px':
63
+ gwidth_str = str(grwidth[0])
64
+ elif grwidth[1]=='cm':
65
+ gwidth_str = str(int(round(grwidth[0]*96/2.54)))
66
+ else:
67
+ gwidth_str = str(int(round(grwidth[0]*96)))
68
+
69
+ if grheight[0]=='default':
70
+ gheight_str = ""
71
+ else:
72
+ if grheight[1]=='px':
73
+ gheight_str = str(grheight[0])
74
+ elif grheight[1]=='cm':
75
+ gheight_str = str(int(round(grheight[0]*96/2.54)))
76
+ else:
77
+ gheight_str = str(int(round(grheight[0]*96)))
78
+ else:
79
+ gwidth = -1
80
+ gheight = -1
81
+ if grwidth[0]=='default':
82
+ gwidth_str = ""
83
+ else:
84
+ if grwidth[1]=='px':
85
+ gwidth_str = str(grwidth[0]*1.0/96)
86
+ gwidth = grwidth[0]
87
+ elif grwidth[1]=='cm':
88
+ gwidth_str = str(grwidth[0]*1.0/2.54)
89
+ gwidth = grwidth[0]*96/2.54
90
+ else:
91
+ gwidth_str = str(grwidth[0])
92
+ gwidth = grwidth[0]*96
93
+
94
+ if grheight[0]=='default':
95
+ gheight_str = ""
96
+ else:
97
+ if grheight[1]=='px':
98
+ gheight_str = str(grheight[0]*1.0/96)
99
+ gheight = grheight[0]
100
+ elif grheight[1]=='cm':
101
+ gheight_str = str(grheight[0]*1.0/2.54)
102
+ gheight = grheight[0]*96/2.54
103
+ else:
104
+ gheight_str = str(grheight[0])
105
+ gheight = grheight[0]*96
106
+
107
+ if gwidth==-1 and gheight==-1:
108
+ gwidth = 528
109
+ gheight = 384
110
+ elif gwidth==-1:
111
+ gwidth = gheight*528.0/384
112
+ elif gheight==-1:
113
+ gheight = gwidth*384.0/528
114
+
115
+ graphs_info = _get_graphs_info()
116
+ gdir = get_ipython_stata_cache_dir()
117
+ glen = len(graphs_info)
118
+ if glen > 0:
119
+ for i in range(glen):
120
+ gph_disp = 'qui graph display %s' % graphs_info[i]
121
+ rc = stlib.StataSO_Execute(get_encode_str(gph_disp), False)
122
+ if rc!=0:
123
+ continue
124
+
125
+ if grformat=='svg':
126
+ graph_out = os.path.join(gdir, 'temp_graph'+str(i)+'.svg')
127
+ if gwidth_str!="" and gheight_str!="":
128
+ gph_exp = 'qui graph export "%s", name(%s) replace width(%s) height(%s) ' % (graph_out, graphs_info[i], gwidth_str, gheight_str)
129
+ elif gwidth_str!="":
130
+ gph_exp = 'qui graph export "%s", name(%s) replace width(%s) ' % (graph_out, graphs_info[i], gwidth_str)
131
+ elif gheight_str!="":
132
+ gph_exp = 'qui graph export "%s", name(%s) replace height(%s) ' % (graph_out, graphs_info[i], gheight_str)
133
+ else:
134
+ gph_exp = 'qui graph export "%s", name(%s) replace width(528) height(384)' % (graph_out, graphs_info[i])
135
+
136
+ stlib.StataSO_Execute(get_encode_str(gph_exp), False)
137
+ display(SVG(filename=graph_out))
138
+ elif grformat=='png':
139
+ graph_out = os.path.join(gdir, 'temp_graph'+str(i)+'.png')
140
+ if gwidth_str!="" and gheight_str!="":
141
+ gph_exp = 'qui graph export "%s", name(%s) replace width(%s) height(%s) ' % (graph_out, graphs_info[i], gwidth_str, gheight_str)
142
+ elif gwidth_str!="":
143
+ gph_exp = 'qui graph export "%s", name(%s) replace width(%s) ' % (graph_out, graphs_info[i], gwidth_str)
144
+ elif gheight_str!="":
145
+ gph_exp = 'qui graph export "%s", name(%s) replace height(%s) ' % (graph_out, graphs_info[i], gheight_str)
146
+ else:
147
+ gph_exp = 'qui graph export "%s", name(%s) replace ' % (graph_out, graphs_info[i])
148
+
149
+ stlib.StataSO_Execute(get_encode_str(gph_exp), False)
150
+ display(Image(filename=graph_out))
151
+ else:
152
+ graph_out = os.path.join(os.getcwd(), str(pdf_counter)+'.pdf')
153
+ if gwidth_str!="" and gheight_str!="":
154
+ gph_exp = 'qui graph export "%s", name(%s) replace xsize(%s) ysize(%s) ' % (graph_out, graphs_info[i], gwidth_str, gheight_str)
155
+ elif gwidth_str!="":
156
+ gph_exp = 'qui graph export "%s", name(%s) replace xsize(%s) ' % (graph_out, graphs_info[i], gwidth_str)
157
+ elif gheight_str!="":
158
+ gph_exp = 'qui graph export "%s", name(%s) replace ysize(%s) ' % (graph_out, graphs_info[i], gheight_str)
159
+ else:
160
+ gph_exp = 'qui graph export "%s", name(%s) replace ' % (graph_out, graphs_info[i])
161
+
162
+ stlib.StataSO_Execute(get_encode_str(gph_exp), False)
163
+ display(_Pdf_Display_Obj(os.path.relpath(graph_out), int(gwidth*1.1), int(gheight*1.1)))
164
+ pdf_counter += 1
pystata/ipython/ipy_utils.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from IPython import version_info as ipy_version
2
+ if ipy_version[0] < 4:
3
+ from IPython.utils.path import get_ipython_cache_dir
4
+ else:
5
+ from IPython.paths import get_ipython_cache_dir
6
+
7
+ def get_ipython_stata_cache_dir():
8
+ return get_ipython_cache_dir()
pystata/ipython/stpymagic.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, print_function
2
+ import os
3
+ import shlex
4
+
5
+ from pystata import config as _config
6
+ from pystata.stexception import IPythonError, IPyKernelError
7
+
8
+ try:
9
+ from IPython.core.magic import (Magics, magics_class, line_cell_magic, needs_local_scope, line_magic)
10
+ from pystata.ipython.ipy_utils import get_ipython_stata_cache_dir
11
+ except ImportError:
12
+ _config.stipython = 1
13
+ raise IPythonError('failed to import IPython package')
14
+
15
+ from pystata import stata as _stata
16
+
17
+ if not _stata.has_num_pand['pknum']:
18
+ _config.stipython = 3
19
+ elif not _stata.has_num_pand['pkpand']:
20
+ _config.stipython = 4
21
+
22
+ if _stata.has_num_pand['pknum']:
23
+ import numpy as np
24
+
25
+ if _stata.has_num_pand['pkpand']:
26
+ import pandas as pd
27
+ from pystata.core import numpy2mata as _mata
28
+
29
+ from IPython import get_ipython
30
+
31
+
32
+ def _parse_arguments(inopts, allowopts, magicname):
33
+ res = {}
34
+ errmsg = 'Type ' + magicname + ' to get more information.'
35
+
36
+ opts = shlex.split(inopts, posix=False)
37
+
38
+ olen = len(opts)
39
+ if olen==0:
40
+ return res
41
+
42
+ i = 0
43
+ while i < olen:
44
+ if opts[i][0]=='-' and ':' in opts[i]:
45
+ raise SyntaxError('option ' + opts[i] + ' not allowed. ' + errmsg)
46
+
47
+ if i==(olen-1):
48
+ if opts[i] in allowopts:
49
+ res[opts[i]] = ''
50
+ i += 1
51
+ else:
52
+ tmp = opts[i] + ':'
53
+ if tmp in allowopts:
54
+ raise SyntaxError('A value is required for option ' + opts[i] + '. ' + errmsg)
55
+ else:
56
+ raise SyntaxError('option ' + opts[i] + ' not allowed. ' + errmsg)
57
+ else:
58
+ if opts[i] in allowopts:
59
+ if opts[i+1][0] != '-':
60
+ raise SyntaxError('option ' + opts[i] + ' misspecified. ' + errmsg)
61
+ else:
62
+ res[opts[i]] = ''
63
+ i += 1
64
+ else:
65
+ tmp = opts[i] + ':'
66
+ if tmp in allowopts:
67
+ if opts[i+1][0] == '-':
68
+ raise SyntaxError('option ' + opts[i] + ' misspecified. ' + errmsg)
69
+ else:
70
+ res[opts[i]] = opts[i+1]
71
+ i += 2
72
+ else:
73
+ raise SyntaxError('option ' + opts[i] + ' not allowed. ' + errmsg)
74
+
75
+ return res
76
+
77
+
78
+ def _get_input_type(o):
79
+ if _stata.has_num_pand['pknum']:
80
+ if isinstance(o, np.ndarray):
81
+ return 1
82
+
83
+ if _stata.has_num_pand['pkpand']:
84
+ if isinstance(o, pd.DataFrame):
85
+ return 2
86
+
87
+ return 0
88
+
89
+
90
+ @magics_class
91
+ class PyStataMagic(Magics):
92
+
93
+ def __init__(self, shell):
94
+ super(PyStataMagic, self).__init__(shell)
95
+ self._lib_dir = os.path.join(get_ipython_stata_cache_dir(), 'stata')
96
+ if not os.path.exists(self._lib_dir):
97
+ os.makedirs(self._lib_dir)
98
+
99
+ @needs_local_scope
100
+ @line_cell_magic
101
+ def stata(self, line, cell=None, local_ns=None):
102
+ '''
103
+ Execute one line or a block of Stata commands.
104
+
105
+ When the line magic command **%stata** is used, a one-line Stata
106
+ command can be specified and executed, as it would be in Stata's
107
+ Command window. When the cell magic command **%%stata** is used, a
108
+ block of Stata commands can be specified and executed all at once.
109
+ This is similar to executing a series of commands from a do-file.
110
+
111
+ Cell magic syntax:
112
+
113
+ %%stata [-d DATA] [-f DFLIST|ARRLIST] [-force]
114
+ [-doutd DATAFRAME] [-douta ARRAY] [-foutd FRAMELIST] [-fouta FRAMELIST]
115
+ [-ret DICTIONARY] [-eret DICTIONARY] [-sret DICTIONARY] [-qui] [-nogr]
116
+ [-gw WIDTH] [-gh HEIGHT]
117
+
118
+ Optional arguments:
119
+
120
+ -d DATA Load a NumPy array or pandas dataframe
121
+ into Stata as the current working dataset.
122
+
123
+ -f DFLIST|ARRLIST Load one or multiple NumPy arrays or
124
+ pandas dataframes into Stata as frames.
125
+ The arrays and dataframes should be
126
+ separated by commas. Each array or
127
+ dataframe is stored in Stata as a separate
128
+ frame with the same name.
129
+
130
+ -force Force loading of the NumPy array or pandas
131
+ dataframe into Stata as the current working
132
+ dataset, even if the dataset in memory has
133
+ changed since it was last saved; or force
134
+ loading of the NumPy arrays or pandas dataframes
135
+ into Stata as separate frames even if one or
136
+ more of the frames already exist in Stata.
137
+
138
+ -doutd DATAFRAME Save the dataset in memory as a pandas
139
+ dataframe when the cell completes.
140
+
141
+ -douta ARRAY Save the dataset in memory as a NumPy
142
+ array when the cell completes.
143
+
144
+ -foutd FRAMELIST Save one or multiple Stata frames as pandas
145
+ dataframes when the cell completes. The Stata
146
+ frames should be separated by commas. Each
147
+ frame is stored in Python as a pandas
148
+ dataframe. The variable names in each frame
149
+ will be used as the column names in the
150
+ corresponding dataframe.
151
+
152
+ -fouta FRAMELIST Save one or multiple Stata frames as NumPy
153
+ arrays when the cell completes. The Stata frames
154
+ should be separated by commas. Each frame is
155
+ stored in Python as a NumPy array.
156
+
157
+ -ret DICTIONARY Store current r() results into a dictionary.
158
+
159
+ -eret DICTIONARY Store current e() results into a dictionary.
160
+
161
+ -sret DICTIONARY Store current s() results into a dictionary.
162
+
163
+ -qui Run Stata commands but suppress output.
164
+
165
+ -nogr Do not display Stata graphics.
166
+
167
+ -gw WIDTH Set graph width in inches, pixels, or centimeters;
168
+ default is inches.
169
+
170
+ -gh HEIGHT Set graph height in inches, pixels, or centimeters;
171
+ default is inches.
172
+
173
+
174
+ Line magic syntax:
175
+
176
+ %stata stata_cmd
177
+ '''
178
+ if cell is None:
179
+ if not line:
180
+ raise SyntaxError("Stata command required")
181
+
182
+ _stata.run(line)
183
+ return
184
+
185
+ allowopts = ['-d:', '-f:', '-force', '-doutd:', '-douta:', '-foutd:', '-fouta:', '-ret:', '-eret:', '-sret:', '-qui', '-nogr', '-gw:', '-gh:']
186
+ args = _parse_arguments(line, allowopts, '%%stata?')
187
+
188
+ if local_ns is None:
189
+ local_ns = {}
190
+
191
+ force_to_load = False
192
+ if '-force' in args:
193
+ force_to_load = True
194
+
195
+ if '-d' in args:
196
+ if not _stata.has_num_pand['pknum'] and not _stata.has_num_pand['pkpand']:
197
+ raise SystemError('NumPy package or pandas package is required to use this argument.')
198
+
199
+ data = args['-d']
200
+ try:
201
+ val = local_ns[data]
202
+ except KeyError:
203
+ try:
204
+ val = self.shell.user_ns[data]
205
+ except KeyError:
206
+ raise NameError("name '%s' is not defined" % data)
207
+
208
+
209
+ input_dtype = _get_input_type(val)
210
+ if input_dtype > 0:
211
+ try:
212
+ if input_dtype==2:
213
+ _stata.pdataframe_to_data(val, force=force_to_load)
214
+ else:
215
+ _stata.nparray_to_data(val, force=force_to_load)
216
+ except SystemError:
217
+ raise
218
+ except:
219
+ raise SystemError("Exception occurred. Data could not be loaded.")
220
+ else:
221
+ raise TypeError("A pandas dataframe or NumPy array is required.")
222
+
223
+ if '-f' in args:
224
+ if not _stata.has_num_pand['pknum'] and not _stata.has_num_pand['pkpand']:
225
+ raise SystemError('NumPy package or pandas package is required to use this argument.')
226
+
227
+ frames = args['-f'].replace("'", '').replace('"', '').split(',')
228
+ for fr in frames:
229
+ try:
230
+ frval = local_ns[fr]
231
+ except KeyError:
232
+ try:
233
+ frval = self.shell.user_ns[fr]
234
+ except KeyError:
235
+ raise NameError("name '%s' is not defined" % fr)
236
+
237
+ input_ftype = _get_input_type(frval)
238
+ if input_ftype==0:
239
+ raise TypeError("%s is not a pandas dataframe or NumPy array. Only dataframe or array is allowed." % fr)
240
+
241
+ for fr in frames:
242
+ try:
243
+ frval = local_ns[fr]
244
+ except KeyError:
245
+ frval = self.shell.user_ns[fr]
246
+
247
+ input_ftype = _get_input_type(frval)
248
+ try:
249
+ if input_ftype==2:
250
+ _stata.pdataframe_to_frame(frval, fr, force=force_to_load)
251
+ else:
252
+ _stata.nparray_to_frame(frval, fr, force=force_to_load)
253
+ except SystemError:
254
+ raise
255
+ except:
256
+ raise SystemError("Exception occurred. %s could not be loaded." % fr)
257
+
258
+
259
+ if '-gw' in args or '-gh' in args:
260
+ gwidth = _config.get_graph_size_str('gw')
261
+ gheight = _config.get_graph_size_str('gh')
262
+ if '-gw' in args and '-gh' in args:
263
+ _config.set_graph_size(args['-gw'], args['-gh'])
264
+ elif '-gw' in args:
265
+ _config.set_graph_size(args['-gw'], None)
266
+ else:
267
+ _config.set_graph_size(None, args['-gh'])
268
+
269
+ if '-nogr' in args:
270
+ grshow = _config.stconfig['grshow']
271
+ _config.set_graph_show(False)
272
+
273
+ if '-qui' in args:
274
+ _stata.run(cell, quietly=True, inline=_config.stconfig['grshow'])
275
+ else:
276
+ _stata.run(cell, quietly=False, inline=_config.stconfig['grshow'])
277
+
278
+ if '-gw' in args or '-gh' in args:
279
+ _config.set_graph_size(gwidth, gheight)
280
+
281
+ if '-nogr' in args:
282
+ _config.set_graph_show(grshow)
283
+
284
+ if '-ret' in args or '-eret' in args or '-sret' in args:
285
+ if '-ret' in args:
286
+ val = _stata.get_return()
287
+ self.shell.push({args['-ret']: val })
288
+
289
+ if '-eret' in args:
290
+ val = _stata.get_ereturn()
291
+ self.shell.push({args['-eret']: val })
292
+
293
+ if '-sret' in args:
294
+ val = _stata.get_sreturn()
295
+ self.shell.push({args['-sret']: val })
296
+
297
+ if '-doutd' in args:
298
+ if not _stata.has_num_pand['pkpand']:
299
+ raise SystemError('pandas package is required to use this argument.')
300
+
301
+ try:
302
+ output_df = _stata.pdataframe_from_data()
303
+ self.shell.push({args['-doutd']: output_df })
304
+ except:
305
+ print("Exception occurred. Data could not be written to the dataframe.")
306
+
307
+ if '-douta' in args:
308
+ if not _stata.has_num_pand['pknum']:
309
+ raise SystemError('NumPy package is required to use this argument.')
310
+
311
+ try:
312
+ output_arr = _stata.nparray_from_data()
313
+ self.shell.push({args['-douta']: output_arr })
314
+ except:
315
+ print("Exception occurred. Data could not be written to the array.")
316
+
317
+ if '-foutd' in args:
318
+ if not _stata.has_num_pand['pkpand']:
319
+ raise SystemError('pandas package is required to use this argument.')
320
+
321
+ frames = args['-foutd'].replace("'", '').replace('"', '').split(',')
322
+ output_dfs = {}
323
+ for fr in frames:
324
+ try:
325
+ output_df = _stata.pdataframe_from_frame(fr)
326
+ output_dfs[fr] = output_df
327
+ except:
328
+ raise SystemError("Exception occurred. Stata's frame %s could not be saved to a pandas dataframe." % fr)
329
+
330
+ self.shell.push(output_dfs)
331
+
332
+ if '-fouta' in args:
333
+ if not _stata.has_num_pand['pknum']:
334
+ raise SystemError('NumPy package is required to use this argument.')
335
+
336
+ frames = args['-fouta'].replace("'", '').replace('"', '').split(',')
337
+ output_arrs = {}
338
+ for fr in frames:
339
+ try:
340
+ output_arr = _stata.nparray_from_frame(fr)
341
+ output_arrs[fr] = output_arr
342
+ except:
343
+ raise SystemError("Exception occurred. Stata's frame %s could not be saved to a NumPy array." % fr)
344
+
345
+ self.shell.push(output_arrs)
346
+
347
+
348
+ @needs_local_scope
349
+ @line_cell_magic
350
+ def mata(self, line, cell=None, local_ns=None):
351
+ '''
352
+ Execute one line or a block of Mata code.
353
+
354
+ When the **%mata** line magic command is used, one line of Mata code
355
+ can be specified and executed. This is similar to specifying
356
+ **mata: istmt** within Stata. When the **%%mata** cell magic command is
357
+ used, a block of Mata code can be specified. The code is executed just
358
+ as it would be in a do-file.
359
+
360
+ Cell magic syntax:
361
+
362
+ %%mata [-m ARRAYLIST] [-outm MATLIST] [-qui] [-c]
363
+
364
+ Execute a block of Mata code. This is equivalent to running a
365
+ block of Mata code within a do-file. You do not need to
366
+ explicitly place the code within the mata[:] and end block.
367
+
368
+ Optional arguments:
369
+
370
+ -m ARRAYLIST Load multiple NumPy arrays into Mata's
371
+ interactive environment. The array names
372
+ should be separated by commas. Each array is
373
+ stored in Mata as a matrix with the same name.
374
+
375
+ -outm MATLIST Save Mata matrices as NumPy arrays when the
376
+ cell completes. The matrix names should be
377
+ separated by commas. Each matrix is stored
378
+ in Python as a NumPy array.
379
+
380
+ -qui Run Mata code but suppress output.
381
+
382
+ -c This argument specifies that Mata code be
383
+ executed in mata: mode. This means that
384
+ if Mata encounters an error, it will stop
385
+ execution and return control to Python. The
386
+ error will then be thrown as a Python SystemError
387
+ exception.
388
+
389
+
390
+ Line magic syntax:
391
+
392
+ %mata [-c]
393
+
394
+ Enter Mata's interactive environment. This is equivalent to
395
+ typing mata or mata: in the Stata Command window.
396
+
397
+ Optional argument:
398
+
399
+ -c Enter interactive Mata environment in mata:
400
+ mode. The default is to enter in mata mode.
401
+
402
+ %mata istmt
403
+
404
+ Run a single-line Mata statement. This is equivalent to executing
405
+ mata: istmt within Stata.
406
+ '''
407
+ if cell is None:
408
+ if not line:
409
+ stcmd = "mata"
410
+ elif line=='-c':
411
+ stcmd = 'mata:'
412
+ else:
413
+ stcmd = "mata: " + line
414
+
415
+ _stata.run(stcmd, inline=False)
416
+ else:
417
+ allowopts = ['-qui', '-c', '-m:', '-outm:']
418
+ args = _parse_arguments(line, allowopts, '%%mata?')
419
+
420
+ if local_ns is None:
421
+ local_ns = {}
422
+
423
+ if '-m' in args:
424
+ if not _stata.has_num_pand['pknum']:
425
+ raise SystemError('NumPy package is required to use this argument.')
426
+
427
+ mats = args['-m'].replace("'", '').replace('"', '').split(',')
428
+ for m in mats:
429
+ try:
430
+ mval = local_ns[m]
431
+ except KeyError:
432
+ try:
433
+ mval = self.shell.user_ns[m]
434
+ except KeyError:
435
+ raise NameError("name '%s' is not defined" % m)
436
+
437
+ for m in mats:
438
+ try:
439
+ mval = local_ns[m]
440
+ except KeyError:
441
+ mval = self.shell.user_ns[m]
442
+
443
+ try:
444
+ _mata.array_to_mata(mval, m)
445
+ except:
446
+ print("Exception occurred. Array %s could not be loaded." % m)
447
+
448
+
449
+ if cell[-1:] != '\n':
450
+ cell = cell + '\n'
451
+
452
+ if '-c' in args:
453
+ cell = "mata:\n" + cell + "end"
454
+ else:
455
+ cell = "mata\n" + cell + "end"
456
+
457
+ if '-qui' in args:
458
+ _stata.run(cell, quietly=True, inline=False)
459
+ else:
460
+ _stata.run(cell, inline=False)
461
+
462
+
463
+ if '-outm' in args:
464
+ if not _stata.has_num_pand['pknum']:
465
+ raise SystemError('NumPy package is required to use this argument.')
466
+
467
+ mats = args['-outm'].replace("'", '').replace('"', '').split(',')
468
+ output_arrs = {}
469
+ for m in mats:
470
+ try:
471
+ output_arr = _mata.array_from_mata(m)
472
+ output_arrs[m] = output_arr
473
+ except:
474
+ print("Exception occurred. Mata matrix %s could not be written to a NumPy array." % m)
475
+
476
+ self.shell.push(output_arrs)
477
+
478
+
479
+ @line_magic
480
+ def pystata(self, line):
481
+ '''
482
+ Stata utility commands.
483
+
484
+ Line magic syntax:
485
+
486
+ %pystata status
487
+
488
+ Display current system information and settings.
489
+
490
+
491
+ %pystata set graph_show True|False [, perm]
492
+
493
+ Set whether Stata graphics are displayed. The default is to
494
+ display the graphics. Note that if multiple graphs are
495
+ generated, only the last one is displayed. To display multiple
496
+ graphs, use the name() option with Stata's graph commands.
497
+
498
+
499
+ %pystata set graph_size w #[in|px|cm] [, perm]
500
+ %pystata set graph_size h #[in|px|cm] [, perm]
501
+ %pystata set graph_size w #[in|px|cm] h #[in|px|cm] [, perm]
502
+
503
+ Set dimensions for Stata graphs. The default is a 5.5-inch width
504
+ and 4-inch height. Values may be specified in inches, pixels, or
505
+ centimeters; the default unit is inches. Either the width or height
506
+ must be specified, or both. If only one is specified, the other one
507
+ is determined by the aspect ratio.
508
+
509
+
510
+ %pystata set graph_format svg|png|pdf [, perm]
511
+
512
+ Set the graphic format used to display Stata graphs. The default
513
+ is svg. If svg or png is specified, the graphs will be embedded.
514
+ If pdf is specified, the graphs will be displayed, and exported
515
+ to PDF files and stored in the current working directory with
516
+ numeric names, such as 0.pdf, 1.pdf, 2.pdf, etc. Storing the PDF
517
+ graph files in the current directory allows you to embed them in
518
+ the notebook when exporting the notebook to a PDF via Latex.
519
+ '''
520
+ if line is None:
521
+ raise SyntaxError('subcommand required')
522
+
523
+ scmd = line.strip().split(',')
524
+ if len(scmd)>=3:
525
+ raise SyntaxError('invalid syntax')
526
+
527
+ sperm = False
528
+ sopt = scmd[1].strip() if len(scmd)==2 else ""
529
+ if sopt!="":
530
+ if sopt not in ["perm", "perma", "perman", "permane", "permanen", "permanent", "permanentl", "permanently"]:
531
+ raise SyntaxError('option ' + sopt + ' not allowed')
532
+ else:
533
+ sperm = True
534
+
535
+ scmd = scmd[0].strip().split()
536
+ slen = len(scmd)
537
+ if slen==0:
538
+ raise SyntaxError('subcommand required')
539
+
540
+ subcmd = scmd[0]
541
+ if subcmd=='help':
542
+ if slen!=1:
543
+ topic = ' '.join(scmd[1:])
544
+ else:
545
+ topic = 'help_advice'
546
+
547
+ _stata.run('help ' + topic, inline=False)
548
+ elif subcmd=='status':
549
+ if slen!=1:
550
+ raise SyntaxError(' '.join(scmd[1:]) + ' not allowed')
551
+ else:
552
+ _config.status()
553
+ elif subcmd=='set':
554
+ if slen==1:
555
+ raise SyntaxError('set type must be specified')
556
+
557
+ sset = scmd[1:]
558
+ settype = sset[0]
559
+ if settype=="graph_size":
560
+ if len(sset)!=3 and len(sset)!=5:
561
+ raise ValueError('invalid graph_size set')
562
+
563
+ if len(sset)==3:
564
+ if sset[1]=='width' or sset[1]=='w':
565
+ _config.set_graph_size(width=sset[2], height=None, perm=sperm)
566
+ elif sset[1]=='height' or sset[1]=='h':
567
+ _config.set_graph_size(width=None, height=sset[2], perm=sperm)
568
+ else:
569
+ raise ValueError('invalid graph_size value')
570
+ else:
571
+ if (sset[1]=='width' or sset[1]=='w') and (sset[3]=='height' or sset[3]=='h'):
572
+ _config.set_graph_size(width=sset[2], height=sset[4], perm=sperm)
573
+ elif (sset[1]=='height' or sset[1]=='h') and (sset[3]=='width' or sset[3]=='w'):
574
+ _config.set_graph_size(width=sset[4], height=sset[2], perm=sperm)
575
+ else:
576
+ raise ValueError('invalid graph_size value')
577
+ elif settype=="graph_show":
578
+ if len(sset)!=2:
579
+ raise SyntaxError('invalid graph_show set; only True or False allowed.')
580
+
581
+ if sset[1]=='True':
582
+ _config.set_graph_show(show=True, perm=sperm)
583
+ elif sset[1]=='False':
584
+ _config.set_graph_show(show=False, perm=sperm)
585
+ else:
586
+ raise ValueError('invalid graph_show value')
587
+ elif settype=="graph_format":
588
+ if len(sset)!=2:
589
+ raise SyntaxError('invalid graph_format set')
590
+
591
+ if sset[1]=='svg':
592
+ _config.set_graph_format(gformat='svg', perm=sperm)
593
+ elif sset[1]=='png':
594
+ _config.set_graph_format(gformat='png', perm=sperm)
595
+ elif sset[1]=='pdf':
596
+ _config.set_graph_format(gformat='pdf', perm=sperm)
597
+ else:
598
+ raise ValueError('invalid graph_format value; only svg, png, or pdf allowed.')
599
+ elif settype=="streaming_output_mode":
600
+ if len(sset)!=2:
601
+ raise SyntaxError('invalid streaming_output_mode set')
602
+
603
+ if sset[1]=='on':
604
+ _config.set_streaming_output_mode(flag='on', perm=sperm)
605
+ elif sset[1]=='off':
606
+ _config.set_streaming_output_mode(flag='off', perm=sperm)
607
+ else:
608
+ raise ValueError('invalid streaming_output_mode value; only on or off allowed.')
609
+ else:
610
+ raise SyntaxError('invalid set type')
611
+ else:
612
+ raise SyntaxError('invalid subcommand')
613
+
614
+ try:
615
+ ip = get_ipython()
616
+ ip.register_magics(PyStataMagic)
617
+ except AttributeError:
618
+ _config.stipython = 2
619
+ raise IPyKernelError('register_magics not found')
pystata/stata.py ADDED
@@ -0,0 +1,945 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This module contains core functions used to interact with Stata.
3
+ '''
4
+ from __future__ import print_function
5
+ from ctypes import c_char_p, c_void_p, cast
6
+
7
+ from pystata import config
8
+ config.check_initialized()
9
+
10
+ if config.pyversion[0]<3:
11
+ from Queue import LifoQueue
12
+ from codecs import open
13
+ else:
14
+ from queue import LifoQueue
15
+
16
+ import sfi
17
+ from pystata.core import stout
18
+ import codeop
19
+ import sys
20
+
21
+ rc2 = 0
22
+ gr_display_func = None
23
+ has_num_pand = {
24
+ "pknum": True,
25
+ "pkpand": True
26
+ }
27
+
28
+ try:
29
+ from pystata.core import numpy2stata
30
+ except:
31
+ has_num_pand['pknum'] = False
32
+
33
+ try:
34
+ from pystata.core import pandas2stata
35
+ except:
36
+ has_num_pand['pkpand'] = False
37
+
38
+
39
+ def _print_no_streaming_output(output, newline):
40
+ if config.pyversion[0] >= 3:
41
+ if newline:
42
+ print(output, file=config.stoutputf)
43
+ else:
44
+ print(output, end='', file=config.stoutputf)
45
+ else:
46
+ if newline:
47
+ print(config.get_encode_str(output), file=config.stoutputf)
48
+ else:
49
+ print(config.get_encode_str(output), end='', file=config.stoutputf)
50
+
51
+
52
+ def _stata_wrk1(cmd, echo=False):
53
+ if config.stconfig['streamout']=='on':
54
+ try:
55
+ queue = LifoQueue()
56
+ outputter = stout.RepeatTimer('Stata', 1, queue, 0.015, None, None, None)
57
+ outputter.start()
58
+
59
+ with stout.RedirectOutput(stout.StataDisplay(), stout.StataError()):
60
+ rc1 = config.stlib.StataSO_Execute(config.get_encode_str(cmd), echo)
61
+
62
+ queue.put(rc1)
63
+
64
+ outputter.join()
65
+ outputter.done()
66
+ except KeyboardInterrupt:
67
+ outputter.done()
68
+ config.stlib.StataSO_SetBreak()
69
+ print('\nKeyboardInterrupt: --break--')
70
+ else:
71
+ try:
72
+ with stout.RedirectOutput(stout.StataDisplay(), stout.StataError()):
73
+ rc1 = config.stlib.StataSO_Execute(config.get_encode_str(cmd), echo)
74
+
75
+ output = config.get_output()
76
+ while len(output)!=0:
77
+ if rc1 != 0:
78
+ raise SystemError(output)
79
+
80
+ _print_no_streaming_output(output, False)
81
+ output = config.get_output()
82
+ else:
83
+ if rc1 != 0:
84
+ raise SystemError("failed to execute the specified command")
85
+ except KeyboardInterrupt:
86
+ config.stlib.StataSO_SetBreak()
87
+ print('\nKeyboardInterrupt: --break--')
88
+
89
+
90
+ def _stata_wrk2(cmd, real_cmd, colon, mode):
91
+ global rc2
92
+ if config.stconfig['streamout']=='on':
93
+ try:
94
+ queue = LifoQueue()
95
+ outputter = stout.RepeatTimer('Stata', 2, queue, 0.015, real_cmd, colon, mode)
96
+ outputter.start()
97
+
98
+ with stout.RedirectOutput(stout.StataDisplay(), stout.StataError()):
99
+ rc2 = config.stlib.StataSO_Execute(config.get_encode_str(cmd), False)
100
+
101
+ queue.put(rc2)
102
+
103
+ outputter.join()
104
+ outputter.done()
105
+ except KeyboardInterrupt:
106
+ outputter.done()
107
+ config.stlib.StataSO_SetBreak()
108
+ print('\nKeyboardInterrupt: --break--')
109
+ else:
110
+ try:
111
+ with stout.RedirectOutput(stout.StataDisplay(), stout.StataError()):
112
+ rc2 = config.stlib.StataSO_Execute(config.get_encode_str(cmd), False)
113
+
114
+ output = config.get_output()
115
+ if rc2 != 0:
116
+ if rc2 != 3000:
117
+ if mode!=1:
118
+ output = stout.output_get_interactive_result(output, real_cmd, colon, mode)
119
+ _print_no_streaming_output(output, False)
120
+ else:
121
+ raise SystemError(config.get_encode_str(output))
122
+
123
+ else:
124
+ while len(output)!=0:
125
+ output_tmp = config.get_output()
126
+ if len(output_tmp)==0:
127
+ if mode!=1:
128
+ output = stout.output_get_interactive_result(output, real_cmd, colon, mode)
129
+ _print_no_streaming_output(output, False)
130
+ else:
131
+ _print_no_streaming_output(output, True)
132
+ break
133
+ else:
134
+ if mode!=1:
135
+ output = stout.output_get_interactive_result(output, real_cmd, colon, mode)
136
+
137
+ _print_no_streaming_output(output, False)
138
+ output = output_tmp
139
+ except KeyboardInterrupt:
140
+ config.stlib.StataSO_SetBreak()
141
+ print('\nKeyboardInterrupt: --break--')
142
+
143
+
144
+ def _get_user_input(uprompt):
145
+ if config.pyversion[0]==2:
146
+ return raw_input(uprompt)
147
+ else:
148
+ return input(uprompt)
149
+
150
+
151
+ def run(cmd, quietly=False, echo=False, inline=None):
152
+ """
153
+ Run a single line or a block of Stata commands.
154
+
155
+ If a single-line Stata command is specified, the command is run through
156
+ Stata directly. If you need to run a multiple-line command or a block of
157
+ Stata commands, enclose the commands within triple quotes, \""" or \'''.
158
+ The set of commands will be placed in a temporary do-file and executed all
159
+ at once. Because the commands are executed from a do-file, you can add comments
160
+ and delimiters with the specified commands.
161
+
162
+ Parameters
163
+ ----------
164
+ cmd : str
165
+ The commands to execute.
166
+
167
+ quietly : bool, optional
168
+ Suppress output from Stata commands. Default is False. When set to
169
+ True, output will be suppressed.
170
+
171
+ echo : bool, optional
172
+ Echo the command. Default is False. This only affects the output when
173
+ executing a single command.
174
+
175
+ inline : None, True, or False, optional
176
+ Specify whether to export and display the graphs generated by the
177
+ commands, if there are any. If `inline` is not specified or specified as
178
+ None, the global setting specified with
179
+ :meth:`~pystata.config.set_graph_show` is applied.
180
+
181
+ Raises
182
+ ------
183
+ SystemError
184
+ This error can be raised if any of the specified Stata commands result
185
+ in an error.
186
+ """
187
+ global rc2
188
+ config.check_initialized()
189
+
190
+ if inline is None:
191
+ inline = config.stconfig['grshow']
192
+ else:
193
+ if inline is not True and inline is not False:
194
+ raise TypeError('inline must be a boolean value')
195
+
196
+ config.stlib.StataSO_ClearOutputBuffer()
197
+ cmds = cmd.splitlines()
198
+ if len(cmds) == 0:
199
+ return
200
+ elif len(cmds) == 1:
201
+ if inline:
202
+ config.stlib.StataSO_Execute(config.get_encode_str("qui _gr_list on"), False)
203
+
204
+ input_cmd = cmds[0].strip()
205
+ if input_cmd=="mata" or input_cmd=="mata:":
206
+ has_colon = False
207
+ if input_cmd=="mata:":
208
+ has_colon = True
209
+
210
+ print('. ' + input_cmd)
211
+ sfi.SFIToolkit.displayln("{hline 49} mata (type {cmd:end} to exit) {hline}")
212
+ incmd = _get_user_input(": ").strip()
213
+ incmds1 = ""
214
+ incmds2 = ""
215
+ inprompt = ": "
216
+ while incmd!="end":
217
+ incmd = incmd + "\n"
218
+ incmds1 = incmds1 + incmd
219
+ incmd = inprompt + incmd
220
+ incmds2 = incmds2 + incmd
221
+
222
+ tmpf = sfi.SFIToolkit.getTempFile()
223
+ with open(tmpf, 'w', encoding="utf-8") as f:
224
+ f.write(input_cmd+"\n")
225
+ f.write(incmds1)
226
+ f.write("end")
227
+
228
+ if quietly:
229
+ _stata_wrk2("qui include " + tmpf, incmds2, has_colon, 2)
230
+ else:
231
+ _stata_wrk2("include " + tmpf, incmds2, has_colon, 2)
232
+
233
+ if rc2 != 0:
234
+ if rc2 != 3000:
235
+ break
236
+ else:
237
+ incmd = _get_user_input("> ").strip()
238
+ inprompt = "> "
239
+ else:
240
+ incmd = _get_user_input(": ").strip()
241
+ incmds1 = ""
242
+ incmds2 = ""
243
+ inprompt = ": "
244
+ else:
245
+ sfi.SFIToolkit.displayln("{hline}")
246
+ elif input_cmd=="python" or input_cmd=="python:":
247
+ has_colon = False
248
+ if input_cmd=="python:":
249
+ has_colon = True
250
+
251
+ print('. ' + input_cmd)
252
+ sfi.SFIToolkit.displayln("{hline 47} python (type {cmd:end} to exit) {hline}")
253
+ incmd = _get_user_input(">>> ")
254
+ incmds1 = ""
255
+ incmds2 = ""
256
+ inprompt = ">>> "
257
+ while incmd!="end":
258
+ incmds1 = incmds1 + incmd
259
+ incmd = inprompt + incmd
260
+ incmds2 = incmds2 + incmd
261
+
262
+ if incmd[:6]!="stata:":
263
+ res = incmd
264
+ try:
265
+ res = codeop.compile_command(incmds1, '<input>', 'single')
266
+ incmds1 = incmds1 + "\n"
267
+ incmds2 = incmds2 + "\n"
268
+ except (OverflowError, SyntaxError, ValueError):
269
+ pass
270
+ else:
271
+ res = incmd
272
+
273
+ if res is None:
274
+ incmd = _get_user_input("... ")
275
+ inprompt = "... "
276
+ else:
277
+ tmpf = sfi.SFIToolkit.getTempFile()
278
+ with open(tmpf, 'w', encoding="utf-8") as f:
279
+ f.write(input_cmd+"\n")
280
+ f.write(incmds1)
281
+ f.write("end")
282
+
283
+ if quietly:
284
+ _stata_wrk2("qui include " + tmpf, incmds2, has_colon, 3)
285
+ else:
286
+ _stata_wrk2("include " + tmpf, incmds2, has_colon, 3)
287
+
288
+ if rc2 != 0:
289
+ break
290
+
291
+ incmd = _get_user_input(">>> ")
292
+ incmds1 = ""
293
+ incmds2 = ""
294
+ inprompt = ">>> "
295
+ else:
296
+ sfi.SFIToolkit.displayln("{hline}")
297
+ else:
298
+ if quietly:
299
+ _stata_wrk1("qui " + cmds[0], echo)
300
+ else:
301
+ _stata_wrk1(cmds[0], echo)
302
+ else:
303
+ if inline:
304
+ config.stlib.StataSO_Execute(config.get_encode_str("qui _gr_list on"), False)
305
+
306
+ tmpf = sfi.SFIToolkit.getTempFile()
307
+ with open(tmpf, 'w', encoding="utf-8") as f:
308
+ f.write(cmd)
309
+
310
+ if quietly:
311
+ _stata_wrk2("qui include " + tmpf, None, False, 1)
312
+ else:
313
+ _stata_wrk2("include " + tmpf, None, False, 1)
314
+
315
+ if inline:
316
+ if config.get_stipython()>=3:
317
+ global gr_display_func
318
+ if gr_display_func is None:
319
+ from pystata.ipython.grdisplay import display_stata_graph
320
+ gr_display_func = display_stata_graph
321
+
322
+ gr_display_func()
323
+
324
+ config.stlib.StataSO_Execute(config.get_encode_str("qui _gr_list off"), False)
325
+
326
+
327
+ def nparray_to_data(arr, prefix='v', force=False):
328
+ """
329
+ Load a NumPy array into Stata's memory, making it the current dataset.
330
+
331
+ When the data type of the array conforms to a Stata variable type, this
332
+ variable type will be used in Stata. Otherwise, each column of the array
333
+ will be converted into a string variable in Stata.
334
+
335
+ By default, **v1**, **v2**, ... are used as the variable names in Stata. If
336
+ `prefix` is specified, it will be used as the variable prefix for all the
337
+ variables loaded into Stata.
338
+
339
+ If there is a dataset in memory and it has been changed since it was last
340
+ saved, an attempt to load a NumPy array into Stata will raise an exception.
341
+ The `force` argument will force loading of the array, replacing the dataset
342
+ in memory.
343
+
344
+ Parameters
345
+ ----------
346
+ arr : NumPy array
347
+ The array to be loaded.
348
+
349
+ prefix : str, optional
350
+ The string to be used as the variable prefix. Default is **v**.
351
+
352
+ force : bool, optional
353
+ Force loading of the array into Stata. Default is False.
354
+
355
+ Raises
356
+ ------
357
+ SystemError
358
+ This error can be raised if there is a dataset in memory that has
359
+ changed since it was last saved, and `force` is False.
360
+ """
361
+ global has_num_pand
362
+ config.check_initialized()
363
+
364
+ if not has_num_pand['pknum']:
365
+ raise SystemError('NumPy package is required to use this function.')
366
+
367
+ changed = sfi.Scalar.getValue('c(changed)')
368
+ if int(changed)==1 and force is False:
369
+ raise SystemError('no; dataset in memory has changed since last saved')
370
+
371
+ if int(changed)==0 or force is True:
372
+ run('clear')
373
+
374
+ numpy2stata.array_to_stata(arr, None, prefix)
375
+
376
+
377
+ def pdataframe_to_data(df, force=False):
378
+ """
379
+ Load a pandas DataFrame into Stata's memory, making it the current dataset.
380
+
381
+ Each column of the DataFrame will be stored as a variable. If the column
382
+ type conforms to a Stata variable type, the variable type will be used in
383
+ Stata. Otherwise, the column will be converted into a string variable in
384
+ Stata.
385
+
386
+ The variable names will correspond to the column names of the DataFrame. If
387
+ the column name is a valid Stata name, it will be used as the variable
388
+ name. If it is not a valid Stata name, a valid variable name is created by
389
+ using the
390
+ `makeVarName() <https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.makeVarName>`__
391
+ method of the `SFIToolkit <https://www.stata.com/python/api17/SFIToolkit.html>`__
392
+ class in the `Stata Function Interface (sfi) <https://www.stata.com/python/api17/>`__ module.
393
+
394
+ If there is a dataset in memory and it has been changed since it was last
395
+ saved, an attempt to load a DataFrame into Stata will raise an exception.
396
+ The `force` argument will force loading of the DataFrame, replacing the
397
+ dataset in memory.
398
+
399
+ Parameters
400
+ ----------
401
+ df : pandas DataFrame
402
+ The DataFrame to be loaded.
403
+
404
+ force : bool, optional
405
+ Force loading of the DataFrame into Stata. Default is False.
406
+
407
+ Raises
408
+ ------
409
+ SystemError
410
+ This error can be raised if there is a dataset in memory that has been
411
+ changed since it was last saved, and `force` is False.
412
+ """
413
+ global has_num_pand
414
+ config.check_initialized()
415
+
416
+ if not has_num_pand['pkpand']:
417
+ raise SystemError('pandas package is required to use this function.')
418
+
419
+ changed = sfi.Scalar.getValue('c(changed)')
420
+ if int(changed)==1 and force is False:
421
+ raise SystemError('no; dataset in memory has changed since last saved')
422
+
423
+ if int(changed)==0 or force is True:
424
+ run('clear')
425
+
426
+ pandas2stata.dataframe_to_stata(df, None)
427
+
428
+
429
+ class _DefaultMissing:
430
+ def __repr__(self):
431
+ return "_DefaultMissing()"
432
+
433
+
434
+ def nparray_from_data(var=None, obs=None, selectvar=None, valuelabel=False, missingval=_DefaultMissing()):
435
+ """
436
+ Export values from the current Stata dataset into a NumPy array.
437
+
438
+ Parameters
439
+ ----------
440
+ var : int, str, or list-like, optional
441
+ Variables to access. It can be specified as a single variable
442
+ index or name, or an iterable of variable indices or names.
443
+ If `var` is not specified, all the variables are specified.
444
+
445
+ obs : int or list-like, optional
446
+ Observations to access. It can be specified as a single
447
+ observation index or an iterable of observation indices.
448
+ If `obs` is not specified, all the observations are specified.
449
+
450
+ selectvar : int or str, optional
451
+ Observations for which `selectvar!=0` will be selected. If `selectvar`
452
+ is an integer, it is interpreted as a variable index. If `selectvar`
453
+ is a string, it should contain the name of a Stata variable.
454
+ Specifying `selectvar` as "" has the same result as not
455
+ specifying `selectvar`, which means no observations are excluded.
456
+ Specifying `selectvar` as -1 means that observations with missing
457
+ values for the variables specified in `var` are to be excluded.
458
+
459
+ valuelabel : bool, optional
460
+ Use the value label when available. Default is False.
461
+
462
+ missingval : :ref:`_DefaultMissing <ref-defaultmissing>`, `optional`
463
+ If `missingval` is specified, all the missing values in the returned
464
+ list are replaced by this value. If it is not specified, the numeric
465
+ value of the corresponding missing value in Stata is returned.
466
+
467
+ Returns
468
+ -------
469
+ NumPy array
470
+ A NumPy array containing the values from the dataset in memory.
471
+
472
+ Raises
473
+ ------
474
+ ValueError
475
+ This error can be raised for three possible reasons. One is if any of
476
+ the variable indices or names specified in `var` are out of
477
+ `range <https://www.stata.com/python/api17/Data.html#ref-datarange>`__
478
+ or not found. Another is if any of the observation indices specified
479
+ in `obs` are out of range. Last, it may be raised if `selectvar` is out of
480
+ range or not found.
481
+
482
+
483
+ .. _ref-defaultmissing:
484
+
485
+ Notes
486
+ -----
487
+ The definition of the utility class **_DefaultMissing** is as follows::
488
+
489
+ class _DefaultMissing:
490
+ def __repr__(self):
491
+ return "_DefaultMissing()"
492
+
493
+ This class is defined only for the purpose of specifying the default
494
+ value for the parameter `missingval` of the above function. Users are
495
+ not recommended to use this class for any other purpose.
496
+ """
497
+ global has_num_pand
498
+ config.check_initialized()
499
+
500
+ if not has_num_pand['pknum']:
501
+ raise SystemError('NumPy package is required to use this function.')
502
+
503
+ if isinstance(missingval, _DefaultMissing):
504
+ return numpy2stata.array_from_stata(None, var, obs, selectvar, valuelabel, None)
505
+ else:
506
+ return numpy2stata.array_from_stata(None, var, obs, selectvar, valuelabel, missingval)
507
+
508
+
509
+ def pdataframe_from_data(var=None, obs=None, selectvar=None, valuelabel=False, missingval=_DefaultMissing()):
510
+ """
511
+ Export values from the current Stata dataset into a pandas DataFrame.
512
+
513
+ Parameters
514
+ ----------
515
+ var : int, str, or list-like, optional
516
+ Variables to access. It can be specified as a single variable
517
+ index or name, or an iterable of variable indices or names.
518
+ If `var` is not specified, all the variables are specified.
519
+
520
+ obs : int or list-like, optional
521
+ Observations to access. It can be specified as a single
522
+ observation index or an iterable of observation indices.
523
+ If `obs` is not specified, all the observations are specified.
524
+
525
+ selectvar : int or str, optional
526
+ Observations for which `selectvar!=0` will be selected. If `selectvar`
527
+ is an integer, it is interpreted as a variable index. If `selectvar`
528
+ is a string, it should contain the name of a Stata variable.
529
+ Specifying `selectvar` as "" has the same result as not
530
+ specifying `selectvar`, which means no observations are excluded.
531
+ Specifying `selectvar` as -1 means that observations with missing
532
+ values for the variables specified in `var` are to be excluded.
533
+
534
+ valuelabel : bool, optional
535
+ Use the value label when available. Default is False.
536
+
537
+ missingval : :ref:`_DefaultMissing <ref-defaultmissing>`, `optional`
538
+ If `missingval` is specified, all the missing values in the returned
539
+ list are replaced by this value. If it is not specified, the numeric
540
+ value of the corresponding missing value in Stata is returned.
541
+
542
+ Returns
543
+ -------
544
+ pandas DataFrame
545
+ A pandas DataFrame containing the values from the dataset in memory.
546
+
547
+ Raises
548
+ ------
549
+ ValueError
550
+ This error can be raised for three possible reasons. One is if any of
551
+ the variable indices or names specified in `var` are out of
552
+ `range <https://www.stata.com/python/api17/Data.html#ref-datarange>`__
553
+ or not found. Another is if any of the observation indices specified
554
+ in `obs` are out of range. Last, it may be raised if `selectvar` is out of
555
+ range or not found.
556
+ """
557
+ global has_num_pand
558
+ config.check_initialized()
559
+
560
+ if not has_num_pand['pkpand']:
561
+ raise SystemError('pandas package is required to use this function.')
562
+
563
+ if isinstance(missingval, _DefaultMissing):
564
+ return(pandas2stata.dataframe_from_stata(None, var, obs, selectvar, valuelabel, None))
565
+ else:
566
+ return(pandas2stata.dataframe_from_stata(None, var, obs, selectvar, valuelabel, missingval))
567
+
568
+
569
+ def nparray_to_frame(arr, stfr, prefix='v', force=False):
570
+ """
571
+ Load a NumPy array into a specified frame in Stata.
572
+
573
+ When the data type of the array conforms to a Stata variable type, this
574
+ variable type will be used in the frame. Otherwise, each column of the
575
+ array will be converted into a string variable in the frame.
576
+
577
+ By default, **v1**, **v2**, ... are used as the variable names in the frame.
578
+ If `prefix` is specified, it will be used as the variable prefix for all the
579
+ variables loaded into the frame.
580
+
581
+ If the frame of the specified name already exists in Stata, an attempt to load
582
+ a NumPy array into the frame will raise an exception. The `force` argument will
583
+ force loading of the array, replacing the original frame.
584
+
585
+ Parameters
586
+ ----------
587
+ arr : NumPy array
588
+ The array to be loaded.
589
+
590
+ stfr : str
591
+ The frame in which to store the array.
592
+
593
+ prefix : str, optional
594
+ The string to be used as the variable prefix. Default is **v**.
595
+
596
+ force : bool, optional
597
+ Force loading of the array into the frame if the frame already exists.
598
+ Default is False.
599
+
600
+ Raises
601
+ ------
602
+ SystemError
603
+ This error can be raised if the specified frame already exists in
604
+ Stata, and `force` is False.
605
+ """
606
+ global has_num_pand
607
+ config.check_initialized()
608
+
609
+ if not has_num_pand['pknum']:
610
+ raise SystemError('NumPy package is required to use this function.')
611
+
612
+ stframe = None
613
+ try:
614
+ stframe = sfi.Frame.connect(stfr)
615
+ except:
616
+ pass
617
+
618
+ if stframe is not None:
619
+ if force is False:
620
+ raise SystemError('%s already exists.' % stfr)
621
+
622
+ stframe.drop()
623
+
624
+ numpy2stata.array_to_stata(arr, stfr, prefix)
625
+
626
+
627
+ def pdataframe_to_frame(df, stfr, force=False):
628
+ """
629
+ Load a pandas DataFrame into a specified frame in Stata.
630
+
631
+ Each column of the DataFrame will be stored as a variable in the frame.
632
+ If the column type conforms to a Stata variable type, the variable type
633
+ will be used in the frame. Otherwise, the column will be converted into a
634
+ string variable in the frame.
635
+
636
+ The variable names will correspond to the column names of the DataFrame.
637
+ If the column name is a valid Stata name, it will be used as the
638
+ variable name. If it is not a valid Stata name, a valid variable name is
639
+ created by using
640
+ the `makeVarName() <https://www.stata.com/python/api17/SFIToolkit.html#sfi.SFIToolkit.makeVarName>`__
641
+ method of the `SFIToolkit <https://www.stata.com/python/api17/SFIToolkit.html>`__
642
+ class in the `Stata Function Interface (sfi) <https://www.stata.com/python/api17/>`__ module.
643
+
644
+ If the frame of the specified name already exists in Stata, an attempt to
645
+ load a pandas DataFrame into the frame will raise an exception. The `force`
646
+ argument will force loading of the DataFrame, replacing the original frame.
647
+
648
+ Parameters
649
+ ----------
650
+ df : pandas DataFrame
651
+ The DataFrame to be loaded.
652
+
653
+ stfr : str
654
+ The frame in which to store the DataFrame.
655
+
656
+ force : bool, optional
657
+ Force loading of the DataFrame into the frame if the frame already
658
+ exists. Default is False.
659
+
660
+ Raises
661
+ ------
662
+ SystemError
663
+ This error can be raised if the specified frame already exists
664
+ in Stata, and `force` is False.
665
+ """
666
+ global has_num_pand
667
+ config.check_initialized()
668
+
669
+ if not has_num_pand['pkpand']:
670
+ raise SystemError('pandas package is required to use this function.')
671
+
672
+ stframe = None
673
+ try:
674
+ stframe = sfi.Frame.connect(stfr)
675
+ except:
676
+ pass
677
+
678
+ if stframe is not None:
679
+ if force is False:
680
+ raise SystemError('%s already exists.' % stfr)
681
+
682
+ stframe.drop()
683
+
684
+ pandas2stata.dataframe_to_stata(df, stfr)
685
+
686
+
687
+ def nparray_from_frame(stfr, var=None, obs=None, selectvar=None, valuelabel=False, missingval=_DefaultMissing()):
688
+ """
689
+ Export values from a Stata frame into a NumPy array.
690
+
691
+ Parameters
692
+ ----------
693
+ stfr : str
694
+ The Stata frame to export.
695
+
696
+ var : int, str, or list-like, optional
697
+ Variables to access. It can be specified as a single variable
698
+ index or name, or an iterable of variable indices or names.
699
+ If `var` is not specified, all the variables are specified.
700
+
701
+ obs : int or list-like, optional
702
+ Observations to access. It can be specified as a single
703
+ observation index or an iterable of observation indices.
704
+ If `obs` is not specified, all the observations are specified.
705
+
706
+ selectvar : int or str, optional
707
+ Observations for which `selectvar!=0` will be selected. If `selectvar`
708
+ is an integer, it is interpreted as a variable index. If `selectvar`
709
+ is a string, it should contain the name of a Stata variable.
710
+ Specifying `selectvar` as "" has the same result as not
711
+ specifying `selectvar`, which means no observations are excluded.
712
+ Specifying `selectvar` as -1 means that observations with missing
713
+ values for the variables specified in `var` are to be excluded.
714
+
715
+ valuelabel : bool, optional
716
+ Use the value label when available. Default is False.
717
+
718
+ missingval : :ref:`_DefaultMissing <ref-defaultmissing>`, `optional`
719
+ If `missingval` is specified, all the missing values in the returned
720
+ list are replaced by this value. If it is not specified, the numeric
721
+ value of the corresponding missing value in Stata is returned.
722
+
723
+ Returns
724
+ -------
725
+ NumPy array
726
+ A NumPy array containing the values from the Stata frame.
727
+
728
+ Raises
729
+ ------
730
+ ValueError
731
+ This error can be raised for three possible reasons. One is if any
732
+ of the variable indices or names specified in `var` are out of
733
+ `range <https://www.stata.com/python/api17/Frame.html#ref-framerange>`__
734
+ or not found. Another is if any of the observation indices specified
735
+ in `obs` are out of range. Last, it may be raised if `selectvar` is out of
736
+ range or not found.
737
+
738
+ FrameError
739
+ This `error <https://www.stata.com/python/api17/FrameError.html#sfi.FrameError>`__
740
+ can be raised if the frame `stfr` does not already exist in Stata, or
741
+ if Python fails to connect to the frame.
742
+ """
743
+ global has_num_pand
744
+ config.check_initialized()
745
+
746
+ if not has_num_pand['pknum']:
747
+ raise SystemError('NumPy package is required to use this function.')
748
+
749
+ if isinstance(missingval, _DefaultMissing):
750
+ return numpy2stata.array_from_stata(stfr, var, obs, selectvar, valuelabel, None)
751
+ else:
752
+ return numpy2stata.array_from_stata(stfr, var, obs, selectvar, valuelabel, missingval)
753
+
754
+
755
+ def pdataframe_from_frame(stfr, var=None, obs=None, selectvar=None, valuelabel=False, missingval=_DefaultMissing()):
756
+ """
757
+ Export values from a Stata frame into a pandas DataFrame.
758
+
759
+ Parameters
760
+ ----------
761
+ stfr : str
762
+ The Stata frame to export.
763
+
764
+ var : int, str, or list-like, optional
765
+ Variables to access. It can be specified as a single variable
766
+ index or name, or an iterable of variable indices or names.
767
+ If `var` is not specified, all the variables are specified.
768
+
769
+ obs : int or list-like, optional
770
+ Observations to access. It can be specified as a single
771
+ observation index or an iterable of observation indices.
772
+ If `obs` is not specified, all the observations are specified.
773
+
774
+ selectvar : int or str, optional
775
+ Observations for which `selectvar!=0` will be selected. If `selectvar`
776
+ is an integer, it is interpreted as a variable index. If `selectvar`
777
+ is a string, it should contain the name of a Stata variable.
778
+ Specifying `selectvar` as "" has the same result as not
779
+ specifying `selectvar`, which means no observations are excluded.
780
+ Specifying `selectvar` as -1 means that observations with missing
781
+ values for the variables specified in `var` are to be excluded.
782
+
783
+ valuelabel : bool, optional
784
+ Use the value label when available. Default is False.
785
+
786
+ missingval : :ref:`_DefaultMissing <ref-defaultmissing>`, `optional`
787
+ If `missingval` is specified, all the missing values in the returned
788
+ list are replaced by this value. If it is not specified, the numeric
789
+ value of the corresponding missing value in Stata is returned.
790
+
791
+ Returns
792
+ -------
793
+ pandas DataFrame
794
+ A pandas DataFrame containing the values from the Stata frame.
795
+
796
+ Raises
797
+ ------
798
+ ValueError
799
+ This error can be raised for three possible reasons. One is if any of
800
+ the variable indices or names specified in `var` are out of
801
+ `range <https://www.stata.com/python/api17/Frame.html#ref-framerange>`__
802
+ or not found. Another is if any of the observation indices specified
803
+ in `obs` are out of range. Last, it may be raised if `selectvar` is out of
804
+ range or not found.
805
+
806
+ FrameError
807
+ This `error <https://www.stata.com/python/api17/FrameError.html#sfi.FrameError>`__
808
+ can be raised if the frame `stfr` does not already exist in Stata,
809
+ or if Python fails to connect to the frame.
810
+ """
811
+ global has_num_pand
812
+ config.check_initialized()
813
+
814
+ if not has_num_pand['pkpand']:
815
+ raise SystemError('pandas package is required to use this function.')
816
+
817
+ if isinstance(missingval, _DefaultMissing):
818
+ return(pandas2stata.dataframe_from_stata(stfr, var, obs, selectvar, valuelabel, None))
819
+ else:
820
+ return(pandas2stata.dataframe_from_stata(stfr, var, obs, selectvar, valuelabel, missingval))
821
+
822
+
823
+ def _get_return_val(res, cat):
824
+ if cat=="r()":
825
+ rrscalar = sfi.SFIToolkit.listReturn("r()", "scalar")
826
+ rscalar = rrscalar.split()
827
+ for rs in rscalar:
828
+ rs = "r(" + rs + ")"
829
+ val = sfi.Scalar.getValue(rs)
830
+ res[rs] = val
831
+
832
+ rrmac = sfi.SFIToolkit.listReturn("r()", "macro")
833
+ rmac = rrmac.split()
834
+ for rs in rmac:
835
+ rs = "r(" + rs + ")"
836
+ val = sfi.Macro.getGlobal(rs)
837
+ res[rs] = val
838
+
839
+ rrmat = sfi.SFIToolkit.listReturn("r()", "matrix")
840
+ rmat = rrmat.split()
841
+ for rm in rmat:
842
+ rm = "r(" + rm + ")"
843
+ val = numpy2stata.array_from_matrix(sfi.Matrix.get(rm))
844
+ res[rm] = val
845
+
846
+ elif cat=="e()":
847
+ eenum = sfi.SFIToolkit.listReturn("e()", "scalar")
848
+ enum = eenum.split()
849
+ for en in enum:
850
+ en = "e(" + en + ")"
851
+ val = sfi.Scalar.getValue(en)
852
+ res[en] = val
853
+
854
+ eestr = sfi.SFIToolkit.listReturn("e()", "macro")
855
+ estr = eestr.split()
856
+ for es in estr:
857
+ es = "e(" + es + ")"
858
+ val = sfi.Macro.getGlobal(es)
859
+ res[es] = val
860
+
861
+ eemat = sfi.SFIToolkit.listReturn("e()", "matrix")
862
+ emat = eemat.split()
863
+ for em in emat:
864
+ em = "e(" + em + ")"
865
+ val = numpy2stata.array_from_matrix(sfi.Matrix.get(em))
866
+ res[em] = val
867
+
868
+ else:
869
+ ssmac = sfi.SFIToolkit.listReturn("s()", "macro")
870
+ smac = ssmac.split()
871
+ for ss in smac:
872
+ ss = "s(" + ss + ")"
873
+ val = sfi.Macro.getGlobal(ss)
874
+ res[ss] = val
875
+
876
+ return res
877
+
878
+
879
+ def get_return():
880
+ """
881
+ Retrieve current **r()** results and store them in a Python dictionary.
882
+
883
+ The keys are Stata's macro and scalar names, and the values are their
884
+ corresponding values. Stata's matrices are converted into NumPy arrays.
885
+
886
+ Returns
887
+ -------
888
+ Dictionary
889
+ A dictionary containing current **r()** results.
890
+ """
891
+ global has_num_pand
892
+ config.check_initialized()
893
+
894
+ if not has_num_pand['pknum']:
895
+ raise SystemError('NumPy package is required to use this function.')
896
+
897
+ res = {}
898
+ _get_return_val(res, "r()")
899
+ return res
900
+
901
+
902
+ def get_ereturn():
903
+ """
904
+ Retrieve current **e()** results and store them in a Python dictionary.
905
+
906
+ The keys are Stata's macro and scalar names, and the values are their
907
+ corresponding values. Stata's matrices are converted into NumPy arrays.
908
+
909
+ Returns
910
+ -------
911
+ Dictionary
912
+ A dictionary containing current **e()** results.
913
+ """
914
+ global has_num_pand
915
+ config.check_initialized()
916
+
917
+ if not has_num_pand['pknum']:
918
+ raise SystemError('NumPy package is required to use this function.')
919
+
920
+ res = {}
921
+ _get_return_val(res, "e()")
922
+ return res
923
+
924
+
925
+ def get_sreturn():
926
+ """
927
+ Retrieve current **s()** results and store them in a Python dictionary.
928
+
929
+ The keys are Stata's macro and scalar names, and the values are their
930
+ corresponding values. Stata's matrices are converted into NumPy arrays.
931
+
932
+ Returns
933
+ -------
934
+ Dictionary
935
+ A dictionary containing current **s()** results.
936
+ """
937
+ global has_num_pand
938
+ config.check_initialized()
939
+
940
+ if not has_num_pand['pknum']:
941
+ raise SystemError('NumPy package is required to use this function.')
942
+
943
+ res = {}
944
+ _get_return_val(res, "s()")
945
+ return res
pystata/stexception.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class PyStataError(Exception):
2
+ """
3
+ This class is the base class for other exceptions defined in this module.
4
+ """
5
+ pass
6
+
7
+
8
+ class IPythonError(PyStataError):
9
+ """
10
+ The class is used to indicate whether the system has IPython support.
11
+ """
12
+ pass
13
+
14
+ class IPyKernelError(PyStataError):
15
+ """
16
+ The class is used to indicate whether pystata is running in IPython
17
+ interactive session.
18
+ """
19
+ pass
pystata/version.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ version = '0.1.0'
2
+ author = 'StataCorp LLC'