Source

MQ for Sage toric varieties / trac_13211_pool_size.patch

The default branch has multiple heads

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# HG changeset patch
# Parent c094723a170992d57f98eaffc0d7e585c76db86e

customizable gap memory pool size with sensible defaults

diff --git a/sage/interfaces/all.py b/sage/interfaces/all.py
--- a/sage/interfaces/all.py
+++ b/sage/interfaces/all.py
@@ -6,7 +6,7 @@
 from fricas import FriCAS, fricas, fricas_console
 
 from expect import is_ExpectElement
-from gap import gap, gap_reset_workspace, gap_console, gap_version, is_GapElement, Gap
+from gap import gap, gap_reset_workspace, gap_console, gap_version, set_gap_memory_pool_size, is_GapElement, Gap
 from gap3 import gap3, gap3_console, gap3_version, Gap3
 from genus2reduction import genus2reduction, Genus2reduction
 from gfan import gfan,  Gfan
diff --git a/sage/interfaces/gap.py b/sage/interfaces/gap.py
--- a/sage/interfaces/gap.py
+++ b/sage/interfaces/gap.py
@@ -211,6 +211,88 @@
     else:
         return gap_cmd, True
 
+############ Set the GAP memory pool size
+
+# you should always use get_gap_memory_pool_size() to access this value
+gap_memory_pool_size = None
+
+def set_gap_memory_pool_size(size_in_bytes):
+    """
+    Set the desired gap memory pool size.
+
+    Subsequently started GAP/libGAP instances will use this as
+    default. Currently running instances are unchanged.
+
+    GAP will only reserve ``size_in_bytes`` address space. Unless you
+    actually start a big GAP computation, the memory will not be
+    used. However, corresponding swap space will be reserved so that
+    GAP will always be able to use the reserved address space if
+    needed. While nothing is actually written to disc as long as you
+    don't run a big GAP computation, the reserved swap space will not
+    be available for other processes.
+
+    INPUT:
+
+    - ``size_in_bytes`` -- integer. The desired memory pool size.
+
+    EXAMPLES::
+    
+        sage: from sage.interfaces.gap import \
+        ...       get_gap_memory_pool_size, set_gap_memory_pool_size
+        sage: n = get_gap_memory_pool_size()
+        sage: set_gap_memory_pool_size(n)
+        sage: n == get_gap_memory_pool_size()
+        True
+        sage: n   # random output
+        1534059315
+    """
+    global gap_memory_pool_size
+    gap_memory_pool_size = size_in_bytes
+    
+def get_gap_memory_pool_size():
+    """
+    Get the gap memory pool size for new GAP processes.
+
+    EXAMPLES::
+    
+        sage: from sage.interfaces.gap import \
+        ...       get_gap_memory_pool_size
+        sage: get_gap_memory_pool_size()   # random output
+        1534059315
+    """
+    global gap_memory_pool_size
+    if gap_memory_pool_size is not None:
+        return gap_memory_pool_size
+    from sage.misc.memory_info import MemoryInfo
+    mem = MemoryInfo()
+    suggested_size = max(int(mem.available_swap() / 10), 
+                         int(mem.available_ram()  / 50))   # in case you run without swap
+    return suggested_size
+
+def _get_gap_memory_pool_size_MB():
+    """
+    Return the gap memory pool size suitable for usage on the GAP
+    command line
+
+    The GAP 4.5.6 command line parser has issues with large numbers, so
+    we return it in megabytes.
+
+    OUTPUT:
+
+    String.
+
+    EXAMPLES:
+
+        sage: from sage.interfaces.gap import \
+        ...       _get_gap_memory_pool_size_MB
+        sage: _get_gap_memory_pool_size_MB()   # random output
+        '1467m'
+    """
+    pool = get_gap_memory_pool_size()
+    pool = (pool // (1024**2)) + 1
+    return str(pool)+'m'
+
+
 ############ Classes with methods for both the GAP3 and GAP4 interface
 
 class Gap_generic(Expect):
@@ -431,7 +513,6 @@
 
         INPUT:
 
-
         -  ``s`` - string containing GAP code.
 
         -  ``newlines`` - bool (default: True); if False,
@@ -985,10 +1066,10 @@
     """
     def __init__(self, max_workspace_size=None,
                  maxread=100000, script_subdirectory=None,
-                 use_workspace_cache = True,
+                 use_workspace_cache=True,
                  server=None,
                  server_tmpdir=None,
-                 logfile = None):
+                 logfile=None):
         """
         EXAMPLES::
         
@@ -998,25 +1079,21 @@
         self.__use_workspace_cache = use_workspace_cache
         cmd, self.__make_workspace = gap_command(use_workspace_cache, server is None)
         cmd += " -b -p -T"
-        if max_workspace_size != None:
-            cmd += " -o %s"%int(max_workspace_size)
-        else: # unlimited
-            if is_64_bit:
-                cmd += " -o 9999G"
-            else:
-                cmd += " -o 3900m"
+        if max_workspace_size == None:
+            max_workspace_size = _get_gap_memory_pool_size_MB()
+        cmd += ' -o ' + str(max_workspace_size)
         cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','sage.g')
         Expect.__init__(self,
-                        name = 'gap',
-                        prompt = 'gap> ',
-                        command = cmd,
-                        maxread = maxread,
-                        server = server,
-                        server_tmpdir = server_tmpdir,
-                        script_subdirectory = script_subdirectory,
-                        restart_on_ctrlc = True,
-                        verbose_start = False,
-                        logfile = logfile,
+                        name='gap',
+                        prompt='gap> ',
+                        command=cmd,
+                        maxread=maxread,
+                        server=server,
+                        server_tmpdir=server_tmpdir,
+                        script_subdirectory=script_subdirectory,
+                        restart_on_ctrlc=True,
+                        verbose_start=False,
+                        logfile=logfile,
                         eval_using_file_cutoff=100)
         self.__seq = 0
 
@@ -1673,7 +1750,7 @@
     
     EXAMPLES::
      
-        sage: gap.console() #not tested
+        sage: gap.console()    # not tested
         .........   GAP, Version 4.5.5 of 16-Jul-2012 (free software, GPL)
         .  GAP  .   http://www.gap-system.org
         .........   Architecture: x86_64-unknown-linux-gnu-gcc-default64
@@ -1694,9 +1771,11 @@
         True
         sage: 'Error' not in gap_startup
         True
+        sage: 'sorry' not in gap_startup
+        True
      """
     cmd, _ = gap_command(use_workspace_cache=False)
-    cmd += os.path.join(SAGE_EXTCODE,'gap','console.g')
+    cmd += ' ' + os.path.join(SAGE_EXTCODE,'gap','console.g')
     os.system(cmd)
 
 def gap_version():
diff --git a/sage/misc/memory_info.py b/sage/misc/memory_info.py
new file mode 100644
--- /dev/null
+++ b/sage/misc/memory_info.py
@@ -0,0 +1,419 @@
+"""
+Information about available RAM/swap
+
+There is no portable way to figure these out, nor should you generally
+have to. But GAP currently needs to allocate a cache of fixed size
+upon startup, and we would like a certain fraction of the swap address
+space.
+
+EXAMPLES::
+
+    sage: from sage.misc.memory_info import MemoryInfo, MemoryInfo_proc
+    sage: mem = MemoryInfo()
+    sage: mem.total_ram()          # random output
+    16708194304
+    sage: mem.available_ram()      # random output
+    1690738688
+    sage: mem.total_swap()         # random output
+    15728635904
+    sage: mem.available_swap()     # random output
+    15340593152
+"""
+
+########################################################################
+#       Copyright (C) 2012 Volker Braun <vbraun.name@gmail.com>
+#
+#  Distributed under the terms of the GNU General Public License (GPL)
+#
+#                  http://www.gnu.org/licenses/
+########################################################################
+
+import subprocess
+from sage.structure.sage_object import SageObject
+
+memory_info_instance = None
+
+def MemoryInfo():
+    """
+    Provide information about memory
+
+    OUTPUT:
+
+    A class that is encapsulates memory information. If no method for
+    the particular host OS is provided, reasonable guesses are given.
+
+    EXAMPLES::
+
+        sage: from sage.misc.memory_info import MemoryInfo, MemoryInfo_proc
+        sage: mem = MemoryInfo()
+        sage: mem.total_ram()       # random output
+        16708194304
+        sage: mem.available_ram()   # random output
+        1690738688
+        sage: mem.total_swap()      # random output
+        15728635904
+        sage: mem.available_swap()  # random output
+        15340593152
+    """
+    global memory_info_instance
+    if memory_info_instance is not None:
+        return memory_info_instance
+    import platform
+    system = platform.system()
+    if memory_info_instance is None and \
+            system != 'Darwin':
+        try:   
+            memory_info_instance = MemoryInfo_proc()
+        except OSError:
+            pass
+    if memory_info_instance is None and \
+            system == 'Darwin':
+        try:
+            memory_info_instance = MemoryInfo_OSX()
+        except OSError:
+            pass
+    if memory_info_instance is None:
+        memory_info_instance = MemoryInfo_guess()
+    return memory_info_instance
+
+
+class MemoryInfo_proc(SageObject):
+    """
+    Provide information from ``/proc/`` pseudo-filesystem on most UNIXes
+
+    EXAMPLES::
+
+        sage: from sage.misc.memory_info import MemoryInfo
+        sage: mem = MemoryInfo()
+        sage: mem.total_ram()   # random output
+        16708194304
+    """
+
+    def __init__(self):
+        try:
+            self._parse_proc_meminfo()
+        except (IOError, ValueError):
+            raise OSError('/proc/meminfo is not available')
+
+    def _parse_proc_meminfo(self):
+        """
+        Parse ``/proc/meminfo``
+
+        OUTPUT:
+
+        A dictionary. All sizes are in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo, MemoryInfo_proc
+            sage: mem = MemoryInfo()
+            sage: if isinstance(mem, MemoryInfo_proc):
+            ...       info = mem._parse_proc_meminfo()
+            ... else:
+            ...       info = None
+            sage: info   # random output
+            {'available_ram': 1749782528, 
+             'total_swap': 15728635904, 
+             'available_swap': 15340572672,
+             'total_ram': 16708194304}
+            sage: keys = set(['available_ram', 'total_swap', 'available_swap', 'total_ram'])
+            sage: (info is None) or (set(info.keys()) == keys)
+            True
+        """
+        kb = 1024
+        result = dict()
+        meminfo = open('/proc/meminfo', 'r')
+        for line in meminfo.readlines():
+            line = line.split()
+            if line[0].startswith('MemTotal') and line[2] == 'kB':
+                result['total_ram'] = int(line[1]) * kb
+            if line[0].startswith('MemFree') and line[2] == 'kB':
+                result['available_ram'] = int(line[1]) * kb
+            if line[0].startswith('SwapTotal') and line[2] == 'kB':
+                result['total_swap'] = int(line[1]) * kb
+            if line[0].startswith('SwapFree') and line[2] == 'kB':
+                result['available_swap'] = int(line[1]) * kb
+        meminfo.close()
+        required = set(['available_ram', 'total_swap', 'available_swap', 'total_ram'])
+        if set(result.keys()) != required:
+            raise OSError('failed to parse /proc/meminfo correctly')
+        return result
+
+    def total_ram(self):
+        """
+        Return the total RAM size
+        
+        OUTPUT:
+
+        Integer. The RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_ram() > 0
+            True
+        """
+        return self._parse_proc_meminfo()['total_ram']
+
+    def available_ram(self):
+        """
+        Return the available (free) RAM size
+        
+        OUTPUT:
+
+        Integer. The free RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_ram() > 0
+            True
+        """
+        return self._parse_proc_meminfo()['available_ram']
+
+    def total_swap(self):
+        """
+        Return the total swap size
+        
+        OUTPUT:
+
+        Integer. The swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_swap() > 0
+            True
+        """
+        return self._parse_proc_meminfo()['total_swap']
+
+    def available_swap(self):
+        """
+        Return the available (free) swap size
+        
+        OUTPUT:
+
+        Integer. The free swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_swap() > 0
+            True
+        """
+        return self._parse_proc_meminfo()['available_swap']
+
+
+class MemoryInfo_OSX(SageObject):
+    """
+    Memory info on OSX
+
+    TESTS::
+
+        sage: from sage.misc.memory_info import MemoryInfo_OSX
+    """
+
+    def __init__(self):
+        self._maxage = 10   # cache result for 10 seconds
+        self._age = -self._maxage
+        try:
+            self._parse_top()
+        except (IOError, ValueError, subprocess.CalledProcessError, KeyError):
+            raise OSError('failed to parse OSX "top" output')
+
+    def _parse_top(self):
+        """
+        Parse ``top`` output
+
+        OUTPUT:
+
+        A dictionary. All sizes are in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo, MemoryInfo_OSX
+            sage: mem = MemoryInfo()
+            sage: if isinstance(mem, MemoryInfo_OSX):
+            ...       info = mem._parse_top()
+            ... else:
+            ...       info = None
+            sage: info   # random output
+            {'available_ram': 1749782528, 
+             'total_ram': 16708194304}
+            sage: keys = set(['available_ram', 'total_ram'])
+            sage: (info is None) or (set(info.keys()) == keys)
+            True
+        """
+        import time
+        if (time.time()-self._age) < self._maxage:
+            return self._parse_top_cache
+        units = { 'K': 1024, 'M':1024**2, 'G':1024**3 }
+        result = dict()
+        meminfo = subprocess.check_output(['top', '-l', '1'], 
+                                          stderr=subprocess.STDOUT)
+        for line in meminfo.splitlines():
+            if not line.startswith('PhysMem:'):
+                continue
+            line = line.split()
+            if not line[-1].startswith('free') or not line[-3].startswith('used'):
+                raise OSError('failed to parse PhysMem: line in "top" output')
+            used_ram = line[-4]
+            free_ram = line[-2]
+            used_ram = int(used_ram[:-1]) * units[used_ram[-1]]
+            free_ram = int(free_ram[:-1]) * units[free_ram[-1]]
+            result = { 'total_ram': used_ram + free_ram,
+                       'available_ram': free_ram }
+            self._age = time.time()
+            self._parse_top_cache = result
+            return result
+        raise OSError('failed to parse "top" output, no PhysMem: section')
+
+    def total_ram(self):
+        """
+        Return the total RAM size
+        
+        OUTPUT:
+
+        Integer. The RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_ram() > 0
+            True
+        """
+        return self._parse_top()['total_ram']
+
+    def available_ram(self):
+        """
+        Return the available (free) RAM size
+        
+        OUTPUT:
+
+        Integer. The free RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_ram() > 0
+            True
+        """
+        return self._parse_top()['available_ram']
+
+    def total_swap(self):
+        """
+        Return the total swap size
+        
+        The OSX swap file is growing dynamically, so we just return
+        twice the total ram.
+
+        OUTPUT:
+
+        Integer. The swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_swap() > 0
+            True
+        """
+        return 2*self.total_ram()
+
+    def available_swap(self):
+        """
+        Return the available (free) swap size
+
+        The OSX swap file is growing dynamically, so we just return
+        twice the available ram.
+        
+        OUTPUT:
+
+        Integer. The free swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_swap() > 0
+            True
+        """
+        return 2*self.available_ram()
+
+
+class MemoryInfo_guess(SageObject):
+    """
+    Guess memory as a fallback.
+
+    TESTS::
+    
+        sage: from sage.misc.memory_info import MemoryInfo_guess
+        sage: mem = MemoryInfo_guess()
+        sage: mem.total_ram()
+        4294967296
+    """
+    def total_ram(self):
+        """
+        Return the total RAM size
+        
+        OUTPUT:
+
+        Integer. The RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_ram() > 0
+            True
+        """
+        GB = 1024 * 1024 * 1024
+        return 4*GB
+
+    def available_ram(self):
+        """
+        Return the available (free) RAM size
+        
+        OUTPUT:
+
+        Integer. The free RAM size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_ram() > 0
+            True
+        """
+        return self.total_ram()
+    
+    def total_swap(self):
+        """
+        Return the total swap size
+        
+        OUTPUT:
+
+        Integer. The swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().total_swap() > 0
+            True
+        """
+        GB = 1024 * 1024 * 1024
+        return 4*GB
+
+    def available_swap(self):
+        """
+        Return the available (free) swap size
+        
+        OUTPUT:
+
+        Integer. The free swap size in bytes.
+
+        EXAMPLES::
+
+            sage: from sage.misc.memory_info import MemoryInfo
+            sage: MemoryInfo().available_swap() > 0
+            True
+        """
+        return self.total_swap()
+        
+        
diff --git a/sage/tests/cmdline.py b/sage/tests/cmdline.py
--- a/sage/tests/cmdline.py
+++ b/sage/tests/cmdline.py
@@ -394,7 +394,7 @@
         sage: (out, err, ret) = test_executable(["sage", "--gap", "-q"], "Size(SymmetricGroup(5));\n")
         sage: out
         '120\n'
-        sage: err
+        sage: err.replace('gap: halving pool size.', '').strip()
         ''
         sage: ret
         0