dcprog 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dcprog-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the dcprog authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recursive-include src/dcprog/sources *.c
dcprog-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: dcprog
3
+ Version: 1.0.0
4
+ Summary: Small command for the part A (OpenMP) and part B (MPI) lab programs
5
+ License-Expression: MIT
6
+ Keywords: openmp,mpi,distributed-computing,lab
7
+ Classifier: Environment :: Console
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Education
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # dcprog
16
+
17
+ Part A (OpenMP) and part B (MPI) lab programs behind one short command.
18
+ No compiler, OpenMP, or MPI install is required.
19
+
20
+ ```bash
21
+ pip install dcprog
22
+ ```
23
+
24
+ ```text
25
+ dcprog list the programs
26
+ dcprog a1a 3 10 20 30 array sum
27
+ dcprog a4 1000000 pi, serial and parallel
28
+ dcprog b2 -p 4 reduce and allreduce on 4 ranks
29
+ dcprog src a4 print the original C source
30
+ ```
31
+
32
+ Leave the numbers off and the command asks for them, same prompts as the C programs.
33
+
34
+ | id | program |
35
+ | --- | --- |
36
+ | a1a | array sum |
37
+ | a1b | `schedule(static, 2)` |
38
+ | a2 | merge sort |
39
+ | a3a | fibonacci |
40
+ | a3b | maximum element |
41
+ | a4 | Leibniz pi |
42
+ | a5 | prime count |
43
+ | b1 | scatter / gather |
44
+ | b2 | reduce / allreduce |
45
+ | b3 | send, recv, broadcast |
46
+ | b4 | strings to root |
47
+ | b5 | barrier |
48
+
49
+ `-p N` is the rank count for part B (default 4). `-t N` is the thread count for part A (default: one per CPU).
dcprog-1.0.0/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # dcprog
2
+
3
+ Part A (OpenMP) and part B (MPI) lab programs behind one short command.
4
+ No compiler, OpenMP, or MPI install is required.
5
+
6
+ ```bash
7
+ pip install dcprog
8
+ ```
9
+
10
+ ```text
11
+ dcprog list the programs
12
+ dcprog a1a 3 10 20 30 array sum
13
+ dcprog a4 1000000 pi, serial and parallel
14
+ dcprog b2 -p 4 reduce and allreduce on 4 ranks
15
+ dcprog src a4 print the original C source
16
+ ```
17
+
18
+ Leave the numbers off and the command asks for them, same prompts as the C programs.
19
+
20
+ | id | program |
21
+ | --- | --- |
22
+ | a1a | array sum |
23
+ | a1b | `schedule(static, 2)` |
24
+ | a2 | merge sort |
25
+ | a3a | fibonacci |
26
+ | a3b | maximum element |
27
+ | a4 | Leibniz pi |
28
+ | a5 | prime count |
29
+ | b1 | scatter / gather |
30
+ | b2 | reduce / allreduce |
31
+ | b3 | send, recv, broadcast |
32
+ | b4 | strings to root |
33
+ | b5 | barrier |
34
+
35
+ `-p N` is the rank count for part B (default 4). `-t N` is the thread count for part A (default: one per CPU).
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dcprog"
7
+ version = "1.0.0"
8
+ description = "Small command for the part A (OpenMP) and part B (MPI) lab programs"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ keywords = ["openmp", "mpi", "distributed-computing", "lab"]
14
+ classifiers = [
15
+ "Environment :: Console",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Education",
18
+ ]
19
+
20
+ [project.scripts]
21
+ dcprog = "dcprog.cli:main"
22
+
23
+ [tool.setuptools.packages.find]
24
+ where = ["src"]
25
+
26
+ [tool.setuptools.package-data]
27
+ dcprog = ["sources/*.c"]
dcprog-1.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """Part A and part B lab programs, as the dcprog command."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,3 @@
1
+ from dcprog.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ import multiprocessing
4
+ import sys
5
+
6
+ from dcprog import __version__
7
+ from dcprog.lab import program_ids, run_program, show_catalog, show_source
8
+
9
+
10
+ def main(argv: list[str] | None = None) -> int:
11
+ multiprocessing.freeze_support()
12
+ if argv is None:
13
+ argv = sys.argv[1:]
14
+ if any(arg in ("-V", "--version") for arg in argv):
15
+ print(__version__)
16
+ return 0
17
+ if not argv or any(arg in ("-h", "--help") for arg in argv):
18
+ show_catalog()
19
+ return 0
20
+ try:
21
+ ranks, threads, args = _split(argv)
22
+ except ValueError as exc:
23
+ print(f"dcprog: {exc}", file=sys.stderr)
24
+ return 2
25
+ if not args or args[0].lower() in ("list", "help"):
26
+ show_catalog()
27
+ return 0
28
+ cmd = args[0].lower()
29
+ if cmd == "src":
30
+ if len(args) != 2:
31
+ print("usage: dcprog src <id>", file=sys.stderr)
32
+ print("ids: " + " ".join(program_ids()), file=sys.stderr)
33
+ return 2
34
+ show_source(args[1].lower())
35
+ return 0
36
+ run_program(cmd, args[1:], threads=threads, ranks=ranks)
37
+ return 0
38
+
39
+
40
+ def _split(argv: list[str]) -> tuple[int, int, list[str]]:
41
+ ranks = 4
42
+ threads = 0
43
+ rest: list[str] = []
44
+ i = 0
45
+ while i < len(argv):
46
+ arg = argv[i]
47
+ if arg in ("-p", "--ranks"):
48
+ ranks = _flag_int(argv, i, "-p", 1, 128)
49
+ i += 2
50
+ continue
51
+ if arg in ("-t", "--threads"):
52
+ threads = _flag_int(argv, i, "-t", 1, 256)
53
+ i += 2
54
+ continue
55
+ if arg == "--":
56
+ rest.extend(argv[i + 1 :])
57
+ break
58
+ rest.append(arg)
59
+ i += 1
60
+ return ranks, threads, rest
61
+
62
+
63
+ def _flag_int(argv: list[str], index: int, flag: str, lo: int, hi: int) -> int:
64
+ if index + 1 >= len(argv):
65
+ raise ValueError(f"{flag} needs a number")
66
+ try:
67
+ value = int(argv[index + 1], 10)
68
+ except ValueError:
69
+ raise ValueError(f"{flag} needs an integer") from None
70
+ if value < lo or value > hi:
71
+ raise ValueError(f"{flag} must be from {lo} to {hi}")
72
+ return value
@@ -0,0 +1,386 @@
1
+ """Same results as the part A and part B C programs, with no compiler required."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import random
7
+ import sys
8
+ import time
9
+ from collections import deque
10
+ from concurrent.futures import ProcessPoolExecutor
11
+ from importlib.resources import files
12
+ from pathlib import Path
13
+ from typing import Callable, NamedTuple
14
+
15
+ Runner = Callable[["Scanner", int, int], None]
16
+
17
+
18
+ class Program(NamedTuple):
19
+ part: str
20
+ blurb: str
21
+ source: str
22
+ run: Runner
23
+
24
+
25
+ class Scanner:
26
+ def __init__(self, preset: list[str]) -> None:
27
+ self.buf: deque[str] = deque(preset)
28
+
29
+ def token(self, prompt: str | None = None) -> str:
30
+ while not self.buf:
31
+ if prompt:
32
+ print(prompt, end="", flush=True)
33
+ prompt = None
34
+ try:
35
+ line = input()
36
+ except EOFError:
37
+ _die("unexpected end of input")
38
+ self.buf.extend(line.split())
39
+ return self.buf.popleft()
40
+
41
+ def integer(self, prompt: str | None = None) -> int:
42
+ token = self.token(prompt)
43
+ try:
44
+ return int(token, 10)
45
+ except ValueError:
46
+ _die(f"expected an integer, got {token!r}")
47
+
48
+
49
+ def show_catalog() -> None:
50
+ print("part A OpenMP")
51
+ for prog_id, prog in PROGRAMS.items():
52
+ if prog.part == "A":
53
+ print(f" {prog_id:<4} {prog.blurb}")
54
+ print("part B MPI")
55
+ for prog_id, prog in PROGRAMS.items():
56
+ if prog.part == "B":
57
+ print(f" {prog_id:<4} {prog.blurb}")
58
+ print()
59
+ print("dcprog <id> [integers...]")
60
+ print("dcprog b2 -p 4")
61
+ print("dcprog src <id>")
62
+
63
+
64
+ def program_ids() -> list[str]:
65
+ return list(PROGRAMS)
66
+
67
+
68
+ def show_source(prog_id: str) -> None:
69
+ prog = _program(prog_id)
70
+ local = Path(__file__).resolve().parent / "sources" / prog.source
71
+ if local.is_file():
72
+ sys.stdout.write(local.read_text(encoding="utf-8"))
73
+ return
74
+ packed = files("dcprog").joinpath("sources", prog.source)
75
+ sys.stdout.write(packed.read_text(encoding="utf-8"))
76
+
77
+
78
+ def run_program(prog_id: str, values: list[str], threads: int, ranks: int) -> None:
79
+ _program(prog_id).run(Scanner(values), threads, ranks)
80
+
81
+
82
+ def run_a1a(scan: Scanner, threads: int, ranks: int) -> None:
83
+ n = _bounded(scan, "Enter n: ", 0, 1000, "n")
84
+ values = [_bounded(scan, f"Enter {n} elements: " if i == 0 else None, _I32_MIN, _I32_MAX, "element") for i in range(n)]
85
+ print(f"Sum = {sum(values)}")
86
+
87
+
88
+ def run_a1b(scan: Scanner, threads: int, ranks: int) -> None:
89
+ n = _bounded(scan, "Enter number of iterations: ", 0, 1000, "n")
90
+ nthreads = _jobs(threads)
91
+ for i in range(0, n, 2):
92
+ owner = (i // 2) % nthreads
93
+ end = i + 1 if i + 1 < n else i
94
+ print(f"Thread {owner}: Iterations {i} -- {end}")
95
+
96
+
97
+ def run_a2(scan: Scanner, threads: int, ranks: int) -> None:
98
+ n = _bounded(scan, "Enter n: ", 0, 1_000_000, "n")
99
+ rng = random.Random(1)
100
+ base = [rng.randrange(0, 32768) for _ in range(n)]
101
+ sequential = list(base)
102
+ started = time.perf_counter()
103
+ _sort_inplace(sequential)
104
+ print("Sequential time: %f" % (time.perf_counter() - started))
105
+ parallel = list(base)
106
+ started = time.perf_counter()
107
+ _psort(parallel, threads)
108
+ print("Parallel time : %f" % (time.perf_counter() - started))
109
+
110
+
111
+ def run_a3a(scan: Scanner, threads: int, ranks: int) -> None:
112
+ n = _bounded(scan, "Enter n: ", 0, 1000, "n")
113
+ a, b = 0, 1
114
+ for _ in range(n):
115
+ print(a, end=" ")
116
+ a, b = b, a + b
117
+ print()
118
+
119
+
120
+ def run_a3b(scan: Scanner, threads: int, ranks: int) -> None:
121
+ n = _bounded(scan, "Enter n: ", 1, 1000, "n")
122
+ values = [_bounded(scan, f"Enter {n} elements: " if i == 0 else None, _I32_MIN, _I32_MAX, "element") for i in range(n)]
123
+ print(f"Maximum = {max(values)}")
124
+
125
+
126
+ def run_a4(scan: Scanner, threads: int, ranks: int) -> None:
127
+ n = _bounded(scan, "Enter n: ", 0, 20_000_000, "n")
128
+ started = time.perf_counter()
129
+ total = 0.0
130
+ factor = 1.0
131
+ for k in range(n):
132
+ total += factor / (2.0 * k + 1.0)
133
+ factor = -factor
134
+ print("Serial pi = %f time = %f" % (4 * total, time.perf_counter() - started))
135
+
136
+ started = time.perf_counter()
137
+ if n == 0:
138
+ parallel = 0.0
139
+ else:
140
+ parallel = _reduce_ranges(_leibniz_range, 0, n - 1, _jobs(threads), 5_000_000)
141
+ print("Parallel pi = %f time = %f" % (4 * parallel, time.perf_counter() - started))
142
+
143
+
144
+ def run_a5(scan: Scanner, threads: int, ranks: int) -> None:
145
+ n = _bounded(scan, "Enter n: ", 0, 2_000_000, "n")
146
+ started = time.perf_counter()
147
+ count = _count_primes(1, n) if n >= 1 else 0
148
+ print("Serial : %d primes time = %f" % (count, time.perf_counter() - started))
149
+
150
+ started = time.perf_counter()
151
+ if n < 1:
152
+ parallel = 0
153
+ else:
154
+ parallel = _reduce_ranges(_count_range, 1, n, _jobs(threads), 300_000)
155
+ print("Parallel: %d primes time = %f" % (parallel, time.perf_counter() - started))
156
+
157
+
158
+ def run_b1(scan: Scanner, threads: int, ranks: int) -> None:
159
+ ranks = _need_ranks(ranks, 1, 100, "b1")
160
+ got = [rank + 1 for rank in range(ranks)]
161
+ for rank, value in enumerate(got):
162
+ print(f"Process {rank} got {value}")
163
+ print("Gathered: " + " ".join(str(value * value) for value in got) + " ")
164
+
165
+
166
+ def run_b2(scan: Scanner, threads: int, ranks: int) -> None:
167
+ ranks = _need_ranks(ranks, 1, 128, "b2")
168
+ values = [rank + 1 for rank in range(ranks)]
169
+ largest = max(values)
170
+ smallest = min(values)
171
+ total = _i32(sum(values))
172
+ product = 1
173
+ for value in values:
174
+ product = _i32(product * value)
175
+ print(f"Reduce: max={largest} min={smallest} sum={total} prod={product}")
176
+ for rank in range(ranks):
177
+ print(
178
+ f"Allreduce (process {rank}): max={largest} min={smallest} sum={total} prod={product}"
179
+ )
180
+
181
+
182
+ def run_b3(scan: Scanner, threads: int, ranks: int) -> None:
183
+ ranks = _need_ranks(ranks, 2, 128, "b3")
184
+ print("Process 0 sent 100 to process 1")
185
+ print("Process 1 received 100 from process 0")
186
+ for rank in range(ranks):
187
+ print(f"Process {rank} got 50 from broadcast")
188
+
189
+
190
+ def run_b4(scan: Scanner, threads: int, ranks: int) -> None:
191
+ _need_ranks(ranks, 4, 128, "b4")
192
+ words = {
193
+ 1: "Bangalore",
194
+ 2: "Ramaiah Institute of Technology",
195
+ 3: "Information Science and Engineering",
196
+ }
197
+ for rank in (1, 2, 3):
198
+ print(f"Root received from process {rank}: {words[rank]}")
199
+
200
+
201
+ def run_b5(scan: Scanner, threads: int, ranks: int) -> None:
202
+ ranks = _need_ranks(ranks, 1, 128, "b5")
203
+ for rank in range(ranks):
204
+ value = rank + 1
205
+ print(f"Process {rank}: square of {value} = {value * value}")
206
+ print("All processes synchronized at the barrier")
207
+
208
+
209
+ def _sort_inplace(values: list[int]) -> None:
210
+ if len(values) < 2:
211
+ return
212
+ _sort(values, 0, len(values) - 1, [0] * len(values))
213
+
214
+
215
+ def _sort_list(values: list[int]) -> list[int]:
216
+ copied = list(values)
217
+ _sort_inplace(copied)
218
+ return copied
219
+
220
+
221
+ def _sort(values: list[int], left: int, right: int, temp: list[int]) -> None:
222
+ if left < right:
223
+ mid = (left + right) // 2
224
+ _sort(values, left, mid, temp)
225
+ _sort(values, mid + 1, right, temp)
226
+ _merge(values, left, mid, right, temp)
227
+
228
+
229
+ def _merge(values: list[int], left: int, mid: int, right: int, temp: list[int]) -> None:
230
+ i, j, k = left, mid + 1, left
231
+ while i <= mid and j <= right:
232
+ if values[i] < values[j]:
233
+ temp[k] = values[i]
234
+ i += 1
235
+ else:
236
+ temp[k] = values[j]
237
+ j += 1
238
+ k += 1
239
+ while i <= mid:
240
+ temp[k] = values[i]
241
+ i += 1
242
+ k += 1
243
+ while j <= right:
244
+ temp[k] = values[j]
245
+ j += 1
246
+ k += 1
247
+ values[left : right + 1] = temp[left : right + 1]
248
+
249
+
250
+ def _psort(values: list[int], threads: int) -> None:
251
+ if len(values) < 2:
252
+ return
253
+ mid = len(values) // 2
254
+ left, right = values[:mid], values[mid:]
255
+ if len(values) >= 250_000 and _jobs(threads) > 1:
256
+ left, right = _pool_map(_sort_list, [left, right])
257
+ else:
258
+ left = _sort_list(left)
259
+ right = _sort_list(right)
260
+ i = j = 0
261
+ for k in range(len(values)):
262
+ take_left = j == len(right) or (i < len(left) and left[i] < right[j])
263
+ if take_left:
264
+ values[k] = left[i]
265
+ i += 1
266
+ else:
267
+ values[k] = right[j]
268
+ j += 1
269
+
270
+
271
+ def _leibniz_range(bounds: tuple[int, int]) -> float:
272
+ lo, hi = bounds
273
+ total = 0.0
274
+ for k in range(lo, hi + 1):
275
+ factor = 1.0 if k % 2 == 0 else -1.0
276
+ total += factor / (2.0 * k + 1.0)
277
+ return total
278
+
279
+
280
+ def _count_range(bounds: tuple[int, int]) -> int:
281
+ lo, hi = bounds
282
+ return _count_primes(lo, hi)
283
+
284
+
285
+ def _count_primes(lo: int, hi: int) -> int:
286
+ count = 0
287
+ for value in range(lo, hi + 1):
288
+ if _is_prime(value):
289
+ count += 1
290
+ return count
291
+
292
+
293
+ def _is_prime(value: int) -> bool:
294
+ if value < 2:
295
+ return False
296
+ i = 2
297
+ while i * i <= value:
298
+ if value % i == 0:
299
+ return False
300
+ i += 1
301
+ return True
302
+
303
+
304
+ def _reduce_ranges(fn: Callable[[tuple[int, int]], float], lo: int, hi: int, jobs: int, threshold: int) -> float:
305
+ width = hi - lo + 1
306
+ parts = jobs if width >= threshold and jobs > 1 else 1
307
+ pieces = _chunks(lo, hi, parts)
308
+ if parts == 1:
309
+ return sum(fn(piece) for piece in pieces)
310
+ return sum(_pool_map(fn, pieces))
311
+
312
+
313
+ def _chunks(lo: int, hi: int, parts: int) -> list[tuple[int, int]]:
314
+ total = hi - lo + 1
315
+ parts = max(1, min(parts, total))
316
+ base, extra = divmod(total, parts)
317
+ pieces = []
318
+ cursor = lo
319
+ for index in range(parts):
320
+ take = base + (1 if index < extra else 0)
321
+ pieces.append((cursor, cursor + take - 1))
322
+ cursor += take
323
+ return pieces
324
+
325
+
326
+ def _pool_map(fn: Callable, items: list):
327
+ with ProcessPoolExecutor(max_workers=len(items)) as pool:
328
+ return list(pool.map(fn, items))
329
+
330
+
331
+ def _jobs(threads: int) -> int:
332
+ if threads:
333
+ return threads
334
+ return os.cpu_count() or 1
335
+
336
+
337
+ def _bounded(scan: Scanner, prompt: str | None, lo: int, hi: int, label: str) -> int:
338
+ value = scan.integer(prompt)
339
+ if value < lo or value > hi:
340
+ _die(f"{label} must be from {lo} to {hi}")
341
+ return value
342
+
343
+
344
+ def _need_ranks(ranks: int, lo: int, hi: int, prog_id: str) -> int:
345
+ if ranks < lo or ranks > hi:
346
+ _die(f"{prog_id} needs -p from {lo} to {hi}")
347
+ return ranks
348
+
349
+
350
+ _I32_MIN = -2147483648
351
+ _I32_MAX = 2147483647
352
+
353
+
354
+ def _i32(value: int) -> int:
355
+ value &= 0xFFFFFFFF
356
+ if value >= 0x80000000:
357
+ value -= 0x100000000
358
+ return value
359
+
360
+
361
+ def _program(prog_id: str) -> Program:
362
+ prog = PROGRAMS.get(prog_id)
363
+ if prog is None:
364
+ _die("unknown program %r. choose from: %s" % (prog_id, " ".join(PROGRAMS)))
365
+ return prog
366
+
367
+
368
+ def _die(message: str) -> None:
369
+ print(f"dcprog: {message}", file=sys.stderr)
370
+ raise SystemExit(1)
371
+
372
+
373
+ PROGRAMS: dict[str, Program] = {
374
+ "a1a": Program("A", "array sum", "A1a_array_sum.c", run_a1a),
375
+ "a1b": Program("A", "static schedule, chunk 2", "A1b_schedule_static.c", run_a1b),
376
+ "a2": Program("A", "merge sort, serial and parallel", "A2_merge_sort.c", run_a2),
377
+ "a3a": Program("A", "fibonacci", "A3a_fibonacci_tasks.c", run_a3a),
378
+ "a3b": Program("A", "maximum element", "A3b_max_element.c", run_a3b),
379
+ "a4": Program("A", "pi (Leibniz)", "A4_pi_estimation.c", run_a4),
380
+ "a5": Program("A", "prime count", "A5_primes.c", run_a5),
381
+ "b1": Program("B", "scatter / gather", "B1_scatter_gather.c", run_b1),
382
+ "b2": Program("B", "reduce / allreduce", "B2_reduce_allreduce.c", run_b2),
383
+ "b3": Program("B", "send, recv, broadcast", "B3_send_recv_bcast.c", run_b3),
384
+ "b4": Program("B", "strings to root", "B4_send_strings_to_root.c", run_b4),
385
+ "b5": Program("B", "barrier", "B5_barrier_square.c", run_b5),
386
+ }
@@ -0,0 +1,17 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int main() {
5
+ int n, i, a[1000], sum = 0;
6
+ printf("Enter n: ");
7
+ scanf("%d", &n);
8
+ printf("Enter %d elements: ", n);
9
+ for (i = 0; i < n; i++) scanf("%d", &a[i]);
10
+
11
+ #pragma omp parallel for reduction(+:sum)
12
+ for (i = 0; i < n; i++)
13
+ sum += a[i];
14
+
15
+ printf("Sum = %d\n", sum);
16
+ return 0;
17
+ }
@@ -0,0 +1,16 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int main() {
5
+ int n, i, tid[1000];
6
+ printf("Enter number of iterations: ");
7
+ scanf("%d", &n);
8
+
9
+ #pragma omp parallel for schedule(static, 2)
10
+ for (i = 0; i < n; i++)
11
+ tid[i] = omp_get_thread_num();
12
+
13
+ for (i = 0; i < n; i += 2)
14
+ printf("Thread %d: Iterations %d -- %d\n", tid[i], i, (i + 1 < n) ? i + 1 : i);
15
+ return 0;
16
+ }
@@ -0,0 +1,53 @@
1
+ #include <stdio.h>
2
+ #include <stdlib.h>
3
+ #include <omp.h>
4
+
5
+ int a[1000000], b[1000000], temp[1000000];
6
+
7
+ void merge(int a[], int l, int m, int r) {
8
+ int i = l, j = m + 1, k = l;
9
+ while (i <= m && j <= r) temp[k++] = (a[i] < a[j]) ? a[i++] : a[j++];
10
+ while (i <= m) temp[k++] = a[i++];
11
+ while (j <= r) temp[k++] = a[j++];
12
+ for (i = l; i <= r; i++) a[i] = temp[i];
13
+ }
14
+
15
+ void sort(int a[], int l, int r) {
16
+ if (l < r) {
17
+ int m = (l + r) / 2;
18
+ sort(a, l, m);
19
+ sort(a, m + 1, r);
20
+ merge(a, l, m, r);
21
+ }
22
+ }
23
+
24
+ void psort(int a[], int l, int r) {
25
+ if (l < r) {
26
+ int m = (l + r) / 2;
27
+ #pragma omp parallel sections
28
+ {
29
+ #pragma omp section
30
+ sort(a, l, m);
31
+ #pragma omp section
32
+ sort(a, m + 1, r);
33
+ }
34
+ merge(a, l, m, r);
35
+ }
36
+ }
37
+
38
+ int main() {
39
+ int n, i;
40
+ double t;
41
+ printf("Enter n: ");
42
+ scanf("%d", &n);
43
+ for (i = 0; i < n; i++) a[i] = b[i] = rand();
44
+
45
+ t = omp_get_wtime();
46
+ sort(a, 0, n - 1);
47
+ printf("Sequential time: %f\n", omp_get_wtime() - t);
48
+
49
+ t = omp_get_wtime();
50
+ psort(b, 0, n - 1);
51
+ printf("Parallel time : %f\n", omp_get_wtime() - t);
52
+ return 0;
53
+ }
@@ -0,0 +1,27 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int fib(int n) {
5
+ int x, y;
6
+ if (n < 2) return n;
7
+ #pragma omp task shared(x)
8
+ x = fib(n - 1);
9
+ #pragma omp task shared(y)
10
+ y = fib(n - 2);
11
+ #pragma omp taskwait
12
+ return x + y;
13
+ }
14
+
15
+ int main() {
16
+ int n, i;
17
+ printf("Enter n: ");
18
+ scanf("%d", &n);
19
+
20
+ #pragma omp parallel
21
+ #pragma omp single
22
+ for (i = 0; i < n; i++)
23
+ printf("%d ", fib(i));
24
+
25
+ printf("\n");
26
+ return 0;
27
+ }
@@ -0,0 +1,18 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int main() {
5
+ int n, i, a[1000], largest;
6
+ printf("Enter n: ");
7
+ scanf("%d", &n);
8
+ printf("Enter %d elements: ", n);
9
+ for (i = 0; i < n; i++) scanf("%d", &a[i]);
10
+
11
+ largest = a[0];
12
+ #pragma omp parallel for reduction(max:largest)
13
+ for (i = 0; i < n; i++)
14
+ if (a[i] > largest) largest = a[i];
15
+
16
+ printf("Maximum = %d\n", largest);
17
+ return 0;
18
+ }
@@ -0,0 +1,26 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int main() {
5
+ int n, k;
6
+ double sum = 0, factor = 1, t;
7
+ printf("Enter n: ");
8
+ scanf("%d", &n);
9
+
10
+ t = omp_get_wtime();
11
+ for (k = 0; k < n; k++) {
12
+ sum += factor / (2.0 * k + 1);
13
+ factor = -factor; /* depends on previous iteration */
14
+ }
15
+ printf("Serial pi = %f time = %f\n", 4 * sum, omp_get_wtime() - t);
16
+
17
+ sum = 0;
18
+ t = omp_get_wtime();
19
+ #pragma omp parallel for reduction(+:sum) private(factor)
20
+ for (k = 0; k < n; k++) {
21
+ factor = (k % 2 == 0) ? 1 : -1; /* depends only on k */
22
+ sum += factor / (2.0 * k + 1);
23
+ }
24
+ printf("Parallel pi = %f time = %f\n", 4 * sum, omp_get_wtime() - t);
25
+ return 0;
26
+ }
@@ -0,0 +1,29 @@
1
+ #include <stdio.h>
2
+ #include <omp.h>
3
+
4
+ int isPrime(int x) {
5
+ if (x < 2) return 0;
6
+ for (int i = 2; i * i <= x; i++)
7
+ if (x % i == 0) return 0;
8
+ return 1;
9
+ }
10
+
11
+ int main() {
12
+ int n, i, count = 0;
13
+ double t;
14
+ printf("Enter n: ");
15
+ scanf("%d", &n);
16
+
17
+ t = omp_get_wtime();
18
+ for (i = 1; i <= n; i++)
19
+ count += isPrime(i);
20
+ printf("Serial : %d primes time = %f\n", count, omp_get_wtime() - t);
21
+
22
+ count = 0;
23
+ t = omp_get_wtime();
24
+ #pragma omp parallel for reduction(+:count)
25
+ for (i = 1; i <= n; i++)
26
+ count += isPrime(i);
27
+ printf("Parallel: %d primes time = %f\n", count, omp_get_wtime() - t);
28
+ return 0;
29
+ }
@@ -0,0 +1,26 @@
1
+ #include <stdio.h>
2
+ #include <mpi.h>
3
+
4
+ int main(int argc, char *argv[]) {
5
+ int rank, size, i, x, a[100];
6
+ MPI_Init(&argc, &argv);
7
+ MPI_Comm_rank(MPI_COMM_WORLD, &rank);
8
+ MPI_Comm_size(MPI_COMM_WORLD, &size);
9
+
10
+ if (rank == 0)
11
+ for (i = 0; i < size; i++) a[i] = i + 1;
12
+
13
+ MPI_Scatter(a, 1, MPI_INT, &x, 1, MPI_INT, 0, MPI_COMM_WORLD);
14
+ printf("Process %d got %d\n", rank, x);
15
+
16
+ x = x * x;
17
+ MPI_Gather(&x, 1, MPI_INT, a, 1, MPI_INT, 0, MPI_COMM_WORLD);
18
+
19
+ if (rank == 0) {
20
+ printf("Gathered: ");
21
+ for (i = 0; i < size; i++) printf("%d ", a[i]);
22
+ printf("\n");
23
+ }
24
+ MPI_Finalize();
25
+ return 0;
26
+ }
@@ -0,0 +1,25 @@
1
+ #include <stdio.h>
2
+ #include <mpi.h>
3
+
4
+ int main(int argc, char *argv[]) {
5
+ int rank, x, max, min, sum, prod;
6
+ MPI_Init(&argc, &argv);
7
+ MPI_Comm_rank(MPI_COMM_WORLD, &rank);
8
+ x = rank + 1;
9
+
10
+ MPI_Reduce(&x, &max, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
11
+ MPI_Reduce(&x, &min, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
12
+ MPI_Reduce(&x, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
13
+ MPI_Reduce(&x, &prod, 1, MPI_INT, MPI_PROD, 0, MPI_COMM_WORLD);
14
+ if (rank == 0)
15
+ printf("Reduce: max=%d min=%d sum=%d prod=%d\n", max, min, sum, prod);
16
+
17
+ MPI_Allreduce(&x, &max, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD);
18
+ MPI_Allreduce(&x, &min, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
19
+ MPI_Allreduce(&x, &sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
20
+ MPI_Allreduce(&x, &prod, 1, MPI_INT, MPI_PROD, MPI_COMM_WORLD);
21
+ printf("Allreduce (process %d): max=%d min=%d sum=%d prod=%d\n", rank, max, min, sum, prod);
22
+
23
+ MPI_Finalize();
24
+ return 0;
25
+ }
@@ -0,0 +1,26 @@
1
+ #include <stdio.h>
2
+ #include <mpi.h>
3
+
4
+ int main(int argc, char *argv[]) {
5
+ int rank, x, b = 0;
6
+ MPI_Init(&argc, &argv);
7
+ MPI_Comm_rank(MPI_COMM_WORLD, &rank);
8
+
9
+ /* Point-to-point: process 0 -> process 1 */
10
+ if (rank == 0) {
11
+ x = 100;
12
+ MPI_Send(&x, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
13
+ printf("Process 0 sent %d to process 1\n", x);
14
+ } else if (rank == 1) {
15
+ MPI_Recv(&x, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
16
+ printf("Process 1 received %d from process 0\n", x);
17
+ }
18
+
19
+ /* One-to-all: process 0 -> every process */
20
+ if (rank == 0) b = 50;
21
+ MPI_Bcast(&b, 1, MPI_INT, 0, MPI_COMM_WORLD);
22
+ printf("Process %d got %d from broadcast\n", rank, b);
23
+
24
+ MPI_Finalize();
25
+ return 0;
26
+ }
@@ -0,0 +1,24 @@
1
+ #include <stdio.h>
2
+ #include <string.h>
3
+ #include <mpi.h>
4
+
5
+ int main(int argc, char *argv[]) {
6
+ int rank, i;
7
+ char msg[100];
8
+ char *words[] = {"", "Bangalore", "Ramaiah Institute of Technology",
9
+ "Information Science and Engineering"};
10
+ MPI_Init(&argc, &argv);
11
+ MPI_Comm_rank(MPI_COMM_WORLD, &rank);
12
+
13
+ if (rank == 0) {
14
+ for (i = 1; i <= 3; i++) {
15
+ MPI_Recv(msg, 100, MPI_CHAR, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
16
+ printf("Root received from process %d: %s\n", i, msg);
17
+ }
18
+ } else if (rank <= 3) {
19
+ MPI_Send(words[rank], strlen(words[rank]) + 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
20
+ }
21
+
22
+ MPI_Finalize();
23
+ return 0;
24
+ }
@@ -0,0 +1,20 @@
1
+ #include <stdio.h>
2
+ #include <mpi.h>
3
+
4
+ int main(int argc, char *argv[]) {
5
+ int rank, x;
6
+ MPI_Init(&argc, &argv);
7
+ MPI_Comm_rank(MPI_COMM_WORLD, &rank);
8
+
9
+ x = rank + 1;
10
+ printf("Process %d: square of %d = %d\n", rank, x, x * x);
11
+ fflush(stdout);
12
+
13
+ MPI_Barrier(MPI_COMM_WORLD); /* wait until all processes reach here */
14
+
15
+ if (rank == 0)
16
+ printf("All processes synchronized at the barrier\n");
17
+
18
+ MPI_Finalize();
19
+ return 0;
20
+ }
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: dcprog
3
+ Version: 1.0.0
4
+ Summary: Small command for the part A (OpenMP) and part B (MPI) lab programs
5
+ License-Expression: MIT
6
+ Keywords: openmp,mpi,distributed-computing,lab
7
+ Classifier: Environment :: Console
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Education
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # dcprog
16
+
17
+ Part A (OpenMP) and part B (MPI) lab programs behind one short command.
18
+ No compiler, OpenMP, or MPI install is required.
19
+
20
+ ```bash
21
+ pip install dcprog
22
+ ```
23
+
24
+ ```text
25
+ dcprog list the programs
26
+ dcprog a1a 3 10 20 30 array sum
27
+ dcprog a4 1000000 pi, serial and parallel
28
+ dcprog b2 -p 4 reduce and allreduce on 4 ranks
29
+ dcprog src a4 print the original C source
30
+ ```
31
+
32
+ Leave the numbers off and the command asks for them, same prompts as the C programs.
33
+
34
+ | id | program |
35
+ | --- | --- |
36
+ | a1a | array sum |
37
+ | a1b | `schedule(static, 2)` |
38
+ | a2 | merge sort |
39
+ | a3a | fibonacci |
40
+ | a3b | maximum element |
41
+ | a4 | Leibniz pi |
42
+ | a5 | prime count |
43
+ | b1 | scatter / gather |
44
+ | b2 | reduce / allreduce |
45
+ | b3 | send, recv, broadcast |
46
+ | b4 | strings to root |
47
+ | b5 | barrier |
48
+
49
+ `-p N` is the rank count for part B (default 4). `-t N` is the thread count for part A (default: one per CPU).
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ src/dcprog/__init__.py
6
+ src/dcprog/__main__.py
7
+ src/dcprog/cli.py
8
+ src/dcprog/lab.py
9
+ src/dcprog.egg-info/PKG-INFO
10
+ src/dcprog.egg-info/SOURCES.txt
11
+ src/dcprog.egg-info/dependency_links.txt
12
+ src/dcprog.egg-info/entry_points.txt
13
+ src/dcprog.egg-info/top_level.txt
14
+ src/dcprog/sources/A1a_array_sum.c
15
+ src/dcprog/sources/A1b_schedule_static.c
16
+ src/dcprog/sources/A2_merge_sort.c
17
+ src/dcprog/sources/A3a_fibonacci_tasks.c
18
+ src/dcprog/sources/A3b_max_element.c
19
+ src/dcprog/sources/A4_pi_estimation.c
20
+ src/dcprog/sources/A5_primes.c
21
+ src/dcprog/sources/B1_scatter_gather.c
22
+ src/dcprog/sources/B2_reduce_allreduce.c
23
+ src/dcprog/sources/B3_send_recv_bcast.c
24
+ src/dcprog/sources/B4_send_strings_to_root.c
25
+ src/dcprog/sources/B5_barrier_square.c
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dcprog = dcprog.cli:main
@@ -0,0 +1 @@
1
+ dcprog