Skip to content

PhasePortraitManager

PhasePortrait2DManager

Bases: object

Source code in phaseportrait/PhasePortraitManager.py
 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
class PhasePortrait2DManager(object):
    @staticmethod
    def plot_from_json(json_str: str) -> str:
        """Returns a string containing SVG figure path for given json.
        For a json example view `phaseportrait/examples/api_examples/phaseportrait2d_example.json`."""
        info = json.loads(json_str)

        representation = PhasePortrait2D(lambda x,y:(x,y), [-1,1])

        # Function
        try:
            match = re.search(r"def\s+(\w+)\(", info['dF'])
            function_name = match.group(1)
            match = re.search(r"(\s+)def", info['dF'])
            if match is not None:
                info['dF'] = info['dF'].replace(match.group(0), "\ndef")
            del match

            exec(info['dF'], globals())
            representation.dF = globals()[function_name]
        except  Exception as e:
            return 0

        # Range
        representation.Range = [[info['Range']['x_min'],info['Range']['x_max']],
                                [info['Range']['y_min'],info['Range']['y_max']]]

        # Parameters
        kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'color', 'xScale', 'yScale']
        for k,v in info.items():
            if k in kargs:
                setattr(representation, k, v)

        # Nullcline
        try:
            if nc:=info['nullcline']:
                representation.add_nullclines(**nc)
        except KeyError:
            pass

        # Plot and save
        fig, ax = representation.plot()

        # path = info['path']
        # fig_name = time.strftime('%a%d%b%Y%H%M%SGMT',time.localtime())
        # fig.savefig(path + fig_name +'.svg', transparent=True)

        return fig
        return fig_name + '.svg'


    @staticmethod
    def json_to_python_code(json_str: str) -> str:
        """Returns a string containing equivalent Python code for the given json.
        For a json example view `phaseportrait/examples/api_examples/phaseportrait2d_example.json`."""

        info = json.loads(json_str)

        match = re.search(r"def\s+(\w+)\(", info['dF'])
        function_name = match.group(1)

        header = f"""from phaseportrait import *\nimport matplotlib.pyplot as plt"""

        function = f"""\n{info['dF']}"""

        portrait = f"""\nphase_diagram = PhasePortrait2D({function_name}, [[{info['Range']['x_min']},{info['Range']['x_max']}],[{info['Range']['y_min']},{info['Range']['y_max']}]]"""

        portrait_kargs = ""
        kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'color', 'xScale', 'yScale']
        first = True
        for k in info.keys():
            if k in kargs:
                if info[k]:
                    if first:
                        portrait += ","
                        first = False
                    if isinstance(info[k], str):
                        portrait_kargs += f"\t{k} = '{info[k]}',\n"
                    else:
                        portrait_kargs += f"\t{k} = {info[k]},\n"

        if first:
            portrait += ')\n'
        else:
            portrait_kargs += ')\n'

        nullcline = ''
        if nc := info.get('nullcline'):
            nullcline = f"\nphase_diagram.add_nullclines(precision={nc['precision']}, offset={nc['offset']})"

        finisher = '\nphase_diagram.plot()\nplt.show()'

        return header +"\n\t\n"+ function +"\n\t\n"+ portrait +"\n"+ portrait_kargs +"\n\t\n"+ nullcline +"\n\t\n"+ finisher

json_to_python_code(json_str) staticmethod

Returns a string containing equivalent Python code for the given json. For a json example view phaseportrait/examples/api_examples/phaseportrait2d_example.json.

Source code in phaseportrait/PhasePortraitManager.py
 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
@staticmethod
def json_to_python_code(json_str: str) -> str:
    """Returns a string containing equivalent Python code for the given json.
    For a json example view `phaseportrait/examples/api_examples/phaseportrait2d_example.json`."""

    info = json.loads(json_str)

    match = re.search(r"def\s+(\w+)\(", info['dF'])
    function_name = match.group(1)

    header = f"""from phaseportrait import *\nimport matplotlib.pyplot as plt"""

    function = f"""\n{info['dF']}"""

    portrait = f"""\nphase_diagram = PhasePortrait2D({function_name}, [[{info['Range']['x_min']},{info['Range']['x_max']}],[{info['Range']['y_min']},{info['Range']['y_max']}]]"""

    portrait_kargs = ""
    kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'color', 'xScale', 'yScale']
    first = True
    for k in info.keys():
        if k in kargs:
            if info[k]:
                if first:
                    portrait += ","
                    first = False
                if isinstance(info[k], str):
                    portrait_kargs += f"\t{k} = '{info[k]}',\n"
                else:
                    portrait_kargs += f"\t{k} = {info[k]},\n"

    if first:
        portrait += ')\n'
    else:
        portrait_kargs += ')\n'

    nullcline = ''
    if nc := info.get('nullcline'):
        nullcline = f"\nphase_diagram.add_nullclines(precision={nc['precision']}, offset={nc['offset']})"

    finisher = '\nphase_diagram.plot()\nplt.show()'

    return header +"\n\t\n"+ function +"\n\t\n"+ portrait +"\n"+ portrait_kargs +"\n\t\n"+ nullcline +"\n\t\n"+ finisher

plot_from_json(json_str) staticmethod

Returns a string containing SVG figure path for given json. For a json example view phaseportrait/examples/api_examples/phaseportrait2d_example.json.

Source code in phaseportrait/PhasePortraitManager.py
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
@staticmethod
def plot_from_json(json_str: str) -> str:
    """Returns a string containing SVG figure path for given json.
    For a json example view `phaseportrait/examples/api_examples/phaseportrait2d_example.json`."""
    info = json.loads(json_str)

    representation = PhasePortrait2D(lambda x,y:(x,y), [-1,1])

    # Function
    try:
        match = re.search(r"def\s+(\w+)\(", info['dF'])
        function_name = match.group(1)
        match = re.search(r"(\s+)def", info['dF'])
        if match is not None:
            info['dF'] = info['dF'].replace(match.group(0), "\ndef")
        del match

        exec(info['dF'], globals())
        representation.dF = globals()[function_name]
    except  Exception as e:
        return 0

    # Range
    representation.Range = [[info['Range']['x_min'],info['Range']['x_max']],
                            [info['Range']['y_min'],info['Range']['y_max']]]

    # Parameters
    kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'color', 'xScale', 'yScale']
    for k,v in info.items():
        if k in kargs:
            setattr(representation, k, v)

    # Nullcline
    try:
        if nc:=info['nullcline']:
            representation.add_nullclines(**nc)
    except KeyError:
        pass

    # Plot and save
    fig, ax = representation.plot()

    # path = info['path']
    # fig_name = time.strftime('%a%d%b%Y%H%M%SGMT',time.localtime())
    # fig.savefig(path + fig_name +'.svg', transparent=True)

    return fig
    return fig_name + '.svg'

PhasePortrait3DManager

Bases: object

Source code in phaseportrait/PhasePortraitManager.py
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
class PhasePortrait3DManager(object):
    @staticmethod
    def plot_from_json(json_str: str) -> str:
        """Returns a string containing SVG figure path for given json.
        For a json example view `phaseportrait/examples/api_examples/phaseportrait3D_example.json`."""
        info = json.loads(json_str)

        representation = PhasePortrait3D(lambda x,y,z:(x,y,-z), [[-1,1]*3])

        # Function
        try:
            match = re.search(r"def\s+(\w+)\(", info['dF'])
            function_name = match.group(1)
            match = re.search(r"(\s+)def", info['dF'])
            if match is not None:
                info['dF'] = info['dF'].replace(match.group(0), "\ndef")
            del match

            exec(info['dF'], globals())
            representation.dF = globals()[function_name]
        except  Exception as e:
            return 0

        # Range
        representation.Range = [[info['Range']['x_min'],info['Range']['x_max']],
                                [info['Range']['y_min'],info['Range']['y_max']],
                                [info['Range']['z_min'],info['Range']['z_max']]]

        # Parameters
        kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'zlabel', 'color', 'xScale', 'yScale', 'zScale']
        for k,v in info.items():
            if k in kargs:
                setattr(representation, k, v)

        # Nullcline
        try:
            if nc:=info['nullcline']:
                representation.add_nullclines(**nc)
        except KeyError:
            pass

        # Plot and save
        fig, ax = representation.plot()

        # path = info['path']
        # fig_name = time.strftime('%a%d%b%Y%H%M%SGMT',time.localtime())
        # fig.savefig(path + fig_name +'.svg', transparent=True)

        return fig
        return fig_name + '.svg'


    @staticmethod
    def json_to_python_code(json_str: str) -> str:
        """Returns a string containing equivalent Python code for the given json."""

        info = json.loads(json_str)

        match = re.search(r"def\s+(\w+)\(", info['dF'])
        function_name = match.group(1)

        header = f"""from phaseportrait import *\nimport matplotlib.pyplot as plt"""

        function = f"""\n{info['dF']}"""

        portrait = f"""\nphase_diagram = PhasePortrait3D({function_name}, [[{info['Range']['x_min']},{info['Range']['x_max']}],[{info['Range']['y_min']},{info['Range']['y_max']}],[{info['Range']['z_min']},{info['Range']['z_max']}]]"""

        portrait_kargs = ""
        kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'zlabel', 'color', 'xScale', 'yScale', 'zScale']
        first = True
        for k in info.keys():
            if k in kargs:
                if info[k]:
                    if first:
                        portrait += ","
                        first = False
                    if isinstance(info[k], str):
                        portrait_kargs += f"\t{k} = '{info[k]}',\n"
                    else:
                        portrait_kargs += f"\t{k} = {info[k]},\n"

        if first:
            portrait += ')\n'
        else:
            portrait_kargs += ')\n'

        nullcline = ''
        if nc := info.get('nullcline'):
            nullcline = f"\nphase_diagram.add_nullclines(precision={nc['precision']}, offset={nc['offset']})"

        finisher = '\nphase_diagram.plot()\nplt.show()'

        return header +"\n\t\n"+ function +"\n\t\n"+ portrait +"\n"+ portrait_kargs +"\n\t\n"+ nullcline +"\n\t\n"+ finisher

json_to_python_code(json_str) staticmethod

Returns a string containing equivalent Python code for the given json.

Source code in phaseportrait/PhasePortraitManager.py
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
@staticmethod
def json_to_python_code(json_str: str) -> str:
    """Returns a string containing equivalent Python code for the given json."""

    info = json.loads(json_str)

    match = re.search(r"def\s+(\w+)\(", info['dF'])
    function_name = match.group(1)

    header = f"""from phaseportrait import *\nimport matplotlib.pyplot as plt"""

    function = f"""\n{info['dF']}"""

    portrait = f"""\nphase_diagram = PhasePortrait3D({function_name}, [[{info['Range']['x_min']},{info['Range']['x_max']}],[{info['Range']['y_min']},{info['Range']['y_max']}],[{info['Range']['z_min']},{info['Range']['z_max']}]]"""

    portrait_kargs = ""
    kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'zlabel', 'color', 'xScale', 'yScale', 'zScale']
    first = True
    for k in info.keys():
        if k in kargs:
            if info[k]:
                if first:
                    portrait += ","
                    first = False
                if isinstance(info[k], str):
                    portrait_kargs += f"\t{k} = '{info[k]}',\n"
                else:
                    portrait_kargs += f"\t{k} = {info[k]},\n"

    if first:
        portrait += ')\n'
    else:
        portrait_kargs += ')\n'

    nullcline = ''
    if nc := info.get('nullcline'):
        nullcline = f"\nphase_diagram.add_nullclines(precision={nc['precision']}, offset={nc['offset']})"

    finisher = '\nphase_diagram.plot()\nplt.show()'

    return header +"\n\t\n"+ function +"\n\t\n"+ portrait +"\n"+ portrait_kargs +"\n\t\n"+ nullcline +"\n\t\n"+ finisher

plot_from_json(json_str) staticmethod

Returns a string containing SVG figure path for given json. For a json example view phaseportrait/examples/api_examples/phaseportrait3D_example.json.

Source code in phaseportrait/PhasePortraitManager.py
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
@staticmethod
def plot_from_json(json_str: str) -> str:
    """Returns a string containing SVG figure path for given json.
    For a json example view `phaseportrait/examples/api_examples/phaseportrait3D_example.json`."""
    info = json.loads(json_str)

    representation = PhasePortrait3D(lambda x,y,z:(x,y,-z), [[-1,1]*3])

    # Function
    try:
        match = re.search(r"def\s+(\w+)\(", info['dF'])
        function_name = match.group(1)
        match = re.search(r"(\s+)def", info['dF'])
        if match is not None:
            info['dF'] = info['dF'].replace(match.group(0), "\ndef")
        del match

        exec(info['dF'], globals())
        representation.dF = globals()[function_name]
    except  Exception as e:
        return 0

    # Range
    representation.Range = [[info['Range']['x_min'],info['Range']['x_max']],
                            [info['Range']['y_min'],info['Range']['y_max']],
                            [info['Range']['z_min'],info['Range']['z_max']]]

    # Parameters
    kargs = ['MeshDim', 'dF_args', 'Density', 'Polar', 'Title', 'xlabel', 'ylabel', 'zlabel', 'color', 'xScale', 'yScale', 'zScale']
    for k,v in info.items():
        if k in kargs:
            setattr(representation, k, v)

    # Nullcline
    try:
        if nc:=info['nullcline']:
            representation.add_nullclines(**nc)
    except KeyError:
        pass

    # Plot and save
    fig, ax = representation.plot()

    # path = info['path']
    # fig_name = time.strftime('%a%d%b%Y%H%M%SGMT',time.localtime())
    # fig.savefig(path + fig_name +'.svg', transparent=True)

    return fig
    return fig_name + '.svg'