예제 #1
0
파일: EarthModel.py 프로젝트: nyleng/modelr
    def __init__(self,earth_structure, namespace):
        """
        Class for handling earth models.

        :param earth_structure: An EarthStructure JSON dictionary. 
        """

        add_arguments = namespace['add_arguments']
        short_description = namespace.get('short_description',
                                          'No description')

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(earth_structure["arguments"])
        except SendHelp as helper:
            raise SendHelp
        
        self.reflect_file = str(earth_structure["datafile"])
        
        # Load the image data
        if earth_structure.get('update_model', None):
            response = requests.get(earth_structure["image"])

            if os.path.exists(self.reflect_file):
                os.remove(self.reflect_file)

            image = \
              Image.open(StringIO(response.content)).convert("RGB")
            image.load()
            self.image = np.asarray(image, dtype="int32")

            self.units = args.units
            self.depth = args.depth
            self.reflectivity_method = args.reflectivity_method

            self.property_map = {}

            # Keep only a direct map for legacy. Input data has name
            # attribute we are going to ignore
            mapping = earth_structure["mapping"]

            # Make a lookup table for vp. This is terribly
            # inefficient for memory, but quicker than looping
            # dictionaries. There is for sure a better way
            self.vp_lookup = np.zeros((256,256,256))
            for colour in mapping:
                rock = \
                  rock_properties_type(mapping[colour]["property"])

                rgb = colour.split('(')[1].split(')')[0].split(',')
                self.vp_lookup[int(rgb[0]), int(rgb[1]),
                               int(rgb[2])] = rock.vp
                                             
                self.property_map[colour] = rock
예제 #2
0
    def __init__(self, earth_structure, namespace):
        """
        Class for handling earth models.

        :param earth_structure: An EarthStructure JSON dictionary.
        """

        add_arguments = namespace['add_arguments']
        short_description = namespace.get('short_description',
                                          'No description')

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(earth_structure["arguments"])
        except SendHelp:
            raise SendHelp

        self.reflect_file = str(earth_structure["datafile"])

        self.property_map = {}
        # Load the image data
        if earth_structure.get('update_model', None):
            response = requests.get(earth_structure["image"])

            if os.path.exists(self.reflect_file):
                os.remove(self.reflect_file)

            image = Image.open(StringIO(response.content))\
                         .convert("RGB")
            image.load()

            self.image = np.asarray(image, dtype="int32")
            self.units = args.units
            self.depth = args.depth
            self.reflectivity_method = args.reflectivity_method

            # Keep only a direct map for legacy. Input data has name
            # attribute we are going to ignore
            mapping = earth_structure["mapping"]

            # Make a lookup table for vp. This is terribly
            # inefficient for memory, but quicker than looping
            # dictionaries. There is for sure a better way
            self.vp_lookup = np.zeros((256, 256, 256))
            for colour in mapping:
                rock = rock_properties_type(mapping[colour]["property"])
                rock.name = mapping[colour]["name"]

                rgb = colour.split('(')[1].split(')')[0].split(',')
                self.vp_lookup[int(rgb[0]), int(rgb[1]), int(rgb[2])] = rock.vp

                self.property_map[colour] = rock
예제 #3
0
파일: server.py 프로젝트: chookee/modelr
    def run_script_jpg(self, script, script_main, add_arguments,
                       short_description, parameters):
        '''
        Run a script that returns a jpeg

        :param script_main: the main method of the script
        :param add_arguments: poplate an argument parser
        :param short_description: a short description of the script
        :param parameters: the parameters from the get request
        '''
        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(parameters)
        except SendHelp:
            self.send_response(200)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            template = self.server.jenv.get_template('ScriptHelp.html')

            # parameters
            html = template.render(script=script,
                                   parser=parser,
                                   parameters=parameters)
            self.wfile.write(html)
            return
        except ArgumentError as err:
            self.send_response(400)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            self.wfile.write('<p><b>Error:</b> %s</p>' % (err.args[0], ))
            self.wfile.write(parser.help_html)
            return

        jpeg_data = script_main(args)[0]

        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-type', 'image/jpeg')
        self.end_headers()

        self.wfile.write(jpeg_data)

        del jpeg_data
예제 #4
0
    def run_script_jpg(self, script, script_main, add_arguments,
                       short_description, parameters):
        '''
        Run a script that returns a jpeg

        :param script_main: the main method of the script
        :param add_arguments: poplate an argument parser
        :param short_description: a short description of the script
        :param parameters: the parameters from the get request
        '''
        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(parameters)
        except SendHelp:
            self.send_response(200)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            template = self.server.jenv.get_template('ScriptHelp.html')

            # parameters
            html = template.render(script=script, parser=parser,
                                   parameters=parameters)
            self.wfile.write(html)
            return
        except ArgumentError as err:
            self.send_response(400)
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            self.wfile.write('<p><b>Error:</b> %s</p>'
                             % (err.args[0],))
            self.wfile.write(parser.help_html)
            return

        jpeg_data = script_main(args)[0]

        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Content-type', 'image/jpeg')
        self.end_headers()

        self.wfile.write(jpeg_data)

        del jpeg_data
예제 #5
0
파일: ModelrPlot.py 프로젝트: nyleng/modelr
    def __init__(self, plot_json, namespace):

        # Parse additional arguments that may be required by the
        # script

        add_arguments = namespace["add_arguments"]
        short_description = namespace.get("short_description", "No description")

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(plot_json)
        except SendHelp as helper:
            raise SendHelp

        self.args = args
        self.script = namespace["run_script"]
예제 #6
0
    def __init__(self, plot_json, namespace):

        # Parse additional arguments that may be required by the
        # script
        add_arguments = namespace['add_arguments']
        short_description = namespace.get('short_description',
                                          'No description')

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(plot_json)
        except SendHelp:
            raise SendHelp

        self.args = args
        self.script = namespace['run_script']
예제 #7
0
    def __init__(self, seismic_params, namespace):
        """
        Class for handling seismic models.

        :param seismic_params: A SeismicModel JSON dictionary.
        :param namespace: Name space of the modeling script
        """

        # Parse additional arguments that may be required by the
        # script
        
        add_arguments = namespace['add_arguments']
        short_description = namespace.get('short_description',
                                                  'No description')

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(seismic_params)
        except SendHelp as helper:
            raise SendHelp

        self.args = args
        self.script = namespace['run_script']

        self.snr = args.snr

        self.wavelet_model = args.wavelet

        self.f_res = 'octave' #args.f_res
        self.stack = 50 #args.stack

        self.phase = args.phase * np.pi / 180.0
        self.n_sensors = 350 #args.sensor_spacing
        self.dt = 0.002 #args.dt

        self.f = args.f
        
        self.start_f = 8.0 #args.f1
        self.end_f = 100.0 #args.f2


        self.theta1 = 0.0 #args.theta1
        self.theta2 = 45.0 #args.theta2
예제 #8
0
    def __init__(self, seismic_params, namespace):
        """
        Class for handling seismic models.

        :param seismic_params: A SeismicModel JSON dictionary.
        :param namespace: Name space of the modeling script
        """

        # Parse additional arguments that may be required by the
        # script
        add_arguments = namespace['add_arguments']
        short_description = namespace.get('short_description',
                                          'No description')

        parser = URLArgumentParser(short_description)
        add_arguments(parser)
        try:
            args = parser.parse_params(seismic_params)
        except SendHelp:
            raise SendHelp

        self.args = args
        self.script = namespace['run_script']

        self.snr = args.snr

        self.wavelet_model = args.wavelet

        self.f_res = 'octave' # args.f_res
        self.stack = 50 # args.stack

        self.phase = args.phase * np.pi / 180.0
        self.n_sensors = 350 # args.sensor_spacing
        self.dt = 0.002 # args.dt

        self.f = args.f
        self.start_f = 8.0 # args.f1
        self.end_f = 100.0 # args.f2

        self.theta1 = 0.0 # args.theta1
        self.theta2 = 45.0 # args.theta2
예제 #9
0
파일: server.py 프로젝트: chookee/modelr
    def do_GET(self):
        '''
        handle a get request.
        '''

        try:
            uri = urlparse(self.path)
            parameters = parse_qs(uri.query)

            # super dangerous. commenting out
            # if uri.path == '/terminate':
            #    self.terminate()
            #    return

            # returns the script help
            if uri.path == '/script_help.json':

                script = parameters.pop('script', None)
                script_type = parameters.pop('type', None)

                namespace = self.eval_script(script, script_type)
                if namespace is None:
                    self.send_response(400)
                    self.end_headers()

                self.send_response(200)
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Headers',
                                 'X-Request, X-Requested-With')
                self.send_header('Content-type', 'application/json')
                self.end_headers()

                script_main = namespace['run_script']
                add_arguments = namespace['add_arguments']
                short_description = namespace.get('short_description',
                                                  'No description')

                parser = URLArgumentParser(short_description)
                add_arguments(parser)

                self.wfile.write(parser.json_data)

                return

            # list the available scripts
            if uri.path == '/available_scripts.json':
                self.send_response(200)
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Headers',
                                 'X-Request, X-Requested-With')
                self.send_header('Content-type', 'application/json')
                self.end_headers()

                script_type = parameters.pop('type', None)

                all_scripts = self.get_available_scripts(script_type)

                data = json.dumps(all_scripts)

                self.wfile.write(data)
                return

            # Outputs a base64 image and an auxillary json structure
            elif uri.path == '/plot.json':
                parameters = parse_qs(uri.query)
                script = parameters.pop("script", None)
                script_type = parameters.pop("type", None)

                # Get the namespace
                namespace = self.eval_script(script, script_type)
                if namespace is None:
                    return

                plot_generator = ModelrScript(parameters, namespace)

                # Run in sub-process to prevent memory hogging
                p = mp.Process(target=self.run_script_jpg_json,
                               args=(plot_generator, ))
                p.start()
                p.join()
                return

            # Outputs json data
            elif uri.path == '/data.json':
                parameters = parse_qs(uri.query)
                script = parameters.pop("script", None)
                script_type = parameters.pop("type", None)
                print "Running", script, script_type

                payload = json.loads(parameters.pop("payload")[0])
                print payload

                # Get the namespace
                namespace = self.eval_script(script, script_type)
                if namespace is None:
                    return

                # payload = json.parse(parameters["payload"])
                script_main = namespace["run_script"]

                # Run in sub-process to prevent memory hogging
                p = mp.Process(target=self.run_script_json,
                               args=(script_main, payload))
                p.start()
                p.join()

            # Output only an image
            elif uri.path == '/plot.jpeg':
                script = parameters.pop('script', None)
                script_type = parameters.pop('type', None)
                namespace = self.eval_script(script, script_type)
                if namespace is None:
                    return

                script_main = namespace['run_script']
                add_arguments = namespace['add_arguments']
                short_description = namespace.get('short_description',
                                                  'No description')
                # "parameters", parameters
                p = mp.Process(target=self.run_script_jpg,
                               args=(script[0], script_main, add_arguments,
                                     short_description, parameters))
                p.start()
                p.join()

            else:
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_error(404, 'File or Path Not Found: %s' % self.path)
                return

        except Exception:
            self.send_response(400)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            tb = traceback.format_exc().splitlines()

            tb = '</br>\n'.join(tb)

            self.wfile.write('<b>Python Error</b></br>')
            self.wfile.write('<div>')
            self.wfile.write(tb)
            self.wfile.write('</div>')
            raise